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-server-common/src/main/java/org/sonar/server/platform/ServerFileSystemImpl.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.platform; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; public class ServerFileSystemImpl implements ServerFileSystem, org.sonar.api.platform.ServerFileSystem, Startable { private static final Logger LOGGER = LoggerFactory.getLogger(ServerFileSystemImpl.class); private final File homeDir; private final File tempDir; private final File deployDir; private final File uninstallDir; public ServerFileSystemImpl(Configuration config) { this.homeDir = createDir(new File(config.get(PATH_HOME.getKey()).get())); this.tempDir = createDir(new File(config.get(PATH_TEMP.getKey()).get())); File dataDir = createDir(new File(config.get(PATH_DATA.getKey()).get())); this.deployDir = new File(dataDir, "web/deploy"); this.uninstallDir = new File(getTempDir(), "uninstalled-plugins"); } @Override public void start() { LOGGER.info("SonarQube home: " + homeDir.getAbsolutePath()); } @Override public void stop() { // do nothing } @Override public File getHomeDir() { return homeDir; } @Override public File getTempDir() { return tempDir; } @Override public File getDeployedPluginsDir() { return new File(deployDir, "plugins"); } @Override public File getDownloadedPluginsDir() { return new File(getHomeDir(), "extensions/downloads"); } @Override public File getInstalledExternalPluginsDir() { return new File(getHomeDir(), "extensions/plugins"); } @Override public File getInstalledBundledPluginsDir() { return new File(getHomeDir(), "lib/extensions"); } @Override public File getPluginIndex() { return new File(deployDir, "plugins/index.txt"); } @Override public File getUninstalledPluginsDir() { return uninstallDir; } private static File createDir(File dir) { try { FileUtils.forceMkdir(dir); return dir; } catch (IOException e) { throw new IllegalStateException("Fail to create directory " + dir, e); } } }
3,235
28.418182
115
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.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.platform; import java.util.Date; import javax.annotation.CheckForNull; import org.sonar.api.CoreProperties; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.SonarQubeVersion; @ComputeEngineSide @ServerSide public class ServerImpl extends Server { private final Configuration config; private final StartupMetadata state; private final UrlSettings urlSettings; private final SonarQubeVersion version; public ServerImpl(Configuration config, StartupMetadata state, UrlSettings urlSettings, SonarQubeVersion version) { this.config = config; this.state = state; this.urlSettings = urlSettings; this.version = version; } /** * Can be null when server is waiting for migration */ @Override @CheckForNull public String getId() { return config.get(CoreProperties.SERVER_ID).orElse(null); } @Override public String getPermanentServerId() { return getId(); } @Override public String getVersion() { return version.get().toString(); } @Override public Date getStartedAt() { return new Date(state.getStartedAt()); } @Override public String getContextPath() { return urlSettings.getContextPath(); } @Override public String getPublicRootUrl() { return urlSettings.getBaseUrl(); } @Override public boolean isSecured() { return urlSettings.isSecured(); } }
2,371
26.905882
117
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerLifecycleNotifier.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.platform; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Startable; import org.sonar.api.platform.Server; import org.sonar.api.platform.ServerStartHandler; import org.sonar.api.platform.ServerStopHandler; /** * @since 2.2 */ public class ServerLifecycleNotifier implements Startable { private static final Logger LOG = LoggerFactory.getLogger(ServerLifecycleNotifier.class); private final ServerStartHandler[] startHandlers; private final ServerStopHandler[] stopHandlers; private final Server server; public ServerLifecycleNotifier(Server server, @Nullable ServerStartHandler[] startHandlers, @Nullable ServerStopHandler[] stopHandlers) { this.startHandlers = startHandlers != null ? startHandlers : new ServerStartHandler[0]; this.stopHandlers = stopHandlers != null ? stopHandlers : new ServerStopHandler[0]; this.server = server; } @Override public void start() { /* * IMPORTANT : * we want to be sure that handlers are notified when all other services are started. * That's why the class Platform explicitely executes the method notifyStart(), instead of letting the ioc container * choose the startup order. */ } public void notifyStart() { LOG.debug("Notify {} handlers...", ServerStartHandler.class.getSimpleName()); for (ServerStartHandler handler : startHandlers) { handler.onServerStart(server); } } @Override public void stop() { LOG.debug("Notify {} handlers...", ServerStopHandler.class.getSimpleName()); for (ServerStopHandler handler : stopHandlers) { handler.onServerStop(server); } } }
2,551
34.943662
139
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/StartupMetadata.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.platform; import javax.annotation.concurrent.Immutable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ComputeEngineSide @ServerSide @Immutable public class StartupMetadata { private final long startedAt; public StartupMetadata(long startedAt) { this.startedAt = startedAt; } public long getStartedAt() { return startedAt; } }
1,255
29.634146
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/StartupMetadataProvider.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.platform; import org.sonar.api.CoreProperties; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import org.springframework.context.annotation.Bean; import static com.google.common.base.Preconditions.checkState; import static org.apache.commons.lang.StringUtils.isBlank; import static org.sonar.api.CoreProperties.SERVER_STARTTIME; @ComputeEngineSide @ServerSide public class StartupMetadataProvider { @Bean("StartupMetadata") public StartupMetadata provide(System2 system, SonarRuntime runtime, NodeInformation nodeInformation, DbClient dbClient) { if (runtime.getSonarQubeSide() == SonarQubeSide.SERVER && nodeInformation.isStartupLeader()) { return generate(system); } else { return load(dbClient); } } /** * Generate a {@link CoreProperties#SERVER_STARTTIME}. * <p> * Persistence is performed by {@link StartupMetadataPersister}. * </p> */ private static StartupMetadata generate(System2 system) { return new StartupMetadata(system.now()); } /** * Load from database */ private static StartupMetadata load(DbClient dbClient) { try (DbSession dbSession = dbClient.openSession(false)) { String startedAt = selectProperty(dbClient, dbSession, SERVER_STARTTIME); return new StartupMetadata(DateUtils.parseDateTime(startedAt).getTime()); } } private static String selectProperty(DbClient dbClient, DbSession dbSession, String key) { PropertyDto prop = dbClient.propertiesDao().selectGlobalProperty(dbSession, key); checkState(prop != null, "Property %s is missing in database", key); checkState(!isBlank(prop.getValue()), "Property %s is set but empty in database", key); return prop.getValue(); } }
2,861
36.168831
124
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/TempFolderProvider.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.platform; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.sonar.api.impl.utils.DefaultTempFolder; import org.sonar.api.utils.TempFolder; import org.springframework.context.annotation.Bean; public class TempFolderProvider { @Bean("TempFolder") public TempFolder provide(ServerFileSystem fs) { File tempDir = new File(fs.getTempDir(), "tmp"); try { FileUtils.forceMkdir(tempDir); } catch (IOException e) { throw new IllegalStateException("Unable to create temp directory " + tempDir, e); } return new DefaultTempFolder(tempDir); } }
1,491
35.390244
87
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/UrlSettings.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.platform; import org.apache.commons.lang.StringUtils; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.apache.commons.lang.StringUtils.stripEnd; import static org.sonar.api.CoreProperties.SERVER_BASE_URL; import static org.sonar.process.ProcessProperties.Property.WEB_CONTEXT; import static org.sonar.process.ProcessProperties.Property.WEB_HOST; @ComputeEngineSide @ServerSide public class UrlSettings { private static final int DEFAULT_PORT = 9000; private static final int DEFAULT_HTTP_PORT = 80; private static final String ALL_IPS_HOST = "0.0.0.0"; private final Configuration config; // cached, so can't change at runtime private final String contextPath; public UrlSettings(Configuration config) { this.config = config; this.contextPath = stripEnd(config.get(WEB_CONTEXT.getKey()).orElse(""), "/"); } public String getBaseUrl() { String url = config.get(SERVER_BASE_URL).orElse(""); if (isEmpty(url)) { url = computeBaseUrl(); } // Remove trailing slashes return StringUtils.removeEnd(url, "/"); } public String getContextPath() { return contextPath; } public boolean isSecured() { return getBaseUrl().startsWith("https://"); } private String computeBaseUrl() { String host = config.get(WEB_HOST.getKey()).orElse(""); int port = config.getInt("sonar.web.port").orElse(0); String context = config.get(WEB_CONTEXT.getKey()).orElse(""); StringBuilder res = new StringBuilder(); res.append("http://"); appendHost(host, res); appendPort(port, res); appendContext(context, res); return res.toString(); } private static void appendHost(String host, StringBuilder res) { if (isEmpty(host) || ALL_IPS_HOST.equals(host)) { res.append("localhost"); } else { res.append(host); } } private static void appendPort(int port, StringBuilder res) { if (port < 1) { res.append(':').append(DEFAULT_PORT); } else if (port != DEFAULT_HTTP_PORT) { res.append(':').append(port); } } private static void appendContext(String context, StringBuilder res) { if (isNotEmpty(context)) { res.append(context); } } }
3,272
30.776699
82
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/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.platform; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/monitoring/DbSection.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.platform.monitoring; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Map; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import static java.sql.Connection.TRANSACTION_NONE; import static java.sql.Connection.TRANSACTION_READ_COMMITTED; import static java.sql.Connection.TRANSACTION_READ_UNCOMMITTED; import static java.sql.Connection.TRANSACTION_REPEATABLE_READ; import static java.sql.Connection.TRANSACTION_SERIALIZABLE; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; /** * Information about database */ public class DbSection implements SystemInfoSection, Global { private static final Map<Integer, String> ISOLATION_LEVEL_BY_ID = Map.of( TRANSACTION_NONE, "TRANSACTION_NONE", TRANSACTION_READ_UNCOMMITTED, "TRANSACTION_READ_UNCOMMITTED", TRANSACTION_READ_COMMITTED, "TRANSACTION_READ_COMMITTED", TRANSACTION_REPEATABLE_READ, "TRANSACTION_REPEATABLE_READ", TRANSACTION_SERIALIZABLE, "TRANSACTION_SERIALIZABLE"); private final DbClient dbClient; public DbSection(DbClient dbClient) { this.dbClient = dbClient; } @Override public Section toProtobuf() { Section.Builder protobuf = Section.newBuilder(); protobuf.setName("Database"); try (DbSession dbSession = dbClient.openSession(false)) { DatabaseMetaData metadata = dbSession.getConnection().getMetaData(); setAttribute(protobuf, "Database", metadata.getDatabaseProductName()); setAttribute(protobuf, "Database Version", metadata.getDatabaseProductVersion()); setAttribute(protobuf, "Username", metadata.getUserName()); setAttribute(protobuf, "URL", metadata.getURL()); setAttribute(protobuf, "Driver", metadata.getDriverName()); setAttribute(protobuf, "Driver Version", metadata.getDriverVersion()); setAttribute(protobuf, "Default transaction isolation", toTransactionIsolationLevelName(metadata.getDefaultTransactionIsolation())); } catch (SQLException e) { throw new IllegalStateException("Fail to get DB metadata", e); } return protobuf.build(); } private static String toTransactionIsolationLevelName(int level) { return ISOLATION_LEVEL_BY_ID.getOrDefault(level, "Unknown transaction level: " + level); } }
3,312
40.936709
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/monitoring/LoggingSection.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.platform.monitoring; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.SystemInfoUtils; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.log.ServerLogging; @ComputeEngineSide @ServerSide public class LoggingSection implements SystemInfoSection { private final SonarRuntime runtime; private final ServerLogging logging; public LoggingSection(SonarRuntime runtime, ServerLogging logging) { this.runtime = runtime; this.logging = logging; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); if (runtime.getSonarQubeSide() == SonarQubeSide.COMPUTE_ENGINE) { protobuf.setName("Compute Engine Logging"); } else { protobuf.setName("Web Logging"); } SystemInfoUtils.setAttribute(protobuf, "Logs Level", logging.getRootLoggerLevel().name()); SystemInfoUtils.setAttribute(protobuf, "Logs Dir", logging.getLogsDir().getAbsolutePath()); return protobuf.build(); } }
2,120
36.875
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/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.platform.monitoring; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProvider.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.platform.monitoring.cluster; import java.util.Arrays; import java.util.List; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; @ServerSide @ComputeEngineSide public class ProcessInfoProvider implements Startable { /** Used for Hazelcast's distributed queries in cluster mode */ private static ProcessInfoProvider instance; private final List<SystemInfoSection> sections; public ProcessInfoProvider(SystemInfoSection[] sections) { this.sections = Arrays.stream(sections) .filter(section -> !(section instanceof Global)) .toList(); } @Override public void start() { instance = this; } @Override public void stop() { instance = null; } public static ProtobufSystemInfo.SystemInfo provide() { ProtobufSystemInfo.SystemInfo.Builder protobuf = ProtobufSystemInfo.SystemInfo.newBuilder(); if (instance != null) { instance.sections.forEach(section -> protobuf.addSections(section.toProtobuf())); } return protobuf.build(); } }
2,095
32.269841
96
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/monitoring/cluster/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.platform.monitoring.cluster; import javax.annotation.ParametersAreNonnullByDefault;
984
40.041667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/serverid/JdbcUrlSanitizer.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.platform.serverid; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.commons.lang.StringUtils; import org.sonar.api.utils.KeyValueFormat; public class JdbcUrlSanitizer { private static final String SQLSERVER_PREFIX = "jdbc:sqlserver://"; public String sanitize(String jdbcUrl) { String result; if (jdbcUrl.startsWith(SQLSERVER_PREFIX)) { result = sanitizeSqlServerUrl(jdbcUrl); } else { // remove query parameters, they don't aim to reference the schema result = StringUtils.substringBefore(jdbcUrl, "?"); } return StringUtils.lowerCase(result, Locale.ENGLISH); } /** * Deal with this strange URL format: * https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url * https://docs.microsoft.com/en-us/sql/connect/jdbc/setting-the-connection-properties */ private static String sanitizeSqlServerUrl(String jdbcUrl) { StringBuilder result = new StringBuilder(); result.append(SQLSERVER_PREFIX); String host; if (jdbcUrl.contains(";")) { host = StringUtils.substringBetween(jdbcUrl, SQLSERVER_PREFIX, ";"); } else { host = StringUtils.substringAfter(jdbcUrl, SQLSERVER_PREFIX); } String queryString = StringUtils.substringAfter(jdbcUrl, ";"); Map<String, String> parameters = KeyValueFormat.parse(queryString); Optional<String> server = firstValue(parameters, "serverName", "servername", "server"); if (server.isPresent()) { result.append(server.get()); } else { result.append(StringUtils.substringBefore(host, ":")); } Optional<String> port = firstValue(parameters, "portNumber", "port"); if (port.isPresent()) { result.append(':').append(port.get()); } else if (host.contains(":")) { result.append(':').append(StringUtils.substringAfter(host, ":")); } Optional<String> database = firstValue(parameters, "databaseName", "database"); database.ifPresent(s -> result.append('/').append(s)); return result.toString(); } private static Optional<String> firstValue(Map<String, String> map, String... keys) { return Arrays.stream(keys) .map(map::get) .filter(Objects::nonNull) .findFirst(); } }
3,175
35.090909
91
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/serverid/ServerIdChecksum.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.platform.serverid; import org.apache.commons.codec.digest.DigestUtils; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; @ServerSide @ComputeEngineSide public class ServerIdChecksum { private final Configuration config; private final JdbcUrlSanitizer jdbcUrlSanitizer; public ServerIdChecksum(Configuration config, JdbcUrlSanitizer jdbcUrlSanitizer) { this.config = config; this.jdbcUrlSanitizer = jdbcUrlSanitizer; } public String computeFor(String serverId) { String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL")); return DigestUtils.sha256Hex(serverId + "|" + jdbcUrlSanitizer.sanitize(jdbcUrl)); } }
1,710
35.404255
116
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/serverid/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.platform.serverid; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/plugins/InstalledPluginReferentialFactory.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.plugins; import org.sonar.api.Startable; import org.sonar.core.platform.PluginRepository; import org.sonar.updatecenter.common.PluginReferential; public class InstalledPluginReferentialFactory implements Startable { private final PluginRepository pluginRepository; private PluginReferential installedPluginReferential; public InstalledPluginReferentialFactory(PluginRepository pluginRepository) { this.pluginRepository = pluginRepository; } @Override public void start() { try { init(); } catch (Exception e) { throw new IllegalStateException("Unable to load installed plugins", e); } } @Override public void stop() { // nothing to do } public PluginReferential getInstalledPluginReferential() { return installedPluginReferential; } private void init() { installedPluginReferential = PluginReferentialMetadataConverter.getInstalledPluginReferential(pluginRepository.getPluginInfos()); } }
1,834
30.637931
133
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/plugins/PluginReferentialMetadataConverter.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.plugins; import com.google.common.base.Function; import com.google.common.collect.Collections2; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.PluginManifest; import org.sonar.updatecenter.common.PluginReferential; import org.sonar.updatecenter.common.PluginReferentialManifestConverter; import org.sonar.updatecenter.common.Version; import javax.annotation.Nonnull; import java.util.Collection; import java.util.List; import static com.google.common.collect.Lists.newArrayList; public class PluginReferentialMetadataConverter { private PluginReferentialMetadataConverter() { // Only static call } public static PluginReferential getInstalledPluginReferential(Collection<PluginInfo> infos) { List<PluginManifest> pluginManifestList = getPluginManifestList(infos); return PluginReferentialManifestConverter.fromPluginManifests(pluginManifestList); } private static List<PluginManifest> getPluginManifestList(Collection<PluginInfo> metadata) { List<PluginManifest> pluginManifestList = newArrayList(); for (PluginInfo plugin : metadata) { pluginManifestList.add(toPluginManifest(plugin)); } return pluginManifestList; } private static PluginManifest toPluginManifest(PluginInfo metadata) { PluginManifest pluginManifest = new PluginManifest(); pluginManifest.setKey(metadata.getKey()); pluginManifest.setName(metadata.getName()); Version version = metadata.getVersion(); if (version != null) { pluginManifest.setVersion(version.getName()); } pluginManifest.setDescription(metadata.getDescription()); pluginManifest.setMainClass(metadata.getMainClass()); pluginManifest.setOrganization(metadata.getOrganizationName()); pluginManifest.setOrganizationUrl(metadata.getOrganizationUrl()); pluginManifest.setLicense(metadata.getLicense()); pluginManifest.setHomepage(metadata.getHomepageUrl()); pluginManifest.setIssueTrackerUrl(metadata.getIssueTrackerUrl()); pluginManifest.setBasePlugin(metadata.getBasePlugin()); pluginManifest.setRequirePlugins(Collections2.transform(metadata.getRequiredPlugins(), RequiredPluginToString.INSTANCE).toArray( new String[metadata.getRequiredPlugins().size()])); return pluginManifest; } private enum RequiredPluginToString implements Function<PluginInfo.RequiredPlugin, String> { INSTANCE; @Override public String apply(@Nonnull PluginInfo.RequiredPlugin requiredPlugin) { return requiredPlugin.toString(); } } }
3,405
38.604651
132
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/plugins/PluginRequirementsValidator.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.plugins; import com.google.common.base.Strings; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.Version; /** * Checks plugins dependency requirements * @param <T> */ public class PluginRequirementsValidator<T extends PluginInfo> { private static final Logger LOG = LoggerFactory.getLogger(PluginRequirementsValidator.class); private final Map<String, T> allPluginsByKeys; PluginRequirementsValidator(Map<String, T> allPluginsByKeys) { this.allPluginsByKeys = allPluginsByKeys; } /** * Utility method that removes the plugins that are not compatible with current environment. */ public static <T extends PluginInfo> void unloadIncompatiblePlugins(Map<String, T> pluginsByKey) { // loop as long as the previous loop ignored some plugins. That allows to support dependencies // on many levels, for example D extends C, which extends B, which requires A. If A is not installed, // then B, C and D must be ignored. That's not possible to achieve this algorithm with a single iteration over plugins. var validator = new PluginRequirementsValidator<>(pluginsByKey); Set<String> removedKeys = new HashSet<>(); do { removedKeys.clear(); for (T plugin : pluginsByKey.values()) { if (!validator.isCompatible(plugin)) { removedKeys.add(plugin.getKey()); } } for (String removedKey : removedKeys) { pluginsByKey.remove(removedKey); } } while (!removedKeys.isEmpty()); } boolean isCompatible(T plugin) { if (!Strings.isNullOrEmpty(plugin.getBasePlugin()) && !allPluginsByKeys.containsKey(plugin.getBasePlugin())) { // it extends a plugin that is not installed LOG.warn("Plugin {} [{}] is ignored because its base plugin [{}] is not installed", plugin.getName(), plugin.getKey(), plugin.getBasePlugin()); return false; } for (PluginInfo.RequiredPlugin requiredPlugin : plugin.getRequiredPlugins()) { PluginInfo installedRequirement = allPluginsByKeys.get(requiredPlugin.getKey()); if (installedRequirement == null) { // it requires a plugin that is not installed LOG.warn("Plugin {} [{}] is ignored because the required plugin [{}] is not installed", plugin.getName(), plugin.getKey(), requiredPlugin.getKey()); return false; } Version installedRequirementVersion = installedRequirement.getVersion(); if (installedRequirementVersion != null && requiredPlugin.getMinimalVersion().compareToIgnoreQualifier(installedRequirementVersion) > 0) { // it requires a more recent version LOG.warn("Plugin {} [{}] is ignored because the version {} of required plugin [{}] is not installed", plugin.getName(), plugin.getKey(), requiredPlugin.getMinimalVersion(), requiredPlugin.getKey()); return false; } } return true; } }
3,888
41.271739
156
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/plugins/ServerExtensionInstaller.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.plugins; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import org.sonar.api.Plugin; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.internal.PluginContextImpl; import org.sonar.api.utils.AnnotationUtils; import org.sonar.core.platform.ExtensionContainer; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Set; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Loads the plugins server extensions and injects them to DI container */ public abstract class ServerExtensionInstaller { private final Configuration configuration; private final SonarRuntime sonarRuntime; private final PluginRepository pluginRepository; private final Set<Class<? extends Annotation>> supportedAnnotationTypes; protected ServerExtensionInstaller(Configuration configuration, SonarRuntime sonarRuntime, PluginRepository pluginRepository, Collection<Class<? extends Annotation>> supportedAnnotationTypes) { requireNonNull(supportedAnnotationTypes, "At least one supported annotation type must be specified"); this.configuration = configuration; this.sonarRuntime = sonarRuntime; this.pluginRepository = pluginRepository; this.supportedAnnotationTypes = ImmutableSet.copyOf(supportedAnnotationTypes); } public void installExtensions(ExtensionContainer container) { ListMultimap<PluginInfo, Object> installedExtensionsByPlugin = ArrayListMultimap.create(); for (PluginInfo pluginInfo : pluginRepository.getPluginInfos()) { try { String pluginKey = pluginInfo.getKey(); Plugin plugin = pluginRepository.getPluginInstance(pluginKey); container.addExtension(pluginInfo, plugin); Plugin.Context context = new PluginContextImpl.Builder() .setSonarRuntime(sonarRuntime) .setBootConfiguration(configuration) .build(); plugin.define(context); for (Object extension : context.getExtensions()) { if (installExtension(container, pluginInfo, extension) != null) { installedExtensionsByPlugin.put(pluginInfo, extension); } else { container.declareExtension(pluginInfo, extension); } } } catch (Throwable e) { // catch Throwable because we want to catch Error too (IncompatibleClassChangeError, ...) throw new IllegalStateException(format("Fail to load plugin %s [%s]", pluginInfo.getName(), pluginInfo.getKey()), e); } } } private Object installExtension(ExtensionContainer container, PluginInfo pluginInfo, Object extension) { for (Class<? extends Annotation> supportedAnnotationType : supportedAnnotationTypes) { if (AnnotationUtils.getAnnotation(extension, supportedAnnotationType) != null) { container.addExtension(pluginInfo, extension); return extension; } } return null; } }
4,012
40.371134
127
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/plugins/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.plugins; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/project/DefaultBranchNameResolver.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.project; import org.sonar.api.config.Configuration; import static org.sonar.core.config.CorePropertyDefinitions.SONAR_PROJECTCREATION_MAINBRANCHNAME; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class DefaultBranchNameResolver { Configuration configuration; public DefaultBranchNameResolver(Configuration configuration) { this.configuration = configuration; } public String getEffectiveMainBranchName() { return configuration.get(SONAR_PROJECTCREATION_MAINBRANCHNAME).orElse(DEFAULT_MAIN_BRANCH_NAME); } }
1,433
35.769231
100
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/project/Project.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.project; import java.util.List; import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import static java.util.Collections.emptyList; @Immutable public class Project { private final String uuid; private final String key; private final String name; private final String description; private final List<String> tags; public Project(String uuid, String key, String name, @Nullable String description, List<String> tags) { this.uuid = uuid; this.key = key; this.name = name; this.description = description; this.tags = tags; } /** * Should use {@link org.sonar.server.project.Project#fromProjectDtoWithTags(org.sonar.db.project.ProjectDto)} instead */ @Deprecated(since = "10.2") public static Project from(ComponentDto project) { return new Project(project.uuid(), project.getKey(), project.name(), project.description(), emptyList()); } public static Project fromProjectDtoWithTags(ProjectDto project) { return new Project(project.getUuid(), project.getKey(), project.getName(), project.getDescription(), project.getTags()); } public static Project from(EntityDto entityDto) { return new Project(entityDto.getUuid(), entityDto.getKey(), entityDto.getName(), entityDto.getDescription(), emptyList()); } /** * Always links to a row that exists in database. */ public String getUuid() { return uuid; } /** * Always links to a row that exists in database. */ public String getKey() { return key; } public String getName() { return name; } public String getDescription() { return description; } public List<String> getTags() { return tags; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Project project = (Project) o; return uuid.equals(project.uuid) && key.equals(project.key) && name.equals(project.name); } @Override public int hashCode() { return Objects.hash(uuid, key, name); } @Override public String toString() { StringBuilder sb = new StringBuilder("Project{"); sb.append("uuid='").append(uuid).append('\''); sb.append(", key='").append(key).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", description=").append(toString(this.description)); sb.append('}'); return sb.toString(); } private static String toString(@Nullable String s) { if (s == null) { return null; } return '\'' + s + '\''; } }
3,621
27.077519
126
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/project/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.project; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalComponentProperties.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.property; /** * List of internal component property keys */ public class InternalComponentProperties { public static final String PORTFOLIO_REFRESH_STATE = "portfolio.refresh.state"; private InternalComponentProperties() { // Static constants only } }
1,135
33.424242
81
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalProperties.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.property; import java.util.Optional; import javax.annotation.Nullable; /** * Allows to read and write internal properties. */ public interface InternalProperties { String SERVER_ID_CHECKSUM = "server.idChecksum"; /** * Compute Engine is pausing/paused if property value is "true". */ String COMPUTE_ENGINE_PAUSE = "ce.pause"; String BITBUCKETCLOUD_APP_SHAREDSECRET = "bbc.app.sharedSecret"; /** * First installation date */ String INSTALLATION_DATE = "installation.date"; /** * first installation SQ version */ String INSTALLATION_VERSION = "installation.version"; /** * Default permission templates */ String DEFAULT_PROJECT_TEMPLATE = "defaultTemplate.prj"; String DEFAULT_PORTFOLIO_TEMPLATE = "defaultTemplate.port"; String DEFAULT_APPLICATION_TEMPLATE = "defaultTemplate.app"; String DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL = "default.admin.cred"; /** * Read the value of the specified property. * * @return {@link Optional#empty()} if the property does not exist, an empty string if the property is empty, * otherwise the value of the property as a String. * * @throws IllegalArgumentException if {@code propertyKey} is {@code null} or empty */ Optional<String> read(String propertyKey); /** * Write the value of the specified property. * <p> * {@code null} and empty string are valid values which will persist the specified property as empty. * </p> * * @throws IllegalArgumentException if {@code propertyKey} is {@code null} or empty */ void write(String propertyKey, @Nullable String value); }
2,490
30.935897
111
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/property/InternalPropertiesImpl.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.property; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static com.google.common.base.Preconditions.checkArgument; /** * A cache-less implementation of {@link InternalProperties} reading and writing to DB table INTERNAL_PROPERTIES. */ public class InternalPropertiesImpl implements InternalProperties { private final DbClient dbClient; public InternalPropertiesImpl(DbClient dbClient) { this.dbClient = dbClient; } @Override public Optional<String> read(String propertyKey) { checkPropertyKey(propertyKey); try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.internalPropertiesDao().selectByKey(dbSession, propertyKey); } } @Override public void write(String propertyKey, @Nullable String value) { checkPropertyKey(propertyKey); try (DbSession dbSession = dbClient.openSession(false)) { if (value == null || value.isEmpty()) { dbClient.internalPropertiesDao().saveAsEmpty(dbSession, propertyKey); } else { dbClient.internalPropertiesDao().save(dbSession, propertyKey, value); } dbSession.commit(); } } private static void checkPropertyKey(@Nullable String propertyKey) { checkArgument(propertyKey != null && !propertyKey.isEmpty(), "property key can't be null nor empty"); } }
2,262
32.776119
113
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/property/MapInternalProperties.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.property; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; /** * Map based implementation of {@link InternalProperties} to be used for unit testing. */ public class MapInternalProperties implements InternalProperties { private final Map<String, String> values = new HashMap<>(1); @Override public Optional<String> read(String propertyKey) { checkPropertyKey(propertyKey); return Optional.ofNullable(values.get(propertyKey)); } @Override public void write(String propertyKey, @Nullable String value) { checkPropertyKey(propertyKey); values.put(propertyKey, value); } private static void checkPropertyKey(@Nullable String propertyKey) { checkArgument(propertyKey != null && !propertyKey.isEmpty(), "property key can't be null nor empty"); } }
1,781
33.941176
105
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/property/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.property; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/Condition.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.qualitygate; import java.util.Objects; import java.util.stream.Stream; import javax.annotation.concurrent.Immutable; import org.sonar.db.qualitygate.QualityGateConditionDto; import static java.util.Objects.requireNonNull; @Immutable public class Condition { private final String metricKey; private final Operator operator; private final String errorThreshold; private final boolean onLeakPeriod; public Condition(String metricKey, Operator operator, String errorThreshold) { this.metricKey = requireNonNull(metricKey, "metricKey can't be null"); this.operator = requireNonNull(operator, "operator can't be null"); this.errorThreshold = requireNonNull(errorThreshold, "errorThreshold can't be null"); this.onLeakPeriod = metricKey.startsWith("new_"); } public String getMetricKey() { return metricKey; } public boolean isOnLeakPeriod() { return onLeakPeriod; } public Operator getOperator() { return operator; } public String getErrorThreshold() { return errorThreshold; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Condition condition = (Condition) o; return Objects.equals(metricKey, condition.metricKey) && operator == condition.operator && Objects.equals(errorThreshold, condition.errorThreshold); } @Override public int hashCode() { return Objects.hash(metricKey, operator, errorThreshold); } @Override public String toString() { return "Condition{" + "metricKey='" + metricKey + '\'' + ", operator=" + operator + ", errorThreshold=" + toString(errorThreshold) + '}'; } private static String toString(String errorThreshold) { return '\'' + errorThreshold + '\''; } public enum Operator { GREATER_THAN(QualityGateConditionDto.OPERATOR_GREATER_THAN), LESS_THAN(QualityGateConditionDto.OPERATOR_LESS_THAN); private final String dbValue; Operator(String dbValue) { this.dbValue = dbValue; } public String getDbValue() { return dbValue; } public static Operator fromDbValue(String s) { return Stream.of(values()) .filter(o -> o.getDbValue().equals(s)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unsupported operator db value: " + s)); } public static boolean isValid(String s) { return Stream.of(values()) .anyMatch(o -> o.getDbValue().equals(s)); } } }
3,426
27.558333
96
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionComparator.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.qualitygate; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; 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.NEW_COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_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_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; /** * Sorts conditions, first based on an hardcoded list of metric keys, then alphabetically by metric key. */ public class ConditionComparator<T> implements Comparator<T> { private static final List<String> CONDITIONS_ORDER = Arrays.asList(NEW_RELIABILITY_RATING_KEY, RELIABILITY_RATING_KEY, NEW_SECURITY_RATING_KEY, SECURITY_RATING_KEY, NEW_MAINTAINABILITY_RATING_KEY, SQALE_RATING_KEY, NEW_COVERAGE_KEY, COVERAGE_KEY, NEW_DUPLICATED_LINES_DENSITY_KEY, DUPLICATED_LINES_DENSITY_KEY); private static final Map<String, Integer> CONDITIONS_ORDER_IDX = IntStream.range(0, CONDITIONS_ORDER.size()).boxed() .collect(Collectors.toMap(CONDITIONS_ORDER::get, x -> x)); private final Function<T, String> metricKeyExtractor; public ConditionComparator(Function<T, String> metricKeyExtractor) { this.metricKeyExtractor = metricKeyExtractor; } @Override public int compare(T c1, T c2) { Function<T, Integer> byList = c -> CONDITIONS_ORDER_IDX.getOrDefault(metricKeyExtractor.apply(c), Integer.MAX_VALUE); return Comparator.comparing(byList).thenComparing(metricKeyExtractor).compare(c1, c2); } }
2,956
45.936508
121
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionEvaluator.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.qualitygate; import java.util.EnumSet; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.api.measures.Metric.ValueType; import org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Optional.of; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.MILLISEC; import static org.sonar.api.measures.Metric.ValueType.PERCENT; import static org.sonar.api.measures.Metric.ValueType.RATING; import static org.sonar.api.measures.Metric.ValueType.WORK_DUR; class ConditionEvaluator { private static final Set<ValueType> NUMERICAL_TYPES = EnumSet.of(INT, RATING, FLOAT, MILLISEC, PERCENT, WORK_DUR); private ConditionEvaluator() { // prevent instantiation } /** * Evaluates the condition for the specified measure */ static EvaluatedCondition evaluate(Condition condition, QualityGateEvaluator.Measures measures) { Optional<QualityGateEvaluator.Measure> measure = measures.get(condition.getMetricKey()); if (measure.isEmpty()) { return new EvaluatedCondition(condition, EvaluationStatus.OK, null); } Optional<Comparable> value = getMeasureValue(condition, measure.get()); if (value.isEmpty()) { return new EvaluatedCondition(condition, EvaluationStatus.OK, null); } ValueType type = measure.get().getType(); return evaluateCondition(condition, type, value.get()) .orElseGet(() -> new EvaluatedCondition(condition, EvaluationStatus.OK, value.get().toString())); } /** * Evaluates the error condition. Returns empty if threshold or measure value is not defined. */ private static Optional<EvaluatedCondition> evaluateCondition(Condition condition, ValueType type, Comparable value) { Comparable threshold = getThreshold(condition, type); if (reachThreshold(value, threshold, condition)) { return of(new EvaluatedCondition(condition, EvaluationStatus.ERROR, value.toString())); } return Optional.empty(); } private static Comparable getThreshold(Condition condition, ValueType valueType) { String valString = condition.getErrorThreshold(); try { return switch (valueType) { case INT, RATING -> parseInteger(valString); case MILLISEC, WORK_DUR -> Long.parseLong(valString); case FLOAT, PERCENT -> Double.parseDouble(valString); case LEVEL -> valueType; default -> throw new IllegalArgumentException(format("Unsupported value type %s. Cannot convert condition value", valueType)); }; } catch (NumberFormatException badValueFormat) { throw new IllegalArgumentException(format( "Quality Gate: unable to parse threshold '%s' to compare against %s", valString, condition.getMetricKey())); } } private static Optional<Comparable> getMeasureValue(Condition condition, QualityGateEvaluator.Measure measure) { if (condition.isOnLeakPeriod()) { return Optional.ofNullable(getLeakValue(measure)); } return Optional.ofNullable(getValue(measure)); } @CheckForNull private static Comparable getValue(QualityGateEvaluator.Measure measure) { if (NUMERICAL_TYPES.contains(measure.getType())) { return measure.getValue().isPresent() ? getNumericValue(measure.getType(), measure.getValue().getAsDouble()) : null; } checkArgument(ValueType.LEVEL.equals(measure.getType()), "Condition is not allowed for type %s" , measure.getType()); return measure.getStringValue().orElse(null); } @CheckForNull private static Comparable getLeakValue(QualityGateEvaluator.Measure measure) { if (NUMERICAL_TYPES.contains(measure.getType())) { return measure.getValue().isPresent() ? getNumericValue(measure.getType(), measure.getValue().getAsDouble()) : null; } throw new IllegalArgumentException("Condition on leak period is not allowed for type " + measure.getType()); } private static Comparable getNumericValue(ValueType type, double value) { return switch (type) { case INT, RATING -> (int) value; case FLOAT, PERCENT -> value; case MILLISEC, WORK_DUR -> (long) value; default -> throw new IllegalArgumentException("Condition on numeric value is not allowed for type " + type); }; } private static int parseInteger(String value) { return value.contains(".") ? Integer.parseInt(value.substring(0, value.indexOf('.'))) : Integer.parseInt(value); } private static boolean reachThreshold(Comparable measureValue, Comparable threshold, Condition condition) { int comparison = measureValue.compareTo(threshold); switch (condition.getOperator()) { case GREATER_THAN: return comparison > 0; case LESS_THAN: return comparison < 0; default: throw new IllegalArgumentException(format("Unsupported operator '%s'", condition.getOperator())); } } }
5,960
39.55102
134
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/EvaluatedCondition.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.qualitygate; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import static java.util.Objects.requireNonNull; @Immutable public class EvaluatedCondition { private final Condition condition; private final EvaluationStatus status; @Nullable private final String value; public EvaluatedCondition(Condition condition, EvaluationStatus status, @Nullable String value) { this.condition = requireNonNull(condition, "condition can't be null"); this.status = requireNonNull(status, "status can't be null"); this.value = value; } public Condition getCondition() { return condition; } public EvaluationStatus getStatus() { return status; } public Optional<String> getValue() { return Optional.ofNullable(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EvaluatedCondition that = (EvaluatedCondition) o; return Objects.equals(condition, that.condition) && status == that.status && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(condition, status, value); } @Override public String toString() { return "EvaluatedCondition{" + "condition=" + condition + ", status=" + status + ", value=" + (value == null ? null : ('\'' + value + '\'')) + '}'; } /** * Quality gate condition evaluation status. */ public enum EvaluationStatus { /** * No measure found or measure had no value. The condition has not been evaluated and therefor ignored in * the computation of the Quality Gate status. */ NO_VALUE, /** * Condition evaluated as OK, error thresholds hasn't been reached. */ OK, /** * Condition evaluated as ERROR, error thresholds has been reached. */ ERROR } }
2,868
27.405941
109
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/EvaluatedQualityGate.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.qualitygate; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.measures.Metric; import org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; @Immutable public class EvaluatedQualityGate { private final QualityGate qualityGate; private final Metric.Level status; private final Collection<EvaluatedCondition> evaluatedConditions; private final boolean ignoredConditionsOnSmallChangeset; private EvaluatedQualityGate(QualityGate qualityGate, Metric.Level status, Collection<EvaluatedCondition> evaluatedConditions, boolean ignoredConditionsOnSmallChangeset) { this.qualityGate = requireNonNull(qualityGate, "qualityGate can't be null"); this.status = requireNonNull(status, "status can't be null"); this.evaluatedConditions = evaluatedConditions; this.ignoredConditionsOnSmallChangeset = ignoredConditionsOnSmallChangeset; } public QualityGate getQualityGate() { return qualityGate; } public Metric.Level getStatus() { return status; } public Collection<EvaluatedCondition> getEvaluatedConditions() { return evaluatedConditions; } public boolean hasIgnoredConditionsOnSmallChangeset() { return ignoredConditionsOnSmallChangeset; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EvaluatedQualityGate that = (EvaluatedQualityGate) o; return Objects.equals(qualityGate, that.qualityGate) && status == that.status && Objects.equals(evaluatedConditions, that.evaluatedConditions); } @Override public int hashCode() { return Objects.hash(qualityGate, status, evaluatedConditions); } @Override public String toString() { return "EvaluatedQualityGate{" + "qualityGate=" + qualityGate + ", status=" + status + ", evaluatedConditions=" + evaluatedConditions + '}'; } public static final class Builder { private QualityGate qualityGate; private Metric.Level status; private final Map<Condition, EvaluatedCondition> evaluatedConditions = new LinkedHashMap<>(); private boolean ignoredConditionsOnSmallChangeset = false; private Builder() { // use static factory method } public Builder setQualityGate(QualityGate qualityGate) { this.qualityGate = qualityGate; return this; } public Builder setStatus(Metric.Level status) { this.status = status; return this; } public Builder setIgnoredConditionsOnSmallChangeset(boolean b) { this.ignoredConditionsOnSmallChangeset = b; return this; } public Builder addEvaluatedCondition(Condition condition, EvaluationStatus status, @Nullable String value) { evaluatedConditions.put(condition, new EvaluatedCondition(condition, status, value)); return this; } public Builder addEvaluatedCondition(EvaluatedCondition c) { evaluatedConditions.put(c.getCondition(), c); return this; } public Set<EvaluatedCondition> getEvaluatedConditions() { return ImmutableSet.copyOf(evaluatedConditions.values()); } public EvaluatedQualityGate build() { checkEvaluatedConditions(qualityGate, evaluatedConditions); List<EvaluatedCondition> sortedEvaluatedConditions = new ArrayList<>(evaluatedConditions.values()); sortedEvaluatedConditions.sort(new ConditionComparator<>(c -> c.getCondition().getMetricKey())); return new EvaluatedQualityGate( this.qualityGate, this.status, sortedEvaluatedConditions, ignoredConditionsOnSmallChangeset); } private static void checkEvaluatedConditions(QualityGate qualityGate, Map<Condition, EvaluatedCondition> evaluatedConditions) { Set<Condition> conditions = qualityGate.getConditions(); Set<Condition> conditionsNotEvaluated = conditions.stream() .filter(c -> !evaluatedConditions.containsKey(c)) .collect(Collectors.toSet()); checkArgument(conditionsNotEvaluated.isEmpty(), "Evaluation missing for the following conditions: %s", conditionsNotEvaluated); Set<Condition> unknownConditions = evaluatedConditions.keySet().stream() .filter(c -> !conditions.contains(c)) .collect(Collectors.toSet()); checkArgument(unknownConditions.isEmpty(), "Evaluation provided for unknown conditions: %s", unknownConditions); } } }
5,791
33.891566
173
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGate.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.qualitygate; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.concurrent.Immutable; import static java.util.Objects.requireNonNull; @Immutable public class QualityGate { private final String id; private final String name; private final Set<Condition> conditions; public QualityGate(String id, String name, Set<Condition> conditions) { this.id = requireNonNull(id, "id can't be null"); this.name = requireNonNull(name, "name can't be null"); this.conditions = requireNonNull(conditions, "conditions can't be null") .stream() .map(c -> requireNonNull(c, "condition can't be null")) .collect(Collectors.toSet()); } public String getId() { return id; } public String getName() { return name; } public Set<Condition> getConditions() { return conditions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QualityGate that = (QualityGate) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(conditions, that.conditions); } @Override public int hashCode() { return Objects.hash(id, name, conditions); } @Override public String toString() { return "QualityGate{" + "id=" + id + ", name='" + name + '\'' + ", conditions=" + conditions + '}'; } }
2,365
27.166667
76
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateEvaluator.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.qualitygate; import java.util.Optional; import java.util.OptionalDouble; import java.util.Set; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.api.server.ServerSide; @ComputeEngineSide @ServerSide public interface QualityGateEvaluator { /** * @param measures must provide the measures related to the metrics * defined by {@link #getMetricKeys(QualityGate)} */ EvaluatedQualityGate evaluate(QualityGate gate, Measures measures, Configuration configuration); /** * Keys of the metrics involved in the computation of gate status. * It may include metrics that are not part of conditions, * for instance "new_lines" for the circuit-breaker on * small changesets. */ Set<String> getMetricKeys(QualityGate gate); interface Measures { Optional<Measure> get(String metricKey); } interface Measure { Metric.ValueType getType(); OptionalDouble getValue(); Optional<String> getStringValue(); } }
1,926
31.116667
98
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateEvaluatorImpl.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.qualitygate; import com.google.common.collect.ImmutableSet; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric.Level; import org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus; import static java.util.stream.Collectors.toSet; public class QualityGateEvaluatorImpl implements QualityGateEvaluator { public static final int MAXIMUM_NEW_LINES_FOR_SMALL_CHANGESETS = 20; /** * Some metrics will be ignored on very small change sets. */ public static final Set<String> METRICS_TO_IGNORE_ON_SMALL_CHANGESETS = ImmutableSet.of( CoreMetrics.NEW_COVERAGE_KEY, CoreMetrics.NEW_LINE_COVERAGE_KEY, CoreMetrics.NEW_BRANCH_COVERAGE_KEY, CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY, CoreMetrics.NEW_DUPLICATED_LINES_KEY, CoreMetrics.NEW_BLOCKS_DUPLICATED_KEY); @Override public EvaluatedQualityGate evaluate(QualityGate gate, Measures measures, Configuration configuration) { EvaluatedQualityGate.Builder result = EvaluatedQualityGate.newBuilder() .setQualityGate(gate); boolean ignoreSmallChanges = configuration.getBoolean(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES).orElse(true); boolean isSmallChangeset = ignoreSmallChanges && isSmallChangeset(measures); gate.getConditions().forEach(condition -> { String metricKey = condition.getMetricKey(); EvaluatedCondition evaluation = ConditionEvaluator.evaluate(condition, measures); if (isSmallChangeset && evaluation.getStatus() != EvaluationStatus.OK && METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricKey)) { result.addEvaluatedCondition(new EvaluatedCondition(evaluation.getCondition(), EvaluationStatus.OK, evaluation.getValue().orElse(null))); result.setIgnoredConditionsOnSmallChangeset(true); } else { result.addEvaluatedCondition(evaluation); } }); result.setStatus(overallStatusOf(result.getEvaluatedConditions())); return result.build(); } @Override public Set<String> getMetricKeys(QualityGate gate) { Set<String> metricKeys = new HashSet<>(); metricKeys.add(CoreMetrics.NEW_LINES_KEY); for (Condition condition : gate.getConditions()) { metricKeys.add(condition.getMetricKey()); } return metricKeys; } private static boolean isSmallChangeset(Measures measures) { Optional<Measure> newLines = measures.get(CoreMetrics.NEW_LINES_KEY); return newLines.isPresent() && newLines.get().getValue().isPresent() && newLines.get().getValue().getAsDouble() < MAXIMUM_NEW_LINES_FOR_SMALL_CHANGESETS; } private static Level overallStatusOf(Set<EvaluatedCondition> conditions) { Set<EvaluationStatus> statuses = conditions.stream() .map(EvaluatedCondition::getStatus) .collect(toSet()); if (statuses.contains(EvaluationStatus.ERROR)) { return Level.ERROR; } return Level.OK; } }
3,926
37.881188
145
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateFinder.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.qualitygate; import java.util.Optional; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; public class QualityGateFinder { private final DbClient dbClient; public QualityGateFinder(DbClient dbClient) { this.dbClient = dbClient; } public QualityGateData getEffectiveQualityGate(DbSession dbSession, ProjectDto projectDto) { return getEffectiveQualityGate(dbSession, projectDto.getUuid()); } public QualityGateData getEffectiveQualityGate(DbSession dbSession, String projectUuid) { Optional<QualityGateData> res = getQualityGateForProject(dbSession, projectUuid); if (res.isPresent()) { return res.get(); } QualityGateDto defaultQualityGate = getDefault(dbSession); return new QualityGateData(defaultQualityGate, true); } private Optional<QualityGateData> getQualityGateForProject(DbSession dbSession, String projectUuid) { return dbClient.projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, projectUuid) .map(qualityGateUuid -> dbClient.qualityGateDao().selectByUuid(dbSession, qualityGateUuid)) .map(qualityGateDto -> new QualityGateData(qualityGateDto, false)); } public QualityGateDto getDefault(DbSession dbSession) { return Optional.ofNullable(dbClient.qualityGateDao().selectDefault(dbSession)).orElseThrow(() -> new IllegalStateException("Default quality gate is missing")); } public static class QualityGateData { private final String uuid; private final String name; private final boolean isDefault; private final boolean builtIn; private QualityGateData(QualityGateDto qualityGate, boolean isDefault) { this.uuid = qualityGate.getUuid(); this.name = qualityGate.getName(); this.isDefault = isDefault; this.builtIn = qualityGate.isBuiltIn(); } public boolean isBuiltIn() { return builtIn; } public String getUuid() { return uuid; } public String getName() { return name; } public boolean isDefault() { return isDefault; } } }
3,016
32.898876
163
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/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.qualitygate; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplate.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.qualitygate.notification; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.EmailSettings; import org.sonar.api.measures.Metric; import org.sonar.api.notifications.Notification; import org.sonar.server.issue.notification.EmailMessage; import org.sonar.server.issue.notification.EmailTemplate; import org.sonar.server.measure.Rating; import java.util.Optional; /** * Creates email message for notification "alerts". * * @since 3.5 */ public class QGChangeEmailTemplate implements EmailTemplate { private final EmailSettings configuration; public QGChangeEmailTemplate(EmailSettings configuration) { this.configuration = configuration; } @Override @CheckForNull public EmailMessage format(Notification notification) { if (!"alerts".equals(notification.getType())) { return null; } // Retrieve useful values String projectId = notification.getFieldValue("projectId"); String projectKey = notification.getFieldValue("projectKey"); String projectName = notification.getFieldValue("projectName"); String projectVersion = notification.getFieldValue("projectVersion"); String branchName = notification.getFieldValue("branch"); String alertName = notification.getFieldValue("alertName"); String alertText = notification.getFieldValue("alertText"); String alertLevel = notification.getFieldValue("alertLevel"); String ratingMetricsInOneString = notification.getFieldValue("ratingMetrics"); boolean isNewAlert = Boolean.parseBoolean(notification.getFieldValue("isNewAlert")); String fullProjectName = computeFullProjectName(projectName, branchName); // Generate text String subject = generateSubject(fullProjectName, alertLevel, isNewAlert); String messageBody = generateMessageBody(projectName, projectKey, projectVersion, branchName, alertName, alertText, isNewAlert, ratingMetricsInOneString); // And finally return the email that will be sent return new EmailMessage() .setMessageId("alerts/" + projectId) .setSubject(subject) .setPlainTextMessage(messageBody); } private static String computeFullProjectName(String projectName, @Nullable String branchName) { if (branchName == null || branchName.isEmpty()) { return projectName; } return String.format("%s (%s)", projectName, branchName); } private static String generateSubject(String fullProjectName, String alertLevel, boolean isNewAlert) { StringBuilder subjectBuilder = new StringBuilder(); if (Metric.Level.OK.toString().equals(alertLevel)) { subjectBuilder.append("\"").append(fullProjectName).append("\" is back to green"); } else if (isNewAlert) { subjectBuilder.append("New quality gate threshold reached on \"").append(fullProjectName).append("\""); } else { subjectBuilder.append("Quality gate status changed on \"").append(fullProjectName).append("\""); } return subjectBuilder.toString(); } private String generateMessageBody(String projectName, String projectKey, @Nullable String projectVersion, @Nullable String branchName, String alertName, String alertText, boolean isNewAlert, String ratingMetricsInOneString) { StringBuilder messageBody = new StringBuilder(); messageBody.append("Project: ").append(projectName).append("\n"); if (branchName != null) { messageBody.append("Branch: ").append(branchName).append("\n"); } if (projectVersion != null) { messageBody.append("Version: ").append(projectVersion).append("\n"); } messageBody.append("Quality gate status: ").append(alertName).append("\n\n"); String[] alerts = StringUtils.split(alertText, ","); if (alerts.length > 0) { if (isNewAlert) { messageBody.append("New quality gate threshold"); } else { messageBody.append("Quality gate threshold"); } if (alerts.length == 1) { messageBody.append(": ").append(formatRating(alerts[0].trim(), ratingMetricsInOneString)).append("\n"); } else { messageBody.append("s:\n"); for (String alert : alerts) { messageBody.append(" - ").append(formatRating(alert.trim(), ratingMetricsInOneString)).append("\n"); } } } messageBody.append("\n").append("More details at: ").append(configuration.getServerBaseURL()).append("/dashboard?id=").append(projectKey); if (branchName != null) { messageBody.append("&branch=").append(branchName); } return messageBody.toString(); } /** * Converts the ratings from digits to a rating letter {@see org.sonar.server.measure.Rating}, based on the * raw text passed to this template. * * Examples: * Reliability rating > 4 will be converted to Reliability rating worse than D * Security rating on New Code > 1 will be converted to Security rating on New Code worse than A * Code Coverage < 50% will not be converted and returned as is. * * @param alert * @param ratingMetricsInOneString * @return full raw alert with converted ratings */ private static String formatRating(String alert, String ratingMetricsInOneString) { Optional<String> ratingToFormat = Optional.empty(); for(String rating : ratingMetricsInOneString.split(",")) { if (alert.matches(rating + " > \\d$")) { ratingToFormat = Optional.of(rating); break; } } if(!ratingToFormat.isPresent()){ return alert; } StringBuilder builder = new StringBuilder(ratingToFormat.get()); builder.append(" worse than "); String rating = alert.substring(alert.length() - 1); builder.append(Rating.valueOf(Integer.parseInt(rating)).name()); return builder.toString(); } }
6,669
38.467456
158
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/notification/QGChangeNotification.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.qualitygate.notification; import javax.annotation.CheckForNull; import org.sonar.api.notifications.Notification; public class QGChangeNotification extends Notification { public QGChangeNotification() { super("alerts"); } @CheckForNull public String getProjectKey() { return getFieldValue("projectKey"); } }
1,195
34.176471
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandler.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.qualitygate.notification; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.sonar.server.notification.EmailNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static java.util.Collections.emptySet; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER; public class QGChangeNotificationHandler extends EmailNotificationHandler<QGChangeNotification> { public static final String KEY = "NewAlerts"; private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY) .setProperty(NotificationDispatcherMetadata.GLOBAL_NOTIFICATION, String.valueOf(true)) .setProperty(NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION, String.valueOf(true)); private final NotificationManager notificationManager; public QGChangeNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel) { super(emailNotificationChannel); this.notificationManager = notificationManager; } @Override public Class<QGChangeNotification> getNotificationClass() { return QGChangeNotification.class; } @Override public Optional<NotificationDispatcherMetadata> getMetadata() { return Optional.of(METADATA); } public static NotificationDispatcherMetadata newMetadata() { return METADATA; } @Override public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<QGChangeNotification> notifications) { Multimap<String, QGChangeNotification> notificationsByProjectKey = notifications.stream() .filter(t -> t.getProjectKey() != null) .collect(index(QGChangeNotification::getProjectKey)); if (notificationsByProjectKey.isEmpty()) { return emptySet(); } return notificationsByProjectKey.asMap().entrySet() .stream() .flatMap(e -> toEmailDeliveryRequests(e.getKey(), e.getValue())) .collect(Collectors.toSet()); } private Stream<? extends EmailDeliveryRequest> toEmailDeliveryRequests(String projectKey, Collection<QGChangeNotification> notifications) { return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, ALL_MUST_HAVE_ROLE_USER) .stream() .flatMap(emailRecipient -> notifications.stream() .map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification))); } }
3,717
41.25
141
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/notification/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.qualitygate.notification; import javax.annotation.ParametersAreNonnullByDefault;
981
39.916667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/ActiveRuleChange.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.qualityprofile; import com.google.common.base.MoreObjects; import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleKey; import org.sonar.db.qualityprofile.QProfileChangeDto; import org.sonar.db.rule.RuleDto; public class ActiveRuleChange { private ActiveRuleDto activeRule; public enum Type { ACTIVATED, DEACTIVATED, UPDATED } private final Type type; private final ActiveRuleKey key; private final String ruleUuid; private String severity = null; private ActiveRuleInheritance inheritance = null; private final Map<String, String> parameters = new HashMap<>(); public ActiveRuleChange(Type type, ActiveRuleDto activeRule, RuleDto ruleDto) { this.type = type; this.key = activeRule.getKey(); this.ruleUuid = ruleDto.getUuid(); this.activeRule = activeRule; } public ActiveRuleChange(Type type, ActiveRuleKey key, RuleDto ruleDto) { this.type = type; this.key = key; this.ruleUuid = ruleDto.getUuid(); } public ActiveRuleKey getKey() { return key; } public String getRuleUuid() { return ruleUuid; } public Type getType() { return type; } @CheckForNull public String getSeverity() { return severity; } public ActiveRuleChange setSeverity(@Nullable String s) { this.severity = s; return this; } public ActiveRuleChange setInheritance(@Nullable ActiveRuleInheritance i) { this.inheritance = i; return this; } @CheckForNull public ActiveRuleInheritance getInheritance() { return inheritance; } public Map<String, String> getParameters() { return parameters; } public ActiveRuleChange setParameter(String key, @Nullable String value) { parameters.put(key, value); return this; } public ActiveRuleChange setParameters(Map<String, String> m) { parameters.clear(); parameters.putAll(m); return this; } @CheckForNull public ActiveRuleDto getActiveRule() { return activeRule; } public ActiveRuleChange setActiveRule(@Nullable ActiveRuleDto activeRule) { this.activeRule = activeRule; return this; } public QProfileChangeDto toDto(@Nullable String userUuid) { QProfileChangeDto dto = new QProfileChangeDto(); dto.setChangeType(type.name()); dto.setRulesProfileUuid(getKey().getRuleProfileUuid()); dto.setUserUuid(userUuid); Map<String, String> data = new HashMap<>(); data.put("ruleUuid", getRuleUuid()); parameters.entrySet().stream() .filter(param -> !param.getKey().isEmpty()) .forEach(param -> data.put("param_" + param.getKey(), param.getValue())); if (StringUtils.isNotEmpty(severity)) { data.put("severity", severity); } if (inheritance != null) { data.put("inheritance", inheritance.name()); } dto.setData(data); return dto; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("type", type) .add("key", key) .add("ruleUuid", ruleUuid) .add("severity", severity) .add("inheritance", inheritance) .add("parameters", parameters) .toString(); } }
4,181
26.513158
81
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/ActiveRuleInheritance.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.qualityprofile; public enum ActiveRuleInheritance { NONE, OVERRIDES, INHERITED }
952
37.12
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/QPMeasureData.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.qualityprofile; import com.google.common.collect.ImmutableSortedSet; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.StringWriter; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.annotation.concurrent.Immutable; import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.util.UtcDateUtils; import static java.util.function.Function.identity; /** * Represents the array of JSON objects stored in the value of the * {@link org.sonar.api.measures.CoreMetrics#QUALITY_PROFILES} measures. */ @Immutable public class QPMeasureData { private final SortedSet<QualityProfile> profiles; public QPMeasureData(Iterable<QualityProfile> qualityProfiles) { this.profiles = ImmutableSortedSet.copyOf(QualityProfileComparator.INSTANCE, qualityProfiles); } public static QPMeasureData fromJson(String json) { return new QPMeasureData(StreamSupport.stream(new JsonParser().parse(json).getAsJsonArray().spliterator(), false) .map(jsonElement -> { JsonObject jsonProfile = jsonElement.getAsJsonObject(); return new QualityProfile( jsonProfile.get("key").getAsString(), jsonProfile.get("name").getAsString(), jsonProfile.get("language").getAsString(), UtcDateUtils.parseDateTime(jsonProfile.get("rulesUpdatedAt").getAsString())); }).toList()); } public static String toJson(QPMeasureData data) { StringWriter json = new StringWriter(); try (JsonWriter writer = JsonWriter.of(json)) { writer.beginArray(); for (QualityProfile profile : data.getProfiles()) { writer .beginObject() .prop("key", profile.getQpKey()) .prop("language", profile.getLanguageKey()) .prop("name", profile.getQpName()) .prop("rulesUpdatedAt", UtcDateUtils.formatDateTime(profile.getRulesUpdatedAt())) .endObject(); } writer.endArray(); } return json.toString(); } public SortedSet<QualityProfile> getProfiles() { return profiles; } public Map<String, QualityProfile> getProfilesByKey() { return profiles.stream().collect(Collectors.toMap(QualityProfile::getQpKey, identity())); } private enum QualityProfileComparator implements Comparator<QualityProfile> { INSTANCE; @Override public int compare(QualityProfile o1, QualityProfile o2) { int c = o1.getLanguageKey().compareTo(o2.getLanguageKey()); if (c == 0) { c = o1.getQpName().compareTo(o2.getQpName()); } return c; } } }
3,536
34.019802
117
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/QualityProfile.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.qualityprofile; import com.google.common.base.MoreObjects; import java.util.Date; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import static java.util.Objects.requireNonNull; /** * Represents the JSON object an array of which is stored in the value of the * {@link org.sonar.api.measures.CoreMetrics#QUALITY_PROFILES} measures. */ @Immutable public class QualityProfile { private final String qpKey; private final String qpName; private final String languageKey; private final Date rulesUpdatedAt; public QualityProfile(String qpKey, String qpName, String languageKey, Date rulesUpdatedAt) { this.qpKey = requireNonNull(qpKey); this.qpName = requireNonNull(qpName); this.languageKey = requireNonNull(languageKey); this.rulesUpdatedAt = requireNonNull(rulesUpdatedAt); } public String getQpKey() { return qpKey; } public String getQpName() { return qpName; } public String getLanguageKey() { return languageKey; } public Date getRulesUpdatedAt() { return new Date(rulesUpdatedAt.getTime()); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QualityProfile qProfile = (QualityProfile) o; return qpKey.equals(qProfile.qpKey); } @Override public int hashCode() { return qpKey.hashCode(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("key", qpKey) .add("name", qpName) .add("language", languageKey) .add("rulesUpdatedAt", rulesUpdatedAt.getTime()) .toString(); } }
2,570
27.252747
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.qualityprofile; import javax.annotation.ParametersAreNonnullByDefault;
971
39.5
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleDoc.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.qualityprofile.index; import com.google.common.collect.Maps; import java.util.Map; import javax.annotation.Nullable; import org.sonar.server.es.BaseDoc; import org.sonar.server.qualityprofile.ActiveRuleInheritance; import static org.apache.commons.lang.StringUtils.containsIgnoreCase; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_INHERITANCE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_PROFILE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_SEVERITY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_ACTIVE_RULE; public class ActiveRuleDoc extends BaseDoc { public static final String DOC_ID_PREFIX = "ar_"; public ActiveRuleDoc(String uuid) { super(TYPE_ACTIVE_RULE, Maps.newHashMapWithExpectedSize(10)); setField(FIELD_ACTIVE_RULE_UUID, uuid); } public ActiveRuleDoc(Map<String, Object> source) { super(TYPE_ACTIVE_RULE, source); } public static String docIdOf(String activeRuleUuid) { return DOC_ID_PREFIX + activeRuleUuid; } public static String activeRuleUuidOf(String docId) { if (docId.startsWith(DOC_ID_PREFIX)) { return docId.substring(DOC_ID_PREFIX.length()); } // support for old active rule docId return docId; } @Override public String getId() { return docIdOf(getField(FIELD_ACTIVE_RULE_UUID)); } ActiveRuleDoc setRuleUuid(String ruleUuid) { setParent(ruleUuid); setField(FIELD_RULE_UUID, ruleUuid); return this; } String getSeverity() { return getNullableField(FIELD_ACTIVE_RULE_SEVERITY); } ActiveRuleDoc setSeverity(@Nullable String s) { setField(FIELD_ACTIVE_RULE_SEVERITY, s); return this; } String getRuleProfileUuid() { return getField(FIELD_ACTIVE_RULE_PROFILE_UUID); } ActiveRuleDoc setRuleProfileUuid(String s) { setField(FIELD_ACTIVE_RULE_PROFILE_UUID, s); return this; } ActiveRuleInheritance getInheritance() { String inheritance = getNullableField(FIELD_ACTIVE_RULE_INHERITANCE); if (inheritance == null || inheritance.isEmpty() || containsIgnoreCase(inheritance, "none")) { return ActiveRuleInheritance.NONE; } else if (containsIgnoreCase(inheritance, "herit")) { return ActiveRuleInheritance.INHERITED; } else if (containsIgnoreCase(inheritance, "over")) { return ActiveRuleInheritance.OVERRIDES; } else { throw new IllegalStateException("Value \"" + inheritance + "\" is not valid for rule's inheritance"); } } public ActiveRuleDoc setInheritance(@Nullable String s) { setField(FIELD_ACTIVE_RULE_INHERITANCE, s); return this; } }
3,731
33.238532
107
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexer.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.qualityprofile.index; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; import org.sonar.db.qualityprofile.IndexedActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.RulesProfileDto; import org.sonar.db.rule.SeverityUtil; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.BulkIndexer.Size; import org.sonar.server.es.EsClient; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexingListener; import org.sonar.server.es.IndexingResult; import org.sonar.server.es.OneToOneResilientIndexingListener; import org.sonar.server.es.ResilientIndexer; import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonar.server.qualityprofile.ActiveRuleInheritance; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.sonar.server.qualityprofile.index.ActiveRuleDoc.docIdOf; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_PROFILE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_ACTIVE_RULE; public class ActiveRuleIndexer implements ResilientIndexer { private static final Logger LOGGER = LoggerFactory.getLogger(ActiveRuleIndexer.class); private static final String ID_TYPE_ACTIVE_RULE_UUID = "activeRuleUuid"; private static final String ID_TYPE_RULE_PROFILE_UUID = "ruleProfileUuid"; private final DbClient dbClient; private final EsClient esClient; public ActiveRuleIndexer(DbClient dbClient, EsClient esClient) { this.dbClient = dbClient; this.esClient = esClient; } @Override public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) { indexAll(Size.LARGE); } public void indexAll() { indexAll(Size.REGULAR); } private void indexAll(Size bulkSize) { try (DbSession dbSession = dbClient.openSession(false)) { BulkIndexer bulkIndexer = createBulkIndexer(bulkSize, IndexingListener.FAIL_ON_ERROR); bulkIndexer.start(); dbClient.activeRuleDao().scrollAllForIndexing(dbSession, ar -> bulkIndexer.add(newIndexRequest(ar))); bulkIndexer.stop(); } } @Override public Set<IndexType> getIndexTypes() { return ImmutableSet.of(TYPE_ACTIVE_RULE); } public void commitAndIndex(DbSession dbSession, Collection<ActiveRuleChange> changes) { List<EsQueueDto> items = changes.stream() .map(ActiveRuleChange::getActiveRule) .map(ar -> newQueueDto(docIdOf(ar.getUuid()), ID_TYPE_ACTIVE_RULE_UUID, ar.getRuleUuid())) .toList(); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); } public void commitDeletionOfProfiles(DbSession dbSession, Collection<QProfileDto> profiles) { List<EsQueueDto> items = profiles.stream() .map(QProfileDto::getRulesProfileUuid) .distinct() .map(ruleProfileUuid -> newQueueDto(ruleProfileUuid, ID_TYPE_RULE_PROFILE_UUID, null)) .toList(); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); } /** * Entry point for Byteman tests. See directory tests/resilience. */ private void postCommit(DbSession dbSession, Collection<EsQueueDto> items) { index(dbSession, items); } /** * @return the number of items that have been successfully indexed */ @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { IndexingResult result = new IndexingResult(); if (items.isEmpty()) { return result; } Map<String, EsQueueDto> activeRuleItems = new HashMap<>(); Map<String, EsQueueDto> ruleProfileItems = new HashMap<>(); items.forEach(i -> { if (ID_TYPE_RULE_PROFILE_UUID.equals(i.getDocIdType())) { ruleProfileItems.put(i.getDocId(), i); } else if (ID_TYPE_ACTIVE_RULE_UUID.equals(i.getDocIdType())) { activeRuleItems.put(i.getDocId(), i); } else { LOGGER.error("Unsupported es_queue.doc_id_type. Removing row from queue: " + i); deleteQueueDto(dbSession, i); } }); if (!activeRuleItems.isEmpty()) { result.add(doIndexActiveRules(dbSession, activeRuleItems)); } if (!ruleProfileItems.isEmpty()) { result.add(doIndexRuleProfiles(dbSession, ruleProfileItems)); } return result; } private IndexingResult doIndexActiveRules(DbSession dbSession, Map<String, EsQueueDto> activeRuleItems) { OneToOneResilientIndexingListener listener = new OneToOneResilientIndexingListener(dbClient, dbSession, activeRuleItems.values()); BulkIndexer bulkIndexer = createBulkIndexer(Size.REGULAR, listener); bulkIndexer.start(); Map<String, EsQueueDto> remaining = new HashMap<>(activeRuleItems); dbClient.activeRuleDao().scrollByUuidsForIndexing(dbSession, toActiveRuleUuids(activeRuleItems), i -> { remaining.remove(docIdOf(i.getUuid())); bulkIndexer.add(newIndexRequest(i)); }); // the remaining ids reference rows that don't exist in db. They must // be deleted from index. remaining.values().forEach(item -> bulkIndexer.addDeletion(TYPE_ACTIVE_RULE, item.getDocId(), item.getDocRouting())); return bulkIndexer.stop(); } private static Collection<String> toActiveRuleUuids(Map<String, EsQueueDto> activeRuleItems) { Set<String> docIds = activeRuleItems.keySet(); return docIds.stream() .map(ActiveRuleDoc::activeRuleUuidOf) .collect(Collectors.toSet()); } private IndexingResult doIndexRuleProfiles(DbSession dbSession, Map<String, EsQueueDto> ruleProfileItems) { IndexingResult result = new IndexingResult(); for (Map.Entry<String, EsQueueDto> entry : ruleProfileItems.entrySet()) { String ruleProfileUUid = entry.getKey(); EsQueueDto item = entry.getValue(); IndexingResult profileResult; RulesProfileDto profile = dbClient.qualityProfileDao().selectRuleProfile(dbSession, ruleProfileUUid); if (profile == null) { // profile does not exist anymore in db --> related documents must be deleted from index rules/activeRule SearchRequest search = EsClient.prepareSearch(TYPE_ACTIVE_RULE.getMainType()) .source(new SearchSourceBuilder().query(QueryBuilders.boolQuery().must(termQuery(FIELD_ACTIVE_RULE_PROFILE_UUID, ruleProfileUUid)))); profileResult = BulkIndexer.delete(esClient, TYPE_ACTIVE_RULE, search); } else { BulkIndexer bulkIndexer = createBulkIndexer(Size.REGULAR, IndexingListener.FAIL_ON_ERROR); bulkIndexer.start(); dbClient.activeRuleDao().scrollByRuleProfileForIndexing(dbSession, ruleProfileUUid, i -> bulkIndexer.add(newIndexRequest(i))); profileResult = bulkIndexer.stop(); } if (profileResult.isSuccess()) { deleteQueueDto(dbSession, item); } result.add(profileResult); } return result; } private void deleteQueueDto(DbSession dbSession, EsQueueDto item) { dbClient.esQueueDao().delete(dbSession, item); dbSession.commit(); } private BulkIndexer createBulkIndexer(Size size, IndexingListener listener) { return new BulkIndexer(esClient, TYPE_ACTIVE_RULE, size, listener); } private static IndexRequest newIndexRequest(IndexedActiveRuleDto dto) { ActiveRuleDoc doc = new ActiveRuleDoc(dto.getUuid()) .setRuleUuid(dto.getRuleUuid()) .setRuleProfileUuid(dto.getRuleProfileUuid()) .setSeverity(SeverityUtil.getSeverityFromOrdinal(dto.getSeverity())); // all the fields must be present, even if value is null String inheritance = dto.getInheritance(); doc.setInheritance(inheritance == null ? ActiveRuleInheritance.NONE.name() : inheritance); return doc.toIndexRequest(); } private static EsQueueDto newQueueDto(String docId, String docIdType, @Nullable String routing) { return EsQueueDto.create(TYPE_ACTIVE_RULE.format(), docId, docIdType, routing); } }
9,352
38.133891
143
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/qualityprofile/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.qualityprofile.index; import javax.annotation.ParametersAreNonnullByDefault;
977
39.75
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/CommonRuleKeys.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.rule; public class CommonRuleKeys { public static final String REPOSITORY_PREFIX = "common-"; public static final String INSUFFICIENT_BRANCH_COVERAGE = "InsufficientBranchCoverage"; public static final String INSUFFICIENT_BRANCH_COVERAGE_PROPERTY = "minimumBranchCoverageRatio"; public static final String INSUFFICIENT_LINE_COVERAGE = "InsufficientLineCoverage"; public static final String INSUFFICIENT_LINE_COVERAGE_PROPERTY = "minimumLineCoverageRatio"; public static final String INSUFFICIENT_COMMENT_DENSITY = "InsufficientCommentDensity"; public static final String INSUFFICIENT_COMMENT_DENSITY_PROPERTY = "minimumCommentDensity"; public static final String DUPLICATED_BLOCKS = "DuplicatedBlocks"; public static final String FAILED_UNIT_TESTS = "FailedUnitTests"; public static final String SKIPPED_UNIT_TESTS = "SkippedUnitTests"; private CommonRuleKeys() { // only static methods } public static String commonRepositoryForLang(String language) { return REPOSITORY_PREFIX + language; } }
1,906
39.574468
98
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/DefaultRuleFinder.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.rule; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableListMultimap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RulePriority; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDao; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; /** * Will be removed in the future. */ public class DefaultRuleFinder implements ServerRuleFinder { private final DbClient dbClient; private final RuleDao ruleDao; private final RuleDescriptionFormatter ruleDescriptionFormatter; public DefaultRuleFinder(DbClient dbClient, RuleDescriptionFormatter ruleDescriptionFormatter) { this.dbClient = dbClient; this.ruleDao = dbClient.ruleDao(); this.ruleDescriptionFormatter = ruleDescriptionFormatter; } @Override public Optional<RuleDto> findDtoByKey(RuleKey key) { try (DbSession dbSession = dbClient.openSession(false)) { return ruleDao.selectByKey(dbSession, key) .filter(r -> r.getStatus() != RuleStatus.REMOVED); } } @Override public Optional<RuleDto> findDtoByUuid(String uuid) { try (DbSession dbSession = dbClient.openSession(false)) { return ruleDao.selectByUuid(uuid, dbSession) .filter(r -> r.getStatus() != RuleStatus.REMOVED); } } @Override public Collection<RuleDto> findAll() { try (DbSession dbSession = dbClient.openSession(false)) { return ruleDao.selectEnabled(dbSession); } } @Override @CheckForNull public org.sonar.api.rules.Rule findByKey(RuleKey key) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<RuleDto> rule = ruleDao.selectByKey(dbSession, key); if (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED) { return toRule(rule.get(), ruleDao.selectRuleParamsByRuleKey(dbSession, rule.get().getKey())); } else { return null; } } } @Override @CheckForNull public org.sonar.api.rules.Rule findByKey(String repositoryKey, String key) { return findByKey(RuleKey.of(repositoryKey, key)); } @Override public final org.sonar.api.rules.Rule find(org.sonar.api.rules.RuleQuery query) { try (DbSession dbSession = dbClient.openSession(false)) { List<RuleDto> rules = ruleDao.selectByQuery(dbSession, query); if (!rules.isEmpty()) { RuleDto rule = rules.get(0); return toRule(rule, ruleDao.selectRuleParamsByRuleKey(dbSession, rule.getKey())); } return null; } } @Override public final Collection<org.sonar.api.rules.Rule> findAll(org.sonar.api.rules.RuleQuery query) { try (DbSession dbSession = dbClient.openSession(false)) { List<RuleDto> rules = ruleDao.selectByQuery(dbSession, query); if (rules.isEmpty()) { return Collections.emptyList(); } return convertToRuleApi(dbSession, rules); } } private Collection<org.sonar.api.rules.Rule> convertToRuleApi(DbSession dbSession, List<RuleDto> ruleDtos) { List<org.sonar.api.rules.Rule> rules = new ArrayList<>(); List<RuleKey> ruleKeys = ruleDtos.stream().map(RuleDto::getKey).toList(); List<RuleParamDto> ruleParamDtos = ruleDao.selectRuleParamsByRuleKeys(dbSession, ruleKeys); ImmutableListMultimap<String, RuleParamDto> ruleParamByRuleUuid = FluentIterable.from(ruleParamDtos).index(RuleParamDtoToRuleUuid.INSTANCE); for (RuleDto rule : ruleDtos) { rules.add(toRule(rule, ruleParamByRuleUuid.get(rule.getUuid()))); } return rules; } private org.sonar.api.rules.Rule toRule(RuleDto rule, List<RuleParamDto> params) { String severity = rule.getSeverityString(); org.sonar.api.rules.Rule apiRule = new org.sonar.api.rules.Rule(); apiRule .setName(rule.getName()) .setLanguage(rule.getLanguage()) .setKey(rule.getRuleKey()) .setConfigKey(rule.getConfigKey()) .setIsTemplate(rule.isTemplate()) .setCreatedAt(new Date(rule.getCreatedAt())) .setUpdatedAt(new Date(rule.getUpdatedAt())) .setRepositoryKey(rule.getRepositoryKey()) .setSeverity(severity != null ? RulePriority.valueOf(severity) : null) .setStatus(rule.getStatus().name()) .setSystemTags(rule.getSystemTags().toArray(new String[rule.getSystemTags().size()])) .setTags(rule.getTags().toArray(new String[rule.getTags().size()])); Optional.ofNullable(ruleDescriptionFormatter.getDescriptionAsHtml(rule)).ifPresent(apiRule::setDescription); List<org.sonar.api.rules.RuleParam> apiParams = new ArrayList<>(); for (RuleParamDto param : params) { apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) .setDefaultValue(param.getDefaultValue())); } apiRule.setParams(apiParams); return apiRule; } private enum RuleParamDtoToRuleUuid implements Function<RuleParamDto, String> { INSTANCE; @Override public String apply(@Nonnull RuleParamDto input) { return input.getRuleUuid(); } } }
6,246
35.109827
144
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/RuleDescriptionFormatter.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.rule; import com.google.common.collect.MoreCollectors; import java.util.Collection; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.markdown.Markdown; import static org.sonar.db.rule.RuleDto.Format.MARKDOWN; public class RuleDescriptionFormatter { @CheckForNull public String getDescriptionAsHtml(RuleDto ruleDto) { if (ruleDto.getDescriptionFormat() == null) { return null; } Collection<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = ruleDto.getRuleDescriptionSectionDtos(); return retrieveDescription(ruleDescriptionSectionDtos, Objects.requireNonNull(ruleDto.getDescriptionFormat())); } @CheckForNull private String retrieveDescription(Collection<RuleDescriptionSectionDto> ruleDescriptionSectionDtos, RuleDto.Format descriptionFormat) { return ruleDescriptionSectionDtos.stream() .filter(RuleDescriptionSectionDto::isDefault) .collect(MoreCollectors.toOptional()) .map(section -> toHtml(descriptionFormat, section)) .orElse(null); } public String toHtml(@Nullable RuleDto.Format descriptionFormat, RuleDescriptionSectionDto ruleDescriptionSectionDto) { if (MARKDOWN.equals(descriptionFormat)) { return Markdown.convertToHtml(ruleDescriptionSectionDto.getContent()); } return ruleDescriptionSectionDto.getContent(); } }
2,344
37.442623
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/ServerRuleFinder.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.rule; import java.util.Collection; import java.util.Optional; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleFinder; import org.sonar.db.rule.RuleDto; public interface ServerRuleFinder extends RuleFinder { Optional<RuleDto> findDtoByKey(RuleKey key); Optional<RuleDto> findDtoByUuid(String uuid); Collection<RuleDto> findAll(); }
1,228
33.138889
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/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.rule; import javax.annotation.ParametersAreNonnullByDefault;
961
40.826087
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleDoc.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.rule.index; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.Collection; import java.util.HashMap; 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.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleForIndexingDto; import org.sonar.markdown.Markdown; import org.sonar.server.es.BaseDoc; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.SQCategory; import static java.util.stream.Collectors.joining; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; /** * Implementation of Rule based on an Elasticsearch document */ public class RuleDoc extends BaseDoc { @VisibleForTesting public RuleDoc(Map<String, Object> fields) { super(TYPE_RULE, new HashMap<>(fields)); } public RuleDoc() { super(TYPE_RULE, Maps.newHashMapWithExpectedSize(16)); } @Override public String getId() { return idAsString(); } private String idAsString() { return getField(RuleIndexDefinition.FIELD_RULE_UUID); } public RuleDoc setUuid(String ruleUuid) { setField(RuleIndexDefinition.FIELD_RULE_UUID, ruleUuid); return this; } @Override protected Optional<String> getSimpleMainTypeRouting() { return Optional.of(idAsString()); } public RuleKey key() { return RuleKey.parse(keyAsString()); } private String keyAsString() { return getField(RuleIndexDefinition.FIELD_RULE_KEY); } public RuleDoc setKey(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_KEY, s); return this; } @CheckForNull public String ruleKey() { return getNullableField(RuleIndexDefinition.FIELD_RULE_RULE_KEY); } public RuleDoc setRuleKey(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_RULE_KEY, s); return this; } @CheckForNull public String repository() { return getNullableField(RuleIndexDefinition.FIELD_RULE_REPOSITORY); } public RuleDoc setRepository(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_REPOSITORY, s); return this; } @CheckForNull public String internalKey() { return getNullableField(RuleIndexDefinition.FIELD_RULE_INTERNAL_KEY); } public RuleDoc setInternalKey(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_INTERNAL_KEY, s); return this; } @CheckForNull public String language() { return getNullableField(RuleIndexDefinition.FIELD_RULE_LANGUAGE); } public RuleDoc setLanguage(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_LANGUAGE, s); return this; } public String name() { return getField(RuleIndexDefinition.FIELD_RULE_NAME); } public RuleDoc setName(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_NAME, s); return this; } @CheckForNull public String htmlDescription() { return getNullableField(RuleIndexDefinition.FIELD_RULE_HTML_DESCRIPTION); } public RuleDoc setHtmlDescription(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_HTML_DESCRIPTION, s); return this; } @CheckForNull public String severity() { return getNullableField(RuleIndexDefinition.FIELD_RULE_SEVERITY); } public RuleDoc setSeverity(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_SEVERITY, s); return this; } @CheckForNull public Collection<String> getOwaspTop10() { return getNullableField(RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10); } public RuleDoc setOwaspTop10(@Nullable Collection<String> o) { setField(RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10, o); return this; } @CheckForNull public Collection<String> getOwaspTop10For2021() { return getNullableField(RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10_2021); } public RuleDoc setOwaspTop10For2021(@Nullable Collection<String> o) { setField(RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10_2021, o); return this; } @CheckForNull public Collection<String> getSansTop25() { return getNullableField(RuleIndexDefinition.FIELD_RULE_SANS_TOP_25); } public RuleDoc setSansTop25(@Nullable Collection<String> s) { setField(RuleIndexDefinition.FIELD_RULE_SANS_TOP_25, s); return this; } @CheckForNull public Collection<String> getCwe() { return getNullableField(RuleIndexDefinition.FIELD_RULE_CWE); } public RuleDoc setCwe(@Nullable Collection<String> c) { setField(RuleIndexDefinition.FIELD_RULE_CWE, c); return this; } @CheckForNull public SQCategory getSonarSourceSecurityCategory() { String key = getNullableField(RuleIndexDefinition.FIELD_RULE_SONARSOURCE_SECURITY); return SQCategory.fromKey(key).orElse(null); } public RuleDoc setSonarSourceSecurityCategory(@Nullable SQCategory sqCategory) { setField(RuleIndexDefinition.FIELD_RULE_SONARSOURCE_SECURITY, sqCategory == null ? null : sqCategory.getKey()); return this; } public Set<String> getTags() { return getField(RuleIndexDefinition.FIELD_RULE_TAGS); } public RuleDoc setTags(Set<String> tags) { setField(RuleIndexDefinition.FIELD_RULE_TAGS, tags); return this; } @CheckForNull public RuleStatus status() { return RuleStatus.valueOf(getField(RuleIndexDefinition.FIELD_RULE_STATUS)); } public RuleDoc setStatus(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_STATUS, s); return this; } @CheckForNull public RuleKey templateKey() { String templateKey = getNullableField(RuleIndexDefinition.FIELD_RULE_TEMPLATE_KEY); return templateKey != null ? RuleKey.parse(templateKey) : null; } public RuleDoc setTemplateKey(@Nullable String s) { setField(RuleIndexDefinition.FIELD_RULE_TEMPLATE_KEY, s); return this; } public boolean isTemplate() { return getField(RuleIndexDefinition.FIELD_RULE_IS_TEMPLATE); } public RuleDoc setIsTemplate(@Nullable Boolean b) { setField(RuleIndexDefinition.FIELD_RULE_IS_TEMPLATE, b); return this; } public boolean isExternal() { return getField(RuleIndexDefinition.FIELD_RULE_IS_EXTERNAL); } public RuleDoc setIsExternal(boolean b) { setField(RuleIndexDefinition.FIELD_RULE_IS_EXTERNAL, b); return this; } @CheckForNull public RuleType type() { String type = getNullableField(RuleIndexDefinition.FIELD_RULE_TYPE); if (type == null) { return null; } return RuleType.valueOf(type); } public RuleDoc setType(@Nullable RuleType ruleType) { setField(RuleIndexDefinition.FIELD_RULE_TYPE, ruleType == null ? null : ruleType.name()); return this; } public long createdAt() { return getField(RuleIndexDefinition.FIELD_RULE_CREATED_AT); } public RuleDoc setCreatedAt(@Nullable Long l) { setField(RuleIndexDefinition.FIELD_RULE_CREATED_AT, l); return this; } public long updatedAt() { return getField(RuleIndexDefinition.FIELD_RULE_UPDATED_AT); } public RuleDoc setUpdatedAt(@Nullable Long l) { setField(RuleIndexDefinition.FIELD_RULE_UPDATED_AT, l); return this; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } public static RuleDoc createFrom(RuleForIndexingDto dto, SecurityStandards securityStandards) { return new RuleDoc() .setUuid(dto.getUuid()) .setKey(dto.getRuleKey().toString()) .setRepository(dto.getRepository()) .setInternalKey(dto.getInternalKey()) .setIsTemplate(dto.isTemplate()) .setIsExternal(dto.isExternal()) .setLanguage(dto.getLanguage()) .setCwe(securityStandards.getCwe()) .setOwaspTop10(securityStandards.getOwaspTop10()) .setOwaspTop10For2021(securityStandards.getOwaspTop10For2021()) .setSansTop25(securityStandards.getSansTop25()) .setSonarSourceSecurityCategory(securityStandards.getSqCategory()) .setName(dto.getName()) .setRuleKey(dto.getPluginRuleKey()) .setSeverity(dto.getSeverityAsString()) .setStatus(dto.getStatus().toString()) .setType(dto.getTypeAsRuleType()) .setCreatedAt(dto.getCreatedAt()) .setTags(Sets.union(dto.getTags(), dto.getSystemTags())) .setUpdatedAt(dto.getUpdatedAt()) .setHtmlDescription(getConcatenatedSectionsInHtml(dto)) .setTemplateKey(getRuleKey(dto)); } @CheckForNull private static String getRuleKey(RuleForIndexingDto dto) { if (dto.getTemplateRuleKey() != null && dto.getTemplateRepository() != null) { return RuleKey.of(dto.getTemplateRepository(), dto.getTemplateRuleKey()).toString(); } return null; } private static String getConcatenatedSectionsInHtml(RuleForIndexingDto dto) { return dto.getRuleDescriptionSectionsDtos().stream() .map(RuleDescriptionSectionDto::getContent) .map(content -> convertToHtmlIfNecessary(dto.getDescriptionFormat(), content)) .collect(joining(" ")); } private static String convertToHtmlIfNecessary(RuleDto.Format format, String content) { if (RuleDto.Format.MARKDOWN.equals(format)) { return Markdown.convertToHtml(content); } return content; } }
10,363
28.953757
115
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleIndex.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.rule.index; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Function; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; 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.Operator; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.join.aggregations.JoinAggregationBuilders; import org.elasticsearch.join.query.HasParentQueryBuilder; import org.elasticsearch.join.query.JoinQueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsUtils; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonar.server.es.StickyFacetBuilder; import org.sonar.server.es.newindex.DefaultIndexSettings; import org.sonar.server.es.textsearch.JavaTokenizer; import org.sonar.server.security.SecurityStandards; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; 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.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; 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.SCROLL_TIME_IN_MINUTES; import static org.sonar.server.es.EsUtils.optimizeScrollRequest; import static org.sonar.server.es.EsUtils.scrollIds; import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE; import static org.sonar.server.es.StickyFacetBuilder.FACET_DEFAULT_SIZE; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.ENGLISH_HTML_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_WORDS_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_INHERITANCE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_PROFILE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_ACTIVE_RULE_SEVERITY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_CREATED_AT; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_CWE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_HTML_DESCRIPTION; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_INTERNAL_KEY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_IS_EXTERNAL; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_IS_TEMPLATE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_KEY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_LANGUAGE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_NAME; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_OWASP_TOP_10_2021; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_REPOSITORY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_RULE_KEY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_SANS_TOP_25; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_SEVERITY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_SONARSOURCE_SECURITY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_STATUS; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_TAGS; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_TEMPLATE_KEY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_TYPE; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_UPDATED_AT; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_ACTIVE_RULE; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; /** * The unique entry-point to interact with Elasticsearch index "rules". * All the requests are listed here. */ public class RuleIndex { public static final String FACET_LANGUAGES = "languages"; public static final String FACET_TAGS = "tags"; public static final String FACET_REPOSITORIES = "repositories"; public static final String FACET_SEVERITIES = "severities"; public static final String FACET_ACTIVE_SEVERITIES = "active_severities"; public static final String FACET_STATUSES = "statuses"; public static final String FACET_TYPES = "types"; public static final String FACET_OLD_DEFAULT = "true"; public static final String FACET_CWE = "cwe"; /** * @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0 */ @Deprecated(since = "10.0", forRemoval = true) public static final String FACET_SANS_TOP_25 = "sansTop25"; public static final String FACET_OWASP_TOP_10 = "owaspTop10"; public static final String FACET_OWASP_TOP_10_2021 = "owaspTop10-2021"; public static final String FACET_SONARSOURCE_SECURITY = "sonarsourceSecurity"; private static final int MAX_FACET_SIZE = 100; public static final List<String> ALL_STATUSES_EXCEPT_REMOVED = Arrays.stream(RuleStatus.values()) .filter(status -> !RuleStatus.REMOVED.equals(status)) .map(RuleStatus::toString) .toList(); private static final String AGGREGATION_NAME_FOR_TAGS = "tagsAggregation"; private final EsClient client; private final System2 system2; public RuleIndex(EsClient client, System2 system2) { this.client = client; this.system2 = system2; } public SearchIdResult<String> search(RuleQuery query, SearchOptions options) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); QueryBuilder qb = buildQuery(query); Map<String, QueryBuilder> filters = buildFilters(query); if (!options.getFacets().isEmpty()) { for (AggregationBuilder aggregation : getFacets(query, options, qb, filters).values()) { sourceBuilder.aggregation(aggregation); } } setSorting(query, sourceBuilder); setPagination(options, sourceBuilder); BoolQueryBuilder fb = boolQuery(); for (QueryBuilder filterBuilder : filters.values()) { fb.must(filterBuilder); } sourceBuilder.query(boolQuery().must(qb).filter(fb)); SearchRequest esSearch = EsClient.prepareSearch(TYPE_RULE) .source(sourceBuilder); return new SearchIdResult<>(client.search(esSearch), input -> input, system2.getDefaultTimeZone().toZoneId()); } /** * Return all rule uuids matching the search query, without pagination nor facets */ public Iterator<String> searchAll(RuleQuery query) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); optimizeScrollRequest(sourceBuilder); QueryBuilder qb = buildQuery(query); Map<String, QueryBuilder> filters = buildFilters(query); BoolQueryBuilder fb = boolQuery(); for (QueryBuilder filterBuilder : filters.values()) { fb.must(filterBuilder); } sourceBuilder.query(boolQuery().must(qb).filter(fb)); SearchRequest esSearch = EsClient.prepareSearch(TYPE_RULE) .scroll(TimeValue.timeValueMinutes(SCROLL_TIME_IN_MINUTES)) .source(sourceBuilder); SearchResponse response = client.search(esSearch); return scrollIds(client, response, i -> i); } /* Build main query (search based) */ private static QueryBuilder buildQuery(RuleQuery query) { // No contextual query case String queryText = query.getQueryText(); if (StringUtils.isEmpty(queryText)) { return matchAllQuery(); } // Build RuleBased contextual query BoolQueryBuilder qb = boolQuery(); BoolQueryBuilder textQuery = boolQuery(); JavaTokenizer.split(queryText) .stream().map(token -> boolQuery().should( matchQuery( SEARCH_GRAMS_ANALYZER.subField(FIELD_RULE_NAME), StringUtils.left(token, DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH)).boost(20F)) .should( matchPhraseQuery( ENGLISH_HTML_ANALYZER.subField(FIELD_RULE_HTML_DESCRIPTION), token).boost(3F))) .forEach(textQuery::must); qb.should(textQuery.boost(20F)); // Match and partial Match queries // Search by key uses the "sortable" sub-field as it requires to be case-insensitive (lower-case filtering) qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_KEY), queryText).operator(Operator.AND).boost(30F)); qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_RULE_KEY), queryText).operator(Operator.AND).boost(15F)); qb.should(termQuery(FIELD_RULE_LANGUAGE, queryText, 3F)); return qb; } private static QueryBuilder termQuery(String field, String query, float boost) { return QueryBuilders.multiMatchQuery(query, field, SEARCH_WORDS_ANALYZER.subField(field)) .operator(Operator.AND) .boost(boost); } /* Build main filter (match based) */ private static Map<String, QueryBuilder> buildFilters(RuleQuery query) { Map<String, QueryBuilder> filters = new HashMap<>(); /* Add enforced filter on main type Rule */ filters.put( FIELD_INDEX_TYPE, boolQuery().must(QueryBuilders.termsQuery(FIELD_INDEX_TYPE, TYPE_RULE.getType()))); /* Add enforced filter on rules that are REMOVED */ filters.put(FIELD_RULE_STATUS, boolQuery().mustNot( QueryBuilders.termQuery(FIELD_RULE_STATUS, RuleStatus.REMOVED.toString()))); addFilter(filters, FIELD_RULE_INTERNAL_KEY, query.getInternalKey()); addFilter(filters, FIELD_RULE_RULE_KEY, query.getRuleKey()); addFilter(filters, query.getLanguages(), FIELD_RULE_LANGUAGE); addFilter(filters, query.getRepositories(), FIELD_RULE_REPOSITORY); addFilter(filters, query.getSeverities(), FIELD_RULE_SEVERITY); addSecurityStandardFilter(filters, FIELD_RULE_CWE, query.getCwe()); addSecurityStandardFilter(filters, FIELD_RULE_OWASP_TOP_10, query.getOwaspTop10()); addSecurityStandardFilter(filters, FIELD_RULE_OWASP_TOP_10_2021, query.getOwaspTop10For2021()); addSecurityStandardFilter(filters, FIELD_RULE_SANS_TOP_25, query.getSansTop25()); addSecurityStandardFilter(filters, FIELD_RULE_SONARSOURCE_SECURITY, query.getSonarsourceSecurity()); addFilter(filters, FIELD_RULE_KEY, query.getKey()); if (isNotEmpty(query.getTags())) { filters.put(FIELD_RULE_TAGS, buildTagsFilter(query.getTags())); } Collection<RuleType> types = query.getTypes(); if (isNotEmpty(types)) { List<String> typeNames = types.stream().map(RuleType::toString).toList(); filters.put(FIELD_RULE_TYPE, QueryBuilders.termsQuery(FIELD_RULE_TYPE, typeNames)); } if (query.getAvailableSinceLong() != null) { filters.put("availableSince", QueryBuilders.rangeQuery(FIELD_RULE_CREATED_AT) .gte(query.getAvailableSinceLong())); } if (isNotEmpty(query.getStatuses())) { Collection<String> stringStatus = new ArrayList<>(); for (RuleStatus status : query.getStatuses()) { stringStatus.add(status.name()); } filters.put(FIELD_RULE_STATUS, QueryBuilders.termsQuery(FIELD_RULE_STATUS, stringStatus)); } Boolean isTemplate = query.isTemplate(); if (isTemplate != null) { filters.put(FIELD_RULE_IS_TEMPLATE, QueryBuilders.termQuery(FIELD_RULE_IS_TEMPLATE, Boolean.toString(isTemplate))); } boolean includeExternal = query.includeExternal(); if (!includeExternal) { filters.put(FIELD_RULE_IS_EXTERNAL, QueryBuilders.termQuery(FIELD_RULE_IS_EXTERNAL, false)); } String template = query.templateKey(); if (template != null) { filters.put(FIELD_RULE_TEMPLATE_KEY, QueryBuilders.termQuery(FIELD_RULE_TEMPLATE_KEY, template)); } /* Implementation of activation query */ QProfileDto profile = query.getQProfile(); if (query.getActivation() != null && profile != null) { QueryBuilder childQuery = buildActivationFilter(query, profile); if (TRUE.equals(query.getActivation())) { filters.put("activation", JoinQueryBuilders.hasChildQuery(TYPE_ACTIVE_RULE.getName(), childQuery, ScoreMode.None)); } else if (FALSE.equals(query.getActivation())) { filters.put("activation", boolQuery().mustNot( JoinQueryBuilders.hasChildQuery(TYPE_ACTIVE_RULE.getName(), childQuery, ScoreMode.None))); } QProfileDto compareToQProfile = query.getCompareToQProfile(); if (compareToQProfile != null) { filters.put("comparison", JoinQueryBuilders.hasChildQuery( TYPE_ACTIVE_RULE.getName(), boolQuery().must(QueryBuilders.termQuery(FIELD_ACTIVE_RULE_PROFILE_UUID, compareToQProfile.getRulesProfileUuid())), ScoreMode.None)); } } return filters; } private static void addSecurityStandardFilter(Map<String, QueryBuilder> filters, String key, Collection<String> values) { if (isNotEmpty(values)) { filters.put(key, boolQuery() .must(QueryBuilders.termsQuery(key, values)) .must(QueryBuilders.termsQuery(FIELD_RULE_TYPE, VULNERABILITY.name(), SECURITY_HOTSPOT.name()))); } } private static void addFilter(Map<String, QueryBuilder> filters, Collection<String> key, String value) { if (isNotEmpty(key)) { filters.put(value, QueryBuilders.termsQuery(value, key)); } } private static void addFilter(Map<String, QueryBuilder> filters, String key, String value) { if (StringUtils.isNotEmpty(value)) { filters.put(key, QueryBuilders.termQuery(key, value)); } } private static BoolQueryBuilder buildTagsFilter(Collection<String> tags) { BoolQueryBuilder q = boolQuery(); for (String tag : tags) { q.should(boolQuery().filter(QueryBuilders.termQuery(FIELD_RULE_TAGS, tag))); } return q; } private static QueryBuilder buildActivationFilter(RuleQuery query, QProfileDto profile) { // ActiveRule Filter (profile and inheritance) BoolQueryBuilder activeRuleFilter = boolQuery(); addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid()); addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance()); addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_SEVERITY, query.getActiveSeverities()); // ChildQuery QueryBuilder childQuery; if (activeRuleFilter.hasClauses()) { childQuery = activeRuleFilter; } else { childQuery = matchAllQuery(); } return childQuery; } private static BoolQueryBuilder addTermFilter(BoolQueryBuilder filter, String field, @Nullable Collection<String> values) { if (isNotEmpty(values)) { BoolQueryBuilder valuesFilter = boolQuery(); for (String value : values) { QueryBuilder valueFilter = QueryBuilders.termQuery(field, value); valuesFilter.should(valueFilter); } filter.must(valuesFilter); } return filter; } private static BoolQueryBuilder addTermFilter(BoolQueryBuilder filter, String field, @Nullable String value) { if (StringUtils.isNotEmpty(value)) { filter.must(QueryBuilders.termQuery(field, value)); } return filter; } private static Map<String, AggregationBuilder> getFacets(RuleQuery query, SearchOptions options, QueryBuilder queryBuilder, Map<String, QueryBuilder> filters) { Map<String, AggregationBuilder> aggregations = new HashMap<>(); StickyFacetBuilder stickyFacetBuilder = stickyFacetBuilder(queryBuilder, filters); addDefaultFacets(query, options, aggregations, stickyFacetBuilder); addStatusFacetIfNeeded(options, aggregations, stickyFacetBuilder); if (options.getFacets().contains(FACET_SEVERITIES)) { aggregations.put(FACET_SEVERITIES, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_SEVERITY, FACET_SEVERITIES, Severity.ALL.toArray())); } addActiveSeverityFacetIfNeeded(query, options, aggregations, stickyFacetBuilder); return aggregations; } private static void addDefaultFacets(RuleQuery query, SearchOptions options, Map<String, AggregationBuilder> aggregations, StickyFacetBuilder stickyFacetBuilder) { if (options.getFacets().contains(FACET_LANGUAGES) || options.getFacets().contains(FACET_OLD_DEFAULT)) { Collection<String> languages = query.getLanguages(); aggregations.put(FACET_LANGUAGES, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_LANGUAGE, FACET_LANGUAGES, MAX_FACET_SIZE, (languages == null) ? (new String[0]) : languages.toArray())); } if (options.getFacets().contains(FACET_TAGS) || options.getFacets().contains(FACET_OLD_DEFAULT)) { Collection<String> tags = query.getTags(); aggregations.put(FACET_TAGS, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_TAGS, FACET_TAGS, MAX_FACET_SIZE, (tags == null) ? (new String[0]) : tags.toArray())); } if (options.getFacets().contains(FACET_TYPES)) { Collection<RuleType> types = query.getTypes(); aggregations.put(FACET_TYPES, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_TYPE, FACET_TYPES, (types == null) ? (new String[0]) : types.toArray())); } if (options.getFacets().contains(FACET_REPOSITORIES) || options.getFacets().contains(FACET_OLD_DEFAULT)) { Collection<String> repositories = query.getRepositories(); aggregations.put(FACET_REPOSITORIES, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_REPOSITORY, FACET_REPOSITORIES, MAX_FACET_SIZE, (repositories == null) ? (new String[0]) : repositories.toArray())); } addDefaultSecurityFacets(query, options, aggregations, stickyFacetBuilder); } private static Function<TermsAggregationBuilder, AggregationBuilder> filterSecurityCategories() { return termsAggregation -> AggregationBuilders.filter( "filter_by_rule_types_" + termsAggregation.getName(), termsQuery(FIELD_RULE_TYPE, VULNERABILITY.name(), SECURITY_HOTSPOT.name())) .subAggregation(termsAggregation); } private static void addDefaultSecurityFacets(RuleQuery query, SearchOptions options, Map<String, AggregationBuilder> aggregations, StickyFacetBuilder stickyFacetBuilder) { if (options.getFacets().contains(FACET_CWE)) { Collection<String> categories = query.getCwe(); aggregations.put(FACET_CWE, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_CWE, FACET_CWE, FACET_DEFAULT_SIZE, filterSecurityCategories(), (categories == null) ? (new String[0]) : categories.toArray())); } if (options.getFacets().contains(FACET_OWASP_TOP_10)) { Collection<String> categories = query.getOwaspTop10(); aggregations.put(FACET_OWASP_TOP_10, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_OWASP_TOP_10, FACET_OWASP_TOP_10, FACET_DEFAULT_SIZE, filterSecurityCategories(), (categories == null) ? (new String[0]) : categories.toArray())); } if (options.getFacets().contains(FACET_OWASP_TOP_10_2021)) { Collection<String> categories = query.getOwaspTop10For2021(); aggregations.put(FACET_OWASP_TOP_10_2021, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_OWASP_TOP_10_2021, FACET_OWASP_TOP_10_2021, FACET_DEFAULT_SIZE, filterSecurityCategories(), (categories == null) ? (new String[0]) : categories.toArray())); } if (options.getFacets().contains(FACET_SANS_TOP_25)) { Collection<String> categories = query.getSansTop25(); aggregations.put(FACET_SANS_TOP_25, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_SANS_TOP_25, FACET_SANS_TOP_25, FACET_DEFAULT_SIZE, filterSecurityCategories(), (categories == null) ? (new String[0]) : categories.toArray())); } if (options.getFacets().contains(FACET_SONARSOURCE_SECURITY)) { Collection<String> categories = query.getSonarsourceSecurity(); aggregations.put(FACET_SONARSOURCE_SECURITY, stickyFacetBuilder.buildStickyFacet(FIELD_RULE_SONARSOURCE_SECURITY, FACET_SONARSOURCE_SECURITY, SecurityStandards.SQCategory.values().length, filterSecurityCategories(), (categories == null) ? (new String[0]) : categories.toArray())); } } private static void addStatusFacetIfNeeded(SearchOptions options, Map<String, AggregationBuilder> aggregations, StickyFacetBuilder stickyFacetBuilder) { if (options.getFacets().contains(FACET_STATUSES)) { BoolQueryBuilder facetFilter = stickyFacetBuilder.getStickyFacetFilter(FIELD_RULE_STATUS); AggregationBuilder statuses = AggregationBuilders.filter(FACET_STATUSES + "_filter", facetFilter) .subAggregation( AggregationBuilders .terms(FACET_STATUSES) .field(FIELD_RULE_STATUS) .includeExclude(new IncludeExclude(Joiner.on('|').join(ALL_STATUSES_EXCEPT_REMOVED), RuleStatus.REMOVED.toString())) .size(ALL_STATUSES_EXCEPT_REMOVED.size())); aggregations.put(FACET_STATUSES, AggregationBuilders.global(FACET_STATUSES).subAggregation(statuses)); } } private static void addActiveSeverityFacetIfNeeded(RuleQuery query, SearchOptions options, Map<String, AggregationBuilder> aggregations, StickyFacetBuilder stickyFacetBuilder) { QProfileDto profile = query.getQProfile(); if (options.getFacets().contains(FACET_ACTIVE_SEVERITIES) && profile != null) { // We are building a children aggregation on active rules // so the rule filter has to be used as parent filter for active rules // from which we remove filters that concern active rules ("activation") HasParentQueryBuilder ruleFilter = JoinQueryBuilders.hasParentQuery( TYPE_RULE.getType(), stickyFacetBuilder.getStickyFacetFilter("activation"), false); // Rebuilding the active rule filter without severities BoolQueryBuilder childrenFilter = boolQuery(); addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid()); RuleIndex.addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance()); QueryBuilder activeRuleFilter = childrenFilter.must(ruleFilter); AggregationBuilder activeSeverities = JoinAggregationBuilders.children(FACET_ACTIVE_SEVERITIES + "_children", TYPE_ACTIVE_RULE.getName()) .subAggregation( AggregationBuilders.filter(FACET_ACTIVE_SEVERITIES + "_filter", activeRuleFilter) .subAggregation( AggregationBuilders .terms(FACET_ACTIVE_SEVERITIES) .field(FIELD_ACTIVE_RULE_SEVERITY) .includeExclude(new IncludeExclude(Joiner.on('|').join(Severity.ALL), null)) .size(Severity.ALL.size()))); aggregations.put(FACET_ACTIVE_SEVERITIES, AggregationBuilders.global(FACET_ACTIVE_SEVERITIES).subAggregation(activeSeverities)); } } private static StickyFacetBuilder stickyFacetBuilder(QueryBuilder query, Map<String, QueryBuilder> filters) { return new StickyFacetBuilder(query, filters, null, BucketOrder.compound(BucketOrder.count(false), BucketOrder.key(true))); } private static void setSorting(RuleQuery query, SearchSourceBuilder esSearch) { /* integrate Query Sort */ String queryText = query.getQueryText(); if (query.getSortField() != null) { FieldSortBuilder sort = SortBuilders.fieldSort(appendSortSuffixIfNeeded(query.getSortField())); if (query.isAscendingSort()) { sort.order(SortOrder.ASC); } else { sort.order(SortOrder.DESC); } esSearch.sort(sort); } else if (StringUtils.isNotEmpty(queryText)) { esSearch.sort(SortBuilders.scoreSort()); } else { esSearch.sort(appendSortSuffixIfNeeded(FIELD_RULE_UPDATED_AT), SortOrder.DESC); // deterministic sort when exactly the same updated_at (same millisecond) esSearch.sort(appendSortSuffixIfNeeded(FIELD_RULE_KEY), SortOrder.ASC); } } private static String appendSortSuffixIfNeeded(String field) { return field + ((field.equals(FIELD_RULE_NAME) || field.equals(FIELD_RULE_KEY)) ? ("." + SORTABLE_ANALYZER.getSubFieldSuffix()) : ""); } private static void setPagination(SearchOptions options, SearchSourceBuilder esSearch) { esSearch.from(options.getOffset()); esSearch.size(options.getLimit()); } public List<String> listTags(@Nullable String query, int size) { int maxPageSize = 500; checkArgument(size <= maxPageSize, "Page size must be lower than or equals to " + maxPageSize); if (size <= 0) { return emptyList(); } TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(AGGREGATION_NAME_FOR_TAGS) .field(FIELD_RULE_TAGS) .size(size) .order(BucketOrder.key(true)) .minDocCount(1); ofNullable(query) .map(EsUtils::escapeSpecialRegexChars) .map(queryString -> ".*" + queryString + ".*") .map(s -> new IncludeExclude(s, null)) .ifPresent(termsAggregation::includeExclude); SearchRequest request = EsClient.prepareSearch(TYPE_RULE.getMainType()) .source(new SearchSourceBuilder() .query(matchAllQuery()) .size(0) .aggregation(termsAggregation)); SearchResponse esResponse = client.search(request); return EsUtils.termsKeys(esResponse.getAggregations().get(AGGREGATION_NAME_FOR_TAGS)); } private static boolean isNotEmpty(@Nullable Collection<?> list) { return list != null && !list.isEmpty(); } }
28,273
43.666667
165
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.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.rule.index; import com.google.common.collect.ImmutableSet; import java.util.Set; import javax.inject.Inject; import org.sonar.api.config.Configuration; 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.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import org.sonar.server.es.newindex.NewRegularIndex; import org.sonar.server.es.newindex.TypeMapping; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.ENGLISH_HTML_ANALYZER; 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.es.newindex.SettingsConfiguration.MANUAL_REFRESH_INTERVAL; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; /** * Definition of ES index "rules", including settings and fields. */ public class RuleIndexDefinition implements IndexDefinition { public static final Index DESCRIPTOR = Index.withRelations("rules"); public static final IndexMainType TYPE_RULE = IndexType.main(DESCRIPTOR, "rule"); public static final String FIELD_RULE_UUID = "ruleUuid"; public static final String FIELD_RULE_KEY = "key"; public static final String FIELD_RULE_REPOSITORY = "repo"; public static final String FIELD_RULE_RULE_KEY = "ruleKey"; public static final String FIELD_RULE_INTERNAL_KEY = "internalKey"; public static final String FIELD_RULE_NAME = "name"; public static final String FIELD_RULE_HTML_DESCRIPTION = "htmlDesc"; public static final String FIELD_RULE_SEVERITY = "severity"; public static final String FIELD_RULE_STATUS = "status"; public static final String FIELD_RULE_LANGUAGE = "lang"; public static final String FIELD_RULE_IS_TEMPLATE = "isTemplate"; public static final String FIELD_RULE_IS_EXTERNAL = "isExternal"; public static final String FIELD_RULE_TEMPLATE_KEY = "templateKey"; public static final String FIELD_RULE_TYPE = "type"; public static final String FIELD_RULE_CREATED_AT = "createdAt"; public static final String FIELD_RULE_UPDATED_AT = "updatedAt"; public static final String FIELD_RULE_CWE = "cwe"; public static final String FIELD_RULE_OWASP_TOP_10 = "owaspTop10"; public static final String FIELD_RULE_OWASP_TOP_10_2021 = "owaspTop10-2021"; public static final String FIELD_RULE_SANS_TOP_25 = "sansTop25"; public static final String FIELD_RULE_SONARSOURCE_SECURITY = "sonarsourceSecurity"; public static final String FIELD_RULE_TAGS = "tags"; public static final Set<String> SORT_FIELDS = ImmutableSet.of( FIELD_RULE_NAME, FIELD_RULE_UPDATED_AT, FIELD_RULE_CREATED_AT, FIELD_RULE_KEY); // Active rule fields public static final IndexRelationType TYPE_ACTIVE_RULE = IndexType.relation(TYPE_RULE, "activeRule"); public static final String FIELD_ACTIVE_RULE_UUID = "activeRule_uuid"; public static final String FIELD_ACTIVE_RULE_INHERITANCE = "activeRule_inheritance"; public static final String FIELD_ACTIVE_RULE_PROFILE_UUID = "activeRule_ruleProfile"; public static final String FIELD_ACTIVE_RULE_SEVERITY = "activeRule_severity"; private final Configuration config; private final boolean enableSource; @Inject public RuleIndexDefinition(Configuration config) { this(config, false); } private RuleIndexDefinition(Configuration config, boolean enableSource) { this.config = config; this.enableSource = enableSource; } /** * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ public static RuleIndexDefinition createForTest() { return new RuleIndexDefinition(new MapSettings().asConfig(), true); } @Override public void define(IndexDefinitionContext context) { NewRegularIndex index = context.create( DESCRIPTOR, newBuilder(config) .setRefreshInterval(MANUAL_REFRESH_INTERVAL) // Default nb of shards should be greater than 1 in order to // easily detect routing misconfiguration. // See https://jira.sonarsource.com/browse/SONAR-9489 .setDefaultNbOfShards(2) .build()) .setEnableSource(enableSource); // Rule type TypeMapping ruleMapping = index.createTypeMapping(TYPE_RULE); ruleMapping.keywordFieldBuilder(FIELD_RULE_UUID).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_KEY).addSubFields(SORTABLE_ANALYZER).build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_RULE_KEY).addSubFields(SORTABLE_ANALYZER).build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_REPOSITORY).build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_INTERNAL_KEY).disableNorms().disableSearch().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_NAME).addSubFields(SORTABLE_ANALYZER, SEARCH_GRAMS_ANALYZER).build(); ruleMapping.textFieldBuilder(FIELD_RULE_HTML_DESCRIPTION) .disableSearch() .disableNorms() .addSubFields(ENGLISH_HTML_ANALYZER) .build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_SEVERITY).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_STATUS).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_LANGUAGE).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_TAGS).build(); ruleMapping.createBooleanField(FIELD_RULE_IS_TEMPLATE); ruleMapping.createBooleanField(FIELD_RULE_IS_EXTERNAL); ruleMapping.keywordFieldBuilder(FIELD_RULE_TEMPLATE_KEY).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_TYPE).disableNorms().build(); ruleMapping.createLongField(FIELD_RULE_CREATED_AT); ruleMapping.createLongField(FIELD_RULE_UPDATED_AT); ruleMapping.keywordFieldBuilder(FIELD_RULE_CWE).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_OWASP_TOP_10).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_OWASP_TOP_10_2021).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_SANS_TOP_25).disableNorms().build(); ruleMapping.keywordFieldBuilder(FIELD_RULE_SONARSOURCE_SECURITY).disableNorms().build(); // Active rule index.createTypeMapping(TYPE_ACTIVE_RULE) .keywordFieldBuilder(FIELD_ACTIVE_RULE_UUID).disableNorms().build() .keywordFieldBuilder(FIELD_ACTIVE_RULE_PROFILE_UUID).disableNorms().build() .keywordFieldBuilder(FIELD_ACTIVE_RULE_INHERITANCE).disableNorms().build() .keywordFieldBuilder(FIELD_ACTIVE_RULE_SEVERITY).disableNorms().build(); } }
7,537
46.1125
116
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleIndexer.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.rule.index; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; import org.sonar.db.rule.RuleForIndexingDto; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.BulkIndexer.Size; import org.sonar.server.es.EsClient; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexingListener; import org.sonar.server.es.IndexingResult; import org.sonar.server.es.OneToOneResilientIndexingListener; import org.sonar.server.es.ResilientIndexer; import org.sonar.server.security.SecurityStandards; import static java.util.Arrays.asList; import static java.util.stream.Collectors.joining; import static java.util.stream.Stream.concat; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; import static org.sonar.server.security.SecurityStandards.SQ_CATEGORY_KEYS_ORDERING; public class RuleIndexer implements ResilientIndexer { private static final Logger LOG = LoggerFactory.getLogger(RuleIndexer.class); private final EsClient esClient; private final DbClient dbClient; public RuleIndexer(EsClient esClient, DbClient dbClient) { this.esClient = esClient; this.dbClient = dbClient; } @Override public Set<IndexType> getIndexTypes() { return ImmutableSet.of(TYPE_RULE); } @Override public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) { if (uninitializedIndexTypes.contains(TYPE_RULE)) { indexAll(Size.LARGE); } } public void indexAll() { indexAll(Size.REGULAR); } private void indexAll(Size bulkSize) { try (DbSession dbSession = dbClient.openSession(false)) { BulkIndexer bulk = createBulkIndexer(bulkSize, IndexingListener.FAIL_ON_ERROR); bulk.start(); dbClient.ruleDao().selectIndexingRules(dbSession, dto -> bulk.add(ruleDocOf(dto).toIndexRequest())); bulk.stop(); } } public void commitAndIndex(DbSession dbSession, Collection<String> ruleUuids) { List<EsQueueDto> items = ruleUuids.stream() .map(RuleIndexer::createQueueDtoForRule) .toList(); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); } /** * Commit a change on a rule and its extension */ public void commitAndIndex(DbSession dbSession, String ruleUuid) { List<EsQueueDto> items = asList(createQueueDtoForRule(ruleUuid)); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); } /** * This method is used by the Byteman script of integration tests. */ private void postCommit(DbSession dbSession, List<EsQueueDto> items) { index(dbSession, items); } @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { IndexingResult result = new IndexingResult(); if (!items.isEmpty()) { ListMultimap<String, EsQueueDto> itemsByType = groupItemsByIndexTypeFormat(items); doIndexRules(dbSession, itemsByType.get(TYPE_RULE.format())).ifPresent(result::add); } return result; } private Optional<IndexingResult> doIndexRules(DbSession dbSession, List<EsQueueDto> items) { if (items.isEmpty()) { return Optional.empty(); } BulkIndexer bulkIndexer = createBulkIndexer(Size.REGULAR, new OneToOneResilientIndexingListener(dbClient, dbSession, items)); bulkIndexer.start(); Set<String> ruleUuids = items .stream() .map(EsQueueDto::getDocId) .collect(Collectors.toSet()); dbClient.ruleDao().selectIndexingRulesByKeys(dbSession, ruleUuids, r -> { bulkIndexer.add(ruleDocOf(r).toIndexRequest()); ruleUuids.remove(r.getUuid()); }); // the remaining items reference rows that don't exist in db. They must be deleted from index. ruleUuids.forEach(ruleUuid -> bulkIndexer.addDeletion(TYPE_RULE, ruleUuid, ruleUuid)); return Optional.of(bulkIndexer.stop()); } private static RuleDoc ruleDocOf(RuleForIndexingDto dto) { SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(dto.getSecurityStandards()); if (!securityStandards.getIgnoredSQCategories().isEmpty()) { LOG.debug( "Rule {} with CWEs '{}' maps to multiple SQ Security Categories: {}", dto.getRuleKey(), String.join(", ", securityStandards.getCwe()), concat(Stream.of(securityStandards.getSqCategory()), securityStandards.getIgnoredSQCategories().stream()) .map(SecurityStandards.SQCategory::getKey) .sorted(SQ_CATEGORY_KEYS_ORDERING) .collect(joining(", "))); } return RuleDoc.createFrom(dto, securityStandards); } private BulkIndexer createBulkIndexer(Size bulkSize, IndexingListener listener) { return new BulkIndexer(esClient, TYPE_RULE, bulkSize, listener); } private static ListMultimap<String, EsQueueDto> groupItemsByIndexTypeFormat(Collection<EsQueueDto> items) { return items.stream().collect(MoreCollectors.index(EsQueueDto::getDocType)); } private static EsQueueDto createQueueDtoForRule(String ruleUuid) { return EsQueueDto.create(TYPE_RULE.format(), ruleUuid, null, ruleUuid); } }
6,404
34.782123
129
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleQuery.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.rule.index; import com.google.common.base.Preconditions; import java.util.Collection; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.db.qualityprofile.QProfileDto; import static java.util.Arrays.asList; public class RuleQuery { private String key; private String queryText; private Collection<String> languages; private Collection<String> repositories; private Collection<String> severities; private Collection<RuleStatus> statuses; private Collection<String> tags; private Collection<RuleType> types; private Boolean activation; private QProfileDto profile; private QProfileDto compareToQProfile; private Collection<String> inheritance; private Collection<String> activeSeverities; private String templateKey; private Boolean isTemplate; private Long availableSince; private String sortField; private boolean ascendingSort = true; private String internalKey; private String ruleKey; private boolean includeExternal; private Collection<String> owaspTop10; private Collection<String> owaspTop10For2021; private Collection<String> sansTop25; private Collection<String> cwe; private Collection<String> sonarsourceSecurity; @CheckForNull public QProfileDto getQProfile() { return profile; } public RuleQuery setQProfile(@Nullable QProfileDto p) { this.profile = p; return this; } public RuleQuery setActivation(@Nullable Boolean activation) { this.activation = activation; return this; } @CheckForNull public Boolean getActivation() { return this.activation; } @CheckForNull public String getKey() { return key; } public RuleQuery setKey(@Nullable String key) { this.key = key; return this; } @CheckForNull public String getQueryText() { return queryText; } /** * Ignored if null or blank */ public RuleQuery setQueryText(@Nullable String queryText) { this.queryText = queryText; return this; } @CheckForNull public Collection<String> getLanguages() { return languages; } public RuleQuery setLanguages(@Nullable Collection<String> languages) { this.languages = languages; return this; } @CheckForNull public Collection<String> getRepositories() { return repositories; } public RuleQuery setRepositories(@Nullable Collection<String> repositories) { this.repositories = repositories; return this; } @CheckForNull public Collection<String> getSeverities() { return severities; } public RuleQuery setSeverities(@Nullable Collection<String> severities) { if (severities != null) { for (String severity : severities) { Preconditions.checkArgument(Severity.ALL.contains(severity), "Unknown severity: " + severity); } } this.severities = severities; return this; } public RuleQuery setSeverities(@Nullable String... severities) { if (severities != null) { return setSeverities(asList(severities)); } return this; } @CheckForNull public Collection<RuleStatus> getStatuses() { return statuses; } public RuleQuery setStatuses(@Nullable Collection<RuleStatus> statuses) { this.statuses = statuses; return this; } @CheckForNull public Collection<String> getTags() { return tags; } public RuleQuery setTags(@Nullable Collection<String> tags) { this.tags = tags; return this; } @CheckForNull public Collection<RuleType> getTypes() { return types; } public RuleQuery setTypes(@Nullable Collection<RuleType> types) { this.types = types; return this; } @CheckForNull public Collection<String> getInheritance() { return inheritance; } public RuleQuery setInheritance(@Nullable Collection<String> inheritance) { this.inheritance = inheritance; return this; } @CheckForNull public Collection<String> getActiveSeverities() { return activeSeverities; } public RuleQuery setActiveSeverities(@Nullable Collection<String> severities) { if (severities != null) { for (String severity : severities) { Preconditions.checkArgument(Severity.ALL.contains(severity), "Unknown severity: " + severity); } } this.activeSeverities = severities; return this; } @CheckForNull public Boolean isTemplate() { return isTemplate; } public RuleQuery setIsTemplate(@Nullable Boolean b) { this.isTemplate = b; return this; } public boolean includeExternal() { return includeExternal; } public RuleQuery setIncludeExternal(boolean b) { this.includeExternal = b; return this; } @CheckForNull public String templateKey() { return templateKey; } public RuleQuery setTemplateKey(@Nullable String templateKey) { this.templateKey = templateKey; return this; } public String getSortField() { return this.sortField; } public RuleQuery setSortField(@Nullable String field) { if (field != null && !RuleIndexDefinition.SORT_FIELDS.contains(field)) { throw new IllegalStateException(String.format("Field '%s' is not sortable", field)); } this.sortField = field; return this; } public boolean isAscendingSort() { return ascendingSort; } public RuleQuery setAscendingSort(boolean b) { this.ascendingSort = b; return this; } public RuleQuery setAvailableSince(@Nullable Long l) { this.availableSince = l; return this; } public Long getAvailableSinceLong() { return this.availableSince; } public RuleQuery setInternalKey(@Nullable String s) { this.internalKey = s; return this; } @CheckForNull public String getInternalKey() { return internalKey; } public RuleQuery setRuleKey(@Nullable String s) { this.ruleKey = s; return this; } @CheckForNull public String getRuleKey() { return ruleKey; } @CheckForNull public QProfileDto getCompareToQProfile() { return compareToQProfile; } public RuleQuery setCompareToQProfile(@Nullable QProfileDto compareToQProfile) { this.compareToQProfile = compareToQProfile; return this; } @CheckForNull public Collection<String> getCwe() { return cwe; } public RuleQuery setCwe(@Nullable Collection<String> cwe) { this.cwe = cwe; return this; } @CheckForNull public Collection<String> getOwaspTop10() { return owaspTop10; } public RuleQuery setOwaspTop10(@Nullable Collection<String> owaspTop10) { this.owaspTop10 = owaspTop10; return this; } @CheckForNull public Collection<String> getOwaspTop10For2021() { return owaspTop10For2021; } public RuleQuery setOwaspTop10For2021(@Nullable Collection<String> owaspTop10For2021) { this.owaspTop10For2021 = owaspTop10For2021; return this; } @CheckForNull public Collection<String> getSansTop25() { return sansTop25; } public RuleQuery setSansTop25(@Nullable Collection<String> sansTop25) { this.sansTop25 = sansTop25; return this; } @CheckForNull public Collection<String> getSonarsourceSecurity() { return sonarsourceSecurity; } public RuleQuery setSonarsourceSecurity(@Nullable Collection<String> sonarsourceSecurity) { this.sonarsourceSecurity = sonarsourceSecurity; return this; } }
8,285
23.29912
102
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/rule/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.rule.index; import javax.annotation.ParametersAreNonnullByDefault;
967
41.086957
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/security/SecurityReviewRating.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.security; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.server.measure.Rating; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; import static org.sonar.server.measure.Rating.C; import static org.sonar.server.measure.Rating.D; import static org.sonar.server.measure.Rating.E; public class SecurityReviewRating { private SecurityReviewRating() { // Only static method } public static Optional<Double> computePercent(long hotspotsToReview, long hotspotsReviewed) { long total = hotspotsToReview + hotspotsReviewed; if (total == 0) { return Optional.empty(); } return Optional.of(hotspotsReviewed * 100.0D / total); } public static Rating computeRating(@Nullable Double percent) { if (percent == null || percent >= 80.0D) { return A; } else if (percent >= 70.0D) { return B; } else if (percent >= 50.0D) { return C; } else if (percent >= 30.0D) { return D; } return E; } }
1,910
31.389831
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/security/SecurityStandards.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.security; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Ordering; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.server.rule.RulesDefinition.OwaspAsvsVersion; import org.sonar.api.server.rule.RulesDefinition.PciDssVersion; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.sonar.api.server.rule.RulesDefinition.PciDssVersion.V3_2; import static org.sonar.server.security.SecurityStandards.VulnerabilityProbability.HIGH; import static org.sonar.server.security.SecurityStandards.VulnerabilityProbability.LOW; import static org.sonar.server.security.SecurityStandards.VulnerabilityProbability.MEDIUM; @Immutable public final class SecurityStandards { public static final String UNKNOWN_STANDARD = "unknown"; /** * @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0 */ @Deprecated(since = "10.0", forRemoval = true) public static final String SANS_TOP_25_INSECURE_INTERACTION = "insecure-interaction"; @Deprecated(since = "10.0", forRemoval = true) public static final String SANS_TOP_25_RISKY_RESOURCE = "risky-resource"; @Deprecated(since = "10.0", forRemoval = true) public static final String SANS_TOP_25_POROUS_DEFENSES = "porous-defenses"; private static final String OWASP_TOP10_PREFIX = "owaspTop10:"; private static final String OWASP_TOP10_2021_PREFIX = "owaspTop10-2021:"; private static final String PCI_DSS_32_PREFIX = V3_2.prefix() + ":"; private static final String PCI_DSS_40_PREFIX = PciDssVersion.V4_0.prefix() + ":"; private static final String OWASP_ASVS_40_PREFIX = OwaspAsvsVersion.V4_0.prefix() + ":"; private static final String CWE_PREFIX = "cwe:"; // See https://www.sans.org/top25-software-errors /** * @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0 */ @Deprecated(since = "10.0", forRemoval = true) private static final Set<String> INSECURE_CWE = new HashSet<>(asList("89", "78", "79", "434", "352", "601")); @Deprecated(since = "10.0", forRemoval = true) private static final Set<String> RISKY_CWE = new HashSet<>(asList("120", "22", "494", "829", "676", "131", "134", "190")); @Deprecated(since = "10.0", forRemoval = true) private static final Set<String> POROUS_CWE = new HashSet<>(asList("306", "862", "798", "311", "807", "250", "863", "732", "327", "307", "759")); /** * @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0 */ @Deprecated public static final Map<String, Set<String>> CWES_BY_SANS_TOP_25 = ImmutableMap.of( SANS_TOP_25_INSECURE_INTERACTION, INSECURE_CWE, SANS_TOP_25_RISKY_RESOURCE, RISKY_CWE, SANS_TOP_25_POROUS_DEFENSES, POROUS_CWE); // https://cwe.mitre.org/top25/archive/2020/2020_cwe_top25.html public static final List<String> CWE_TOP25_2020 = List.of("79", "787", "20", "125", "119", "89", "200", "416", "352", "78", "190", "22", "476", "287", "434", "732", "94", "522", "611", "798", "502", "269", "400", "306", "862"); // https://cwe.mitre.org/top25/archive/2021/2021_cwe_top25.html public static final List<String> CWE_TOP25_2021 = List.of("787", "79", "125", "20", "78", "89", "416", "22", "352", "434", "306", "190", "502", "287", "476", "798", "119", "862", "276", "200", "522", "732", "611", "918", "77"); // https://cwe.mitre.org/top25/archive/2022/2022_cwe_top25.html public static final List<String> CWE_TOP25_2022 = List.of("787", "79", "89", "20", "125", "78", "416", "22", "352", "434", "476", "502", "190", "287", "798", "862", "77", "306", "119", "276", "918", "362", "400", "611", "94"); public static final String CWE_YEAR_2020 = "2020"; public static final String CWE_YEAR_2021 = "2021"; public static final String CWE_YEAR_2022 = "2022"; public static final Map<String, List<String>> CWES_BY_CWE_TOP_25 = Map.of( CWE_YEAR_2020, CWE_TOP25_2020, CWE_YEAR_2021, CWE_TOP25_2021, CWE_YEAR_2022, CWE_TOP25_2022); private static final List<String> OWASP_ASVS_40_LEVEL_1 = List.of("2.1.1", "2.1.10", "2.1.11", "2.1.12", "2.1.2", "2.1.3", "2.1.4", "2.1.5", "2.1.6", "2.1.7", "2.1.8", "2.1.9", "2.10.1", "2.10.2", "2.10.3", "2.10.4", "2.2.1", "2.2.2", "2.2.3", "2.3.1", "2.5.1", "2.5.2", "2.5.3", "2.5.4", "2.5.5", "2.5.6", "2.7.1", "2.7.2", "2.7.3", "2.7.4", "2.8.1", "3.1.1", "3.2.1", "3.2.2", "3.2.3", "3.3.1", "3.3.2", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.7.1", "4.1.1", "4.1.2", "4.1.3", "4.1.4", "4.1.5", "4.2.1", "4.2.2", "4.3.1", "4.3.2", "5.1.1", "5.1.2", "5.1.3", "5.1.4", "5.1.5", "5.2.1", "5.2.2", "5.2.3", "5.2.4", "5.2.5", "5.2.6", "5.2.7", "5.2.8", "5.3.1", "5.3.10", "5.3.2", "5.3.3", "5.3.4", "5.3.5", "5.3.6", "5.3.7", "5.3.8", "5.3.9", "5.5.1", "5.5.2", "5.5.3", "5.5.4", "6.2.1", "7.1.1", "7.1.2", "7.4.1", "8.2.1", "8.2.2", "8.2.3", "8.3.1", "8.3.2", "8.3.3", "8.3.4", "9.1.1", "9.1.2", "9.1.3", "10.3.1", "10.3.2", "10.3.3", "11.1.1", "11.1.2", "11.1.3", "11.1.4", "11.1.5", "12.1.1", "12.3.1", "12.3.2", "12.3.3", "12.3.4", "12.3.5", "12.4.1", "12.4.2", "12.5.1", "12.5.2", "12.6.1", "13.1.1", "13.1.2", "13.1.3", "13.2.1", "13.2.2", "13.2.3", "13.3.1", "14.2.1", "14.2.2", "14.2.3", "14.3.1", "14.3.2", "14.3.3", "14.4.1", "14.4.2", "14.4.3", "14.4.4", "14.4.5", "14.4.6", "14.4.7", "14.5.1", "14.5.2", "14.5.3"); private static final List<String> OWASP_ASVS_40_LEVEL_2 = Stream.concat(Stream.of("1.1.1", "1.1.2", "1.1.3", "1.1.4", "1.1.5", "1.1.6", "1.1.7", "1.10.1", "1.11.1", "1.11.2", "1.12.1", "1.12.2", "1.14.1", "1.14.2", "1.14.3", "1.14.4", "1.14.5", "1.14.6", "1.2.1", "1.2.2", "1.2.3", "1.2.4", "1.4.1", "1.4.2", "1.4.3", "1.4.4", "1.4.5", "1.5.1", "1.5.2", "1.5.3", "1.5.4", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.7.1", "1.7.2", "1.8.1", "1.8.2", "1.9.1", "1.9.2", "2.3.2", "2.3.3", "2.4.1", "2.4.2", "2.4.3", "2.4.4", "2.4.5", "2.5.7", "2.6.1", "2.6.2", "2.6.3", "2.7.5", "2.7.6", "2.8.2", "2.8.3", "2.8.4", "2.8.5", "2.8.6", "2.9.1", "2.9.2", "2.9.3", "3.2.4", "3.3.3", "3.3.4", "3.5.1", "3.5.2", "3.5.3", "4.3.3", "5.4.1", "5.4.2", "5.4.3", "6.1.1", "6.1.2", "6.1.3", "6.2.2", "6.2.3", "6.2.4", "6.2.5", "6.2.6", "6.3.1", "6.3.2", "6.4.1", "6.4.2", "7.1.3", "7.1.4", "7.2.1", "7.2.2", "7.3.1", "7.3.2", "7.3.3", "7.3.4", "7.4.2", "7.4.3", "8.1.1", "8.1.2", "8.1.3", "8.1.4", "8.3.5", "8.3.6", "8.3.7", "8.3.8", "9.2.1", "9.2.2", "9.2.3", "9.2.4", "10.2.1", "10.2.2", "11.1.6", "11.1.7", "11.1.8", "12.1.2", "12.1.3", "12.2.1", "12.3.6", "13.1.4", "13.1.5", "13.2.4", "13.2.5", "13.2.6", "13.3.2", "13.4.1", "13.4.2", "14.1.1", "14.1.2", "14.1.3", "14.1.4", "14.2.4", "14.2.5", "14.2.6", "14.5.4"), OWASP_ASVS_40_LEVEL_1.stream()) .toList(); private static final List<String> OWASP_ASVS_40_LEVEL_3 = Stream .concat(Stream.of("1.11.3", "2.2.4", "2.2.5", "2.2.6", "2.2.7", "2.8.7", "3.6.1", "3.6.2", "6.2.7", "6.2.8", "6.3.3", "8.1.5", "8.1.6", "9.2.5", "10.1.1", "10.2.3", "10.2.4", "10.2.5", "10.2.6", "14.1.5"), OWASP_ASVS_40_LEVEL_2.stream()) .toList(); public static final Map<Integer, List<String>> OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL = Map.of( 1, OWASP_ASVS_40_LEVEL_1, 2, OWASP_ASVS_40_LEVEL_2, 3, OWASP_ASVS_40_LEVEL_3); public static final Map<OwaspAsvsVersion, Map<Integer, List<String>>> OWASP_ASVS_REQUIREMENTS_BY_LEVEL = Map.of( OwaspAsvsVersion.V4_0, OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL); public enum VulnerabilityProbability { HIGH(3), MEDIUM(2), LOW(1); private final int score; VulnerabilityProbability(int index) { this.score = index; } public int getScore() { return score; } public static Optional<VulnerabilityProbability> byScore(@Nullable Integer score) { if (score == null) { return Optional.empty(); } return Arrays.stream(values()) .filter(t -> t.score == score) .findFirst(); } } public enum SQCategory { BUFFER_OVERFLOW("buffer-overflow", HIGH), SQL_INJECTION("sql-injection", HIGH), RCE("rce", MEDIUM), OBJECT_INJECTION("object-injection", LOW), COMMAND_INJECTION("command-injection", HIGH), PATH_TRAVERSAL_INJECTION("path-traversal-injection", HIGH), LDAP_INJECTION("ldap-injection", LOW), XPATH_INJECTION("xpath-injection", LOW), LOG_INJECTION("log-injection", LOW), XXE("xxe", MEDIUM), XSS("xss", HIGH), DOS("dos", MEDIUM), SSRF("ssrf", MEDIUM), CSRF("csrf", HIGH), HTTP_RESPONSE_SPLITTING("http-response-splitting", LOW), OPEN_REDIRECT("open-redirect", MEDIUM), WEAK_CRYPTOGRAPHY("weak-cryptography", MEDIUM), AUTH("auth", HIGH), INSECURE_CONF("insecure-conf", LOW), FILE_MANIPULATION("file-manipulation", LOW), ENCRYPTION_OF_SENSITIVE_DATA("encrypt-data", LOW), TRACEABILITY("traceability", LOW), PERMISSION("permission", MEDIUM), OTHERS("others", LOW); private static final Map<String, SQCategory> SQ_CATEGORY_BY_KEY = stream(values()).collect(Collectors.toMap(SQCategory::getKey, Function.identity())); private final String key; private final VulnerabilityProbability vulnerability; SQCategory(String key, VulnerabilityProbability vulnerability) { this.key = key; this.vulnerability = vulnerability; } public String getKey() { return key; } public VulnerabilityProbability getVulnerability() { return vulnerability; } public static Optional<SQCategory> fromKey(@Nullable String key) { return Optional.ofNullable(key).map(SQ_CATEGORY_BY_KEY::get); } } public enum PciDss { R1("1"), R2("2"), R3("3"), R4("4"), R5("5"), R6("6"), R7("7"), R8("8"), R9("9"), R10("10"), R11("11"), R12("12"); private final String category; PciDss(String category) { this.category = category; } public String category() { return category; } } public enum OwaspAsvs { C1("1"), C2("2"), C3("3"), C4("4"), C5("5"), C6("6"), C7("7"), C8("8"), C9("9"), C10("10"), C11("11"), C12("12"), C13("13"), C14("14"); private final String category; OwaspAsvs(String category) { this.category = category; } public String category() { return category; } } public static final Map<SQCategory, Set<String>> CWES_BY_SQ_CATEGORY = ImmutableMap.<SQCategory, Set<String>>builder() .put(SQCategory.BUFFER_OVERFLOW, Set.of("119", "120", "131", "676", "788")) .put(SQCategory.SQL_INJECTION, Set.of("89", "564", "943")) .put(SQCategory.COMMAND_INJECTION, Set.of("77", "78", "88", "214")) .put(SQCategory.PATH_TRAVERSAL_INJECTION, Set.of("22")) .put(SQCategory.LDAP_INJECTION, Set.of("90")) .put(SQCategory.XPATH_INJECTION, Set.of("643")) .put(SQCategory.RCE, Set.of("94", "95")) .put(SQCategory.DOS, Set.of("400", "624")) .put(SQCategory.SSRF, Set.of("918")) .put(SQCategory.CSRF, Set.of("352")) .put(SQCategory.XSS, Set.of("79", "80", "81", "82", "83", "84", "85", "86", "87")) .put(SQCategory.LOG_INJECTION, Set.of("117")) .put(SQCategory.HTTP_RESPONSE_SPLITTING, Set.of("113")) .put(SQCategory.OPEN_REDIRECT, Set.of("601")) .put(SQCategory.XXE, Set.of("611", "827")) .put(SQCategory.OBJECT_INJECTION, Set.of("134", "470", "502")) .put(SQCategory.WEAK_CRYPTOGRAPHY, Set.of("295", "297", "321", "322", "323", "324", "325", "326", "327", "328", "330", "780")) .put(SQCategory.AUTH, Set.of("798", "640", "620", "549", "522", "521", "263", "262", "261", "259", "308")) .put(SQCategory.INSECURE_CONF, Set.of("102", "215", "346", "614", "489", "942")) .put(SQCategory.FILE_MANIPULATION, Set.of("97", "73")) .put(SQCategory.ENCRYPTION_OF_SENSITIVE_DATA, Set.of("311", "315", "319")) .put(SQCategory.TRACEABILITY, Set.of("778")) .put(SQCategory.PERMISSION, Set.of("266", "269", "284", "668", "732")) .build(); private static final Ordering<SQCategory> SQ_CATEGORY_ORDERING = Ordering.explicit(stream(SQCategory.values()).toList()); public static final Ordering<String> SQ_CATEGORY_KEYS_ORDERING = Ordering.explicit(stream(SQCategory.values()).map(SQCategory::getKey).toList()); private final Set<String> standards; private final Set<String> cwe; private final SQCategory sqCategory; private final Set<SQCategory> ignoredSQCategories; private SecurityStandards(Set<String> standards, Set<String> cwe, SQCategory sqCategory, Set<SQCategory> ignoredSQCategories) { this.standards = standards; this.cwe = cwe; this.sqCategory = sqCategory; this.ignoredSQCategories = ignoredSQCategories; } public Set<String> getStandards() { return standards; } public Set<String> getCwe() { return cwe; } public Set<String> getPciDss32() { return getMatchingStandards(standards, PCI_DSS_32_PREFIX); } public Set<String> getPciDss40() { return getMatchingStandards(standards, PCI_DSS_40_PREFIX); } public Set<String> getOwaspAsvs40() { return getMatchingStandards(standards, OWASP_ASVS_40_PREFIX); } public Set<String> getOwaspTop10() { return getMatchingStandards(standards, OWASP_TOP10_PREFIX); } public Set<String> getOwaspTop10For2021() { return getMatchingStandards(standards, OWASP_TOP10_2021_PREFIX); } /** * @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0 */ @Deprecated public Set<String> getSansTop25() { return toSansTop25(cwe); } public Set<String> getCweTop25() { return toCweTop25(cwe); } public SQCategory getSqCategory() { return sqCategory; } /** * If CWEs mapped to multiple {@link SQCategory}, those which are not taken into account are listed here. */ public Set<SQCategory> getIgnoredSQCategories() { return ignoredSQCategories; } /** * @throws IllegalStateException if {@code securityStandards} maps to multiple {@link SQCategory SQCategories} */ public static SecurityStandards fromSecurityStandards(Set<String> securityStandards) { Set<String> standards = securityStandards.stream().filter(Objects::nonNull).collect(Collectors.toSet()); Set<String> cwe = toCwes(standards); List<SQCategory> sq = toSortedSQCategories(cwe); SQCategory sqCategory = sq.iterator().next(); Set<SQCategory> ignoredSQCategories = sq.stream().skip(1).collect(Collectors.toSet()); return new SecurityStandards(standards, cwe, sqCategory, ignoredSQCategories); } public static Set<String> getRequirementsForCategoryAndLevel(String category, int level) { return OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL.get(level).stream() .filter(req -> req.startsWith(category + ".")) .collect(Collectors.toSet()); } public static Set<String> getRequirementsForCategoryAndLevel(OwaspAsvs category, int level) { return getRequirementsForCategoryAndLevel(category.category(), level); } private static Set<String> getMatchingStandards(Set<String> securityStandards, String prefix) { return securityStandards.stream() .filter(s -> s.startsWith(prefix)) .map(s -> s.substring(prefix.length())) .collect(Collectors.toSet()); } private static Set<String> toCwes(Collection<String> securityStandards) { Set<String> result = securityStandards.stream() .filter(s -> s.startsWith(CWE_PREFIX)) .map(s -> s.substring(CWE_PREFIX.length())) .collect(Collectors.toSet()); return result.isEmpty() ? singleton(UNKNOWN_STANDARD) : result; } private static Set<String> toCweTop25(Set<String> cwe) { return CWES_BY_CWE_TOP_25 .keySet() .stream() .filter(k -> cwe.stream().anyMatch(CWES_BY_CWE_TOP_25.get(k)::contains)) .collect(Collectors.toSet()); } private static Set<String> toSansTop25(Collection<String> cwe) { return CWES_BY_SANS_TOP_25 .keySet() .stream() .filter(k -> cwe.stream().anyMatch(CWES_BY_SANS_TOP_25.get(k)::contains)) .collect(Collectors.toSet()); } private static List<SQCategory> toSortedSQCategories(Collection<String> cwe) { List<SQCategory> result = CWES_BY_SQ_CATEGORY .keySet() .stream() .filter(k -> cwe.stream().anyMatch(CWES_BY_SQ_CATEGORY.get(k)::contains)) .sorted(SQ_CATEGORY_ORDERING) .toList(); return result.isEmpty() ? singletonList(SQCategory.OTHERS) : result; } }
17,865
43.665
179
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/security/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.security; import javax.annotation.ParametersAreNonnullByDefault;
965
41
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/ChildSettings.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.setting; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.Settings; import org.sonar.api.config.internal.ConfigurationBridge; import static java.util.Objects.requireNonNull; public class ChildSettings extends Settings { private final Settings parentSettings; private final Map<String, String> localProperties = new HashMap<>(); public ChildSettings(Settings parentSettings) { super(parentSettings.getDefinitions(), parentSettings.getEncryption()); this.parentSettings = parentSettings; } @Override protected Optional<String> get(String key) { String value = localProperties.get(key); if (value != null) { return Optional.of(value); } return parentSettings.getRawString(key); } @Override protected void set(String key, String value) { localProperties.put( requireNonNull(key, "key can't be null"), requireNonNull(value, "value can't be null").trim()); } @Override protected void remove(String key) { localProperties.remove(key); } /** * Only returns the currently loaded properties. * * <p> * On the Web Server, global properties are loaded lazily when requested by name. Therefor, * this will return only global properties which have been requested using * {@link #get(String)} at least once prior to this call. */ @Override public Map<String, String> getProperties() { // order is important. local properties override parent properties. ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); builder.putAll(parentSettings.getProperties()); builder.putAll(localProperties); return builder.build(); } public Configuration asConfiguration() { return new ConfigurationBridge(this); } }
2,763
31.904762
93
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/DatabaseSettingLoader.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.setting; import java.util.Map; import java.util.stream.Collectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import static org.apache.commons.lang.StringUtils.defaultString; public class DatabaseSettingLoader implements SettingLoader { private final DbClient dbClient; public DatabaseSettingLoader(DbClient dbClient) { this.dbClient = dbClient; } @Override public String load(String key) { PropertyDto dto = dbClient.propertiesDao().selectGlobalProperty(key); if (dto != null) { return defaultString(dto.getValue()); } return null; } @Override public Map<String, String> loadAll() { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.propertiesDao().selectGlobalProperties(dbSession) .stream() .collect(Collectors.toMap(PropertyDto::getKey, p -> defaultString(p.getValue()))); } } }
1,817
30.894737
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/DatabaseSettingsEnabler.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.setting; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ComputeEngineSide @ServerSide public class DatabaseSettingsEnabler implements Startable { private final ThreadLocalSettings settings; private final DatabaseSettingLoader loader; public DatabaseSettingsEnabler(ThreadLocalSettings settings, DatabaseSettingLoader loader) { this.settings = settings; this.loader = loader; } @Override public void start() { settings.setSettingLoader(loader); } @Override public void stop() { // nothing to do } }
1,477
29.791667
94
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/NopSettingLoader.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.setting; import java.util.Collections; import java.util.Map; public class NopSettingLoader implements SettingLoader { @Override public String load(String key) { return null; } @Override public Map<String, String> loadAll() { return Collections.emptyMap(); } }
1,152
30.162162
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/ProjectConfigurationLoader.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.setting; import org.sonar.api.config.Configuration; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; public interface ProjectConfigurationLoader { /** * Loads configuration for the specified components. * <p> * Returns the applicable component configuration with most specific configuration overriding more global ones * (eg. global > project > branch). * <p> */ Configuration loadBranchConfiguration(DbSession dbSession, BranchDto branch); Configuration loadProjectConfiguration(DbSession dbSession, String projectUuid); }
1,442
36.973684
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/ProjectConfigurationLoaderImpl.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.setting; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.Settings; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.property.PropertyDto; public class ProjectConfigurationLoaderImpl implements ProjectConfigurationLoader { private final Settings globalSettings; private final DbClient dbClient; public ProjectConfigurationLoaderImpl(Settings globalSettings, DbClient dbClient) { this.globalSettings = globalSettings; this.dbClient = dbClient; } @Override public Configuration loadBranchConfiguration(DbSession dbSession, BranchDto branch) { return loadProjectAndBranchConfiguration(dbSession, branch.getProjectUuid(), branch.getUuid()); } @Override public Configuration loadProjectConfiguration(DbSession dbSession, String projectUuid) { return loadProjectAndBranchConfiguration(dbSession, projectUuid, null); } private Configuration loadProjectAndBranchConfiguration(DbSession dbSession, String projectUuid, @Nullable String branchUuid) { ChildSettings projectSettings = internalLoadProjectConfiguration(dbSession, projectUuid); if (branchUuid == null) { return projectSettings.asConfiguration(); } ChildSettings settings = new ChildSettings(projectSettings); dbClient.propertiesDao() .selectEntityProperties(dbSession, branchUuid) .forEach(property -> settings.setProperty(property.getKey(), property.getValue())); return settings.asConfiguration(); } private ChildSettings internalLoadProjectConfiguration(DbSession dbSession, String uuid) { ChildSettings settings = new ChildSettings(globalSettings); List<PropertyDto> propertyDtos = dbClient.propertiesDao().selectEntityProperties(dbSession, uuid); propertyDtos.forEach(property -> settings.setProperty(property.getKey(), property.getValue())); return settings; } }
2,862
38.763889
129
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/SettingLoader.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.setting; import java.util.Map; import javax.annotation.CheckForNull; public interface SettingLoader { @CheckForNull String load(String key); Map<String,String> loadAll(); }
1,052
30.909091
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/ThreadLocalSettings.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.setting; import com.google.common.annotations.VisibleForTesting; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import javax.inject.Inject; import org.apache.ibatis.exceptions.PersistenceException; import org.sonar.api.CoreProperties; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.Settings; import org.sonar.api.server.ServerSide; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; /** * Merge of system settings (including conf/sonar.properties) and the global properties stored * in the db table "properties". These settings do not contain the settings specific to a project. * * <p> * System settings have precedence on others. * </p> * * <p> * The thread-local cache is optional. It is disabled when the method {@link #unload()} has not * been called. That allows to remove complexity with handling of cleanup of thread-local cache * on daemon threads (notifications) or startup "main" thread. * </p> */ @ComputeEngineSide @ServerSide public class ThreadLocalSettings extends Settings { private final Properties systemProps = new Properties(); private static final ThreadLocal<Map<String, String>> CACHE = new ThreadLocal<>(); private Map<String, String> getPropertyDbFailureCache = Collections.emptyMap(); private Map<String, String> getPropertiesDbFailureCache = Collections.emptyMap(); private SettingLoader settingLoader; @Inject public ThreadLocalSettings(PropertyDefinitions definitions, Properties props) { this(definitions, props, new NopSettingLoader()); } @VisibleForTesting ThreadLocalSettings(PropertyDefinitions definitions, Properties props, SettingLoader settingLoader) { super(definitions, new Encryption(null)); this.settingLoader = settingLoader; props.forEach((k, v) -> systemProps.put(k, v == null ? null : v.toString().trim())); // TODO something wrong about lifecycle here. It could be improved getEncryption().setPathToSecretKey(get(CoreProperties.ENCRYPTION_SECRET_KEY_PATH).orElse(null)); } @VisibleForTesting SettingLoader getSettingLoader() { return settingLoader; } protected void setSettingLoader(SettingLoader settingLoader) { this.settingLoader = Objects.requireNonNull(settingLoader); } @Override protected Optional<String> get(String key) { // search for the first value available in // 1. system properties // 2. core property from environment variable // 3. thread local cache (if enabled) // 4. db String value = systemProps.getProperty(key); if (value != null) { return Optional.of(value); } Optional<String> envVal = getDefinitions().getValueFromEnv(key); if (envVal.isPresent()) { return envVal; } Map<String, String> dbProps = CACHE.get(); // caching is disabled if (dbProps == null) { return Optional.ofNullable(load(key)); } String loadedValue; if (dbProps.containsKey(key)) { // property may not exist in db. In this case key is present // in cache but value is null loadedValue = dbProps.get(key); } else { // cache the effective value (null if the property // is not persisted) loadedValue = load(key); dbProps.put(key, loadedValue); } return Optional.ofNullable(loadedValue); } private String load(String key) { try { return settingLoader.load(key); } catch (PersistenceException e) { return getPropertyDbFailureCache.get(key); } } @Override protected void set(String key, String value) { checkKeyAndValue(key, value); Map<String, String> dbProps = CACHE.get(); if (dbProps != null) { dbProps.put(key, value.trim()); } } private static void checkKeyAndValue(String key, String value) { requireNonNull(key, "key can't be null"); requireNonNull(value, "value can't be null"); } @Override protected void remove(String key) { Map<String, String> dbProps = CACHE.get(); if (dbProps != null) { dbProps.remove(key); } } /** * Enables the thread specific cache of settings. */ public void load() { CACHE.set(new HashMap<>()); } /** * Clears the cache specific to the current thread (if any). */ public void unload() { Map<String, String> settings = CACHE.get(); CACHE.remove(); // update cache of settings to be used in case of DB connectivity error this.getPropertyDbFailureCache = settings; } @Override public Map<String, String> getProperties() { Map<String, String> result = new HashMap<>(); loadAll(result); getDefinitions().getAllPropertiesSetInEnv().forEach(result::put); systemProps.forEach((key, value) -> result.put((String) key, (String) value)); return unmodifiableMap(result); } private void loadAll(Map<String, String> appendTo) { try { Map<String, String> cache = settingLoader.loadAll(); appendTo.putAll(cache); getPropertiesDbFailureCache = cache; } catch (PersistenceException e) { appendTo.putAll(getPropertiesDbFailureCache); } } }
6,203
31.3125
103
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/setting/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.setting; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/telemetry/TelemetryData.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.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.EditionProvider.Edition; import org.sonar.db.user.UserTelemetryDto; import static java.util.Objects.requireNonNullElse; import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION; public class TelemetryData { private final String serverId; private final String version; private final Long messageSequenceNumber; private final Map<String, String> plugins; private final Database database; private final EditionProvider.Edition edition; private final String defaultQualityGate; private final Long installationDate; private final String installationVersion; private final boolean inContainer; private final ManagedInstanceInformation managedInstanceInformation; private final CloudUsage cloudUsage; private final List<UserTelemetryDto> users; private final List<Project> projects; private final List<ProjectStatistics> projectStatistics; private final List<Branch> branches; private final List<QualityGate> qualityGates; private final Collection<NewCodeDefinition> newCodeDefinitions; private final Boolean hasUnanalyzedC; private final Boolean hasUnanalyzedCpp; private final int ncdId; private final Set<String> customSecurityConfigs; private TelemetryData(Builder builder) { serverId = builder.serverId; version = builder.version; messageSequenceNumber = builder.messageSequenceNumber; plugins = builder.plugins; database = builder.database; edition = builder.edition; defaultQualityGate = builder.defaultQualityGate; installationDate = builder.installationDate; installationVersion = builder.installationVersion; inContainer = builder.inContainer; users = builder.users; projects = builder.projects; projectStatistics = builder.projectStatistics; qualityGates = builder.qualityGates; hasUnanalyzedC = builder.hasUnanalyzedC; hasUnanalyzedCpp = builder.hasUnanalyzedCpp; customSecurityConfigs = requireNonNullElse(builder.customSecurityConfigs, Set.of()); managedInstanceInformation = builder.managedInstanceInformation; cloudUsage = builder.cloudUsage; ncdId = builder.ncdId; branches = builder.branches; newCodeDefinitions = builder.newCodeDefinitions; } public String getServerId() { return serverId; } public String getVersion() { return version; } public Long getMessageSequenceNumber() { return messageSequenceNumber; } public Map<String, String> getPlugins() { return plugins; } public Database getDatabase() { return database; } public Optional<EditionProvider.Edition> getEdition() { return Optional.ofNullable(edition); } public String getDefaultQualityGate() { return defaultQualityGate; } public Long getInstallationDate() { return installationDate; } public String getInstallationVersion() { return installationVersion; } public boolean isInContainer() { return inContainer; } public ManagedInstanceInformation getManagedInstanceInformation() { return managedInstanceInformation; } public CloudUsage getCloudUsage() { return cloudUsage; } public Optional<Boolean> hasUnanalyzedC() { return Optional.ofNullable(hasUnanalyzedC); } public Optional<Boolean> hasUnanalyzedCpp() { return Optional.ofNullable(hasUnanalyzedCpp); } public Set<String> getCustomSecurityConfigs() { return customSecurityConfigs; } public List<UserTelemetryDto> getUserTelemetries() { return users; } public List<Project> getProjects() { return projects; } public List<ProjectStatistics> getProjectStatistics() { return projectStatistics; } public List<QualityGate> getQualityGates() { return qualityGates; } static Builder builder() { return new Builder(); } public int getNcdId() { return ncdId; } public List<Branch> getBranches() { return branches; } public Collection<NewCodeDefinition> getNewCodeDefinitions() { return newCodeDefinitions; } static class Builder { private String serverId; private String version; private Long messageSequenceNumber; private Map<String, String> plugins; private Database database; private Edition edition; private String defaultQualityGate; private Long installationDate; private String installationVersion; private boolean inContainer = false; private ManagedInstanceInformation managedInstanceInformation; private CloudUsage cloudUsage; private Boolean hasUnanalyzedC; private Boolean hasUnanalyzedCpp; private Set<String> customSecurityConfigs; private List<UserTelemetryDto> users; private List<Project> projects; private List<ProjectStatistics> projectStatistics; private List<Branch> branches; private Collection<NewCodeDefinition> newCodeDefinitions; private List<QualityGate> qualityGates; private int ncdId; private Builder() { // enforce static factory method } Builder setServerId(String serverId) { this.serverId = serverId; return this; } Builder setVersion(String version) { this.version = version; return this; } Builder setMessageSequenceNumber(@Nullable Long messageSequenceNumber) { this.messageSequenceNumber = messageSequenceNumber; return this; } Builder setPlugins(Map<String, String> plugins) { this.plugins = plugins; return this; } Builder setDatabase(Database database) { this.database = database; return this; } Builder setEdition(@Nullable Edition edition) { this.edition = edition; return this; } Builder setDefaultQualityGate(String defaultQualityGate) { this.defaultQualityGate = defaultQualityGate; return this; } Builder setInstallationDate(@Nullable Long installationDate) { this.installationDate = installationDate; return this; } Builder setInstallationVersion(@Nullable String installationVersion) { this.installationVersion = installationVersion; return this; } Builder setInContainer(boolean inContainer) { this.inContainer = inContainer; return this; } Builder setHasUnanalyzedC(@Nullable Boolean hasUnanalyzedC) { this.hasUnanalyzedC = hasUnanalyzedC; return this; } Builder setHasUnanalyzedCpp(@Nullable Boolean hasUnanalyzedCpp) { this.hasUnanalyzedCpp = hasUnanalyzedCpp; return this; } Builder setCustomSecurityConfigs(Set<String> customSecurityConfigs) { this.customSecurityConfigs = customSecurityConfigs; return this; } Builder setUsers(List<UserTelemetryDto> users) { this.users = users; return this; } Builder setProjects(List<Project> projects) { this.projects = projects; return this; } Builder setManagedInstanceInformation(ManagedInstanceInformation managedInstanceInformation) { this.managedInstanceInformation = managedInstanceInformation; return this; } Builder setCloudUsage(CloudUsage cloudUsage) { this.cloudUsage = cloudUsage; return this; } TelemetryData build() { requireNonNullValues(serverId, version, plugins, database, messageSequenceNumber); return new TelemetryData(this); } Builder setProjectStatistics(List<ProjectStatistics> projectStatistics) { this.projectStatistics = projectStatistics; return this; } Builder setQualityGates(List<QualityGate> qualityGates) { this.qualityGates = qualityGates; return this; } Builder setNcdId(int ncdId) { this.ncdId = ncdId; return this; } private static void requireNonNullValues(Object... values) { Arrays.stream(values).forEach(Objects::requireNonNull); } Builder setBranches(List<Branch> branches) { this.branches = branches; return this; } Builder setNewCodeDefinitions(Collection<NewCodeDefinition> newCodeDefinitions) { this.newCodeDefinitions = newCodeDefinitions; return this; } } record Database(String name, String version) { } record NewCodeDefinition(String type, @Nullable String value, String scope) { private static final NewCodeDefinition instanceDefault = new NewCodeDefinition(PREVIOUS_VERSION.name(), "", "instance"); public static NewCodeDefinition getInstanceDefault() { return instanceDefault; } @Override public String value() { return value == null ? "" : value; } } record Branch(String projectUuid, String branchUuid, int ncdId, int greenQualityGateCount, int analysisCount, boolean excludeFromPurge) { } record Project(String projectUuid, Long lastAnalysis, String language, Long loc) { } record QualityGate(String uuid, String caycStatus) { } record ManagedInstanceInformation(boolean isManaged, @Nullable String provider) { } record CloudUsage(boolean kubernetes, @Nullable String kubernetesVersion, @Nullable String kubernetesPlatform, @Nullable String kubernetesProvider, @Nullable String officialHelmChart, @Nullable String containerRuntime, boolean officialImage) { } public static class ProjectStatistics { private final String projectUuid; private final Long branchCount; private final Long pullRequestCount; private final String qualityGate; private final String scm; private final String ci; private final String devopsPlatform; private final Long bugs; private final Long vulnerabilities; private final Long securityHotspots; private final Long technicalDebt; private final Long developmentCost; private final int ncdId; ProjectStatistics(Builder builder) { this.projectUuid = builder.projectUuid; this.branchCount = builder.branchCount; this.pullRequestCount = builder.pullRequestCount; this.qualityGate = builder.qualityGate; this.scm = builder.scm; this.ci = builder.ci; this.devopsPlatform = builder.devopsPlatform; this.bugs = builder.bugs; this.vulnerabilities = builder.vulnerabilities; this.securityHotspots = builder.securityHotspots; this.technicalDebt = builder.technicalDebt; this.developmentCost = builder.developmentCost; this.ncdId = builder.ncdId; } public int getNcdId() { return ncdId; } public String getProjectUuid() { return projectUuid; } public Long getBranchCount() { return branchCount; } public Long getPullRequestCount() { return pullRequestCount; } public String getQualityGate() { return qualityGate; } public String getScm() { return scm; } public String getCi() { return ci; } public String getDevopsPlatform() { return devopsPlatform; } public Optional<Long> getBugs() { return Optional.ofNullable(bugs); } public Optional<Long> getVulnerabilities() { return Optional.ofNullable(vulnerabilities); } public Optional<Long> getSecurityHotspots() { return Optional.ofNullable(securityHotspots); } public Optional<Long> getTechnicalDebt() { return Optional.ofNullable(technicalDebt); } public Optional<Long> getDevelopmentCost() { return Optional.ofNullable(developmentCost); } static class Builder { private String projectUuid; private Long branchCount; private Long pullRequestCount; private String qualityGate; private String scm; private String ci; private String devopsPlatform; private Long bugs; private Long vulnerabilities; private Long securityHotspots; private Long technicalDebt; private Long developmentCost; private int ncdId; public Builder setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public Builder setNcdId(int ncdId) { this.ncdId = ncdId; return this; } public Builder setBranchCount(Long branchCount) { this.branchCount = branchCount; return this; } public Builder setPRCount(Long pullRequestCount) { this.pullRequestCount = pullRequestCount; return this; } public Builder setQG(String qualityGate) { this.qualityGate = qualityGate; return this; } public Builder setScm(String scm) { this.scm = scm; return this; } public Builder setCi(String ci) { this.ci = ci; return this; } public Builder setDevops(String devopsPlatform) { this.devopsPlatform = devopsPlatform; return this; } public Builder setBugs(@Nullable Number bugs) { this.bugs = bugs != null ? bugs.longValue() : null; return this; } public Builder setVulnerabilities(@Nullable Number vulnerabilities) { this.vulnerabilities = vulnerabilities != null ? vulnerabilities.longValue() : null; return this; } public Builder setSecurityHotspots(@Nullable Number securityHotspots) { this.securityHotspots = securityHotspots != null ? securityHotspots.longValue() : null; return this; } public Builder setTechnicalDebt(@Nullable Number technicalDebt) { this.technicalDebt = technicalDebt != null ? technicalDebt.longValue() : null; return this; } public Builder setDevelopmentCost(@Nullable Number developmentCost) { this.developmentCost = developmentCost != null ? developmentCost.longValue() : null; return this; } public ProjectStatistics build() { return new ProjectStatistics(this); } } } }
14,961
27.283554
149
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/telemetry/TelemetryDataJsonWriter.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.google.common.annotations.VisibleForTesting; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Locale; import org.apache.commons.codec.digest.DigestUtils; import org.jetbrains.annotations.NotNull; import org.sonar.api.utils.System2; import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.telemetry.TelemetryExtension; import static org.sonar.api.utils.DateUtils.DATETIME_FORMAT; public class TelemetryDataJsonWriter { @VisibleForTesting static final String MANAGED_INSTANCE_PROPERTY = "managedInstanceInformation"; @VisibleForTesting static final String CLOUD_USAGE_PROPERTY = "cloudUsage"; private static final String LANGUAGE_PROPERTY = "language"; private static final String VERSION = "version"; private static final String NCD_ID = "ncdId"; private static final String PROJECT_ID = "projectUuid"; private final List<TelemetryExtension> extensions; private final System2 system2; public TelemetryDataJsonWriter(List<TelemetryExtension> extensions, System2 system2) { this.extensions = extensions; this.system2 = system2; } public void writeTelemetryData(JsonWriter json, TelemetryData telemetryData) { json.beginObject(); json.prop("id", telemetryData.getServerId()); json.prop(VERSION, telemetryData.getVersion()); json.prop("messageSequenceNumber", telemetryData.getMessageSequenceNumber()); json.prop("localTimestamp", toUtc(system2.now())); json.prop(NCD_ID, telemetryData.getNcdId()); telemetryData.getEdition().ifPresent(e -> json.prop("edition", e.name().toLowerCase(Locale.ENGLISH))); json.prop("defaultQualityGate", telemetryData.getDefaultQualityGate()); json.name("database"); json.beginObject(); json.prop("name", telemetryData.getDatabase().name()); json.prop(VERSION, telemetryData.getDatabase().version()); json.endObject(); json.name("plugins"); json.beginArray(); telemetryData.getPlugins().forEach((plugin, version) -> { json.beginObject(); json.prop("name", plugin); json.prop(VERSION, version); json.endObject(); }); json.endArray(); if (!telemetryData.getCustomSecurityConfigs().isEmpty()) { json.name("customSecurityConfig"); json.beginArray(); json.values(telemetryData.getCustomSecurityConfigs()); json.endArray(); } telemetryData.hasUnanalyzedC().ifPresent(hasUnanalyzedC -> json.prop("hasUnanalyzedC", hasUnanalyzedC)); telemetryData.hasUnanalyzedCpp().ifPresent(hasUnanalyzedCpp -> json.prop("hasUnanalyzedCpp", hasUnanalyzedCpp)); if (telemetryData.getInstallationDate() != null) { json.prop("installationDate", toUtc(telemetryData.getInstallationDate())); } if (telemetryData.getInstallationVersion() != null) { json.prop("installationVersion", telemetryData.getInstallationVersion()); } json.prop("container", telemetryData.isInContainer()); writeUserData(json, telemetryData); writeProjectData(json, telemetryData); writeProjectStatsData(json, telemetryData); writeBranches(json, telemetryData); writeNewCodeDefinitions(json, telemetryData); writeQualityGates(json, telemetryData); writeManagedInstanceInformation(json, telemetryData.getManagedInstanceInformation()); writeCloudUsage(json, telemetryData.getCloudUsage()); extensions.forEach(e -> e.write(json)); json.endObject(); } private static void writeUserData(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getUserTelemetries() != null) { json.name("users"); json.beginArray(); telemetryData.getUserTelemetries().forEach(user -> { json.beginObject(); json.prop("userUuid", DigestUtils.sha3_224Hex(user.getUuid())); json.prop("status", user.isActive() ? "active" : "inactive"); json.prop("identityProvider", user.getExternalIdentityProvider()); if (user.getLastConnectionDate() != null) { json.prop("lastActivity", toUtc(user.getLastConnectionDate())); } if (user.getLastSonarlintConnectionDate() != null) { json.prop("lastSonarlintActivity", toUtc(user.getLastSonarlintConnectionDate())); } json.prop("managed", user.getScimUuid() != null); json.endObject(); }); json.endArray(); } } private static void writeProjectData(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getProjects() != null) { json.name("projects"); json.beginArray(); telemetryData.getProjects().forEach(project -> { json.beginObject(); json.prop(PROJECT_ID, project.projectUuid()); if (project.lastAnalysis() != null) { json.prop("lastAnalysis", toUtc(project.lastAnalysis())); } json.prop(LANGUAGE_PROPERTY, project.language()); json.prop("loc", project.loc()); json.endObject(); }); json.endArray(); } } private static void writeBranches(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getBranches() != null) { json.name("branches"); json.beginArray(); telemetryData.getBranches().forEach(branch -> { json.beginObject(); json.prop(PROJECT_ID, branch.projectUuid()); json.prop("branchUuid", branch.branchUuid()); json.prop(NCD_ID, branch.ncdId()); json.prop("greenQualityGateCount", branch.greenQualityGateCount()); json.prop("analysisCount", branch.analysisCount()); json.prop("excludeFromPurge", branch.excludeFromPurge()); json.endObject(); }); json.endArray(); } } private static void writeNewCodeDefinitions(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getNewCodeDefinitions() != null) { json.name("new-code-definitions"); json.beginArray(); telemetryData.getNewCodeDefinitions().forEach(ncd -> { json.beginObject(); json.prop(NCD_ID, ncd.hashCode()); json.prop("type", ncd.type()); json.prop("value", ncd.value()); json.prop("scope", ncd.scope()); json.endObject(); }); json.endArray(); } } private static void writeProjectStatsData(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getProjectStatistics() != null) { json.name("projects-general-stats"); json.beginArray(); telemetryData.getProjectStatistics().forEach(project -> { json.beginObject(); json.prop(PROJECT_ID, project.getProjectUuid()); json.prop("branchCount", project.getBranchCount()); json.prop("pullRequestCount", project.getPullRequestCount()); json.prop("qualityGate", project.getQualityGate()); json.prop("scm", project.getScm()); json.prop("ci", project.getCi()); json.prop("devopsPlatform", project.getDevopsPlatform()); json.prop(NCD_ID, project.getNcdId()); project.getBugs().ifPresent(bugs -> json.prop("bugs", bugs)); project.getVulnerabilities().ifPresent(vulnerabilities -> json.prop("vulnerabilities", vulnerabilities)); project.getSecurityHotspots().ifPresent(securityHotspots -> json.prop("securityHotspots", securityHotspots)); project.getTechnicalDebt().ifPresent(technicalDebt -> json.prop("technicalDebt", technicalDebt)); project.getDevelopmentCost().ifPresent(developmentCost -> json.prop("developmentCost", developmentCost)); json.endObject(); }); json.endArray(); } } private static void writeQualityGates(JsonWriter json, TelemetryData telemetryData) { if (telemetryData.getQualityGates() != null) { json.name("quality-gates"); json.beginArray(); telemetryData.getQualityGates().forEach(qualityGate -> { json.beginObject(); json.prop("uuid", qualityGate.uuid()); json.prop("caycStatus", qualityGate.caycStatus()); json.endObject(); }); json.endArray(); } } private static void writeManagedInstanceInformation(JsonWriter json, TelemetryData.ManagedInstanceInformation provider) { json.name(MANAGED_INSTANCE_PROPERTY); json.beginObject(); json.prop("isManaged", provider.isManaged()); json.prop("provider", provider.isManaged() ? provider.provider() : null); json.endObject(); } private static void writeCloudUsage(JsonWriter json, TelemetryData.CloudUsage cloudUsage) { json.name(CLOUD_USAGE_PROPERTY); json.beginObject(); json.prop("kubernetes", cloudUsage.kubernetes()); json.prop("kubernetesVersion", cloudUsage.kubernetesVersion()); json.prop("kubernetesPlatform", cloudUsage.kubernetesPlatform()); json.prop("kubernetesProvider", cloudUsage.kubernetesProvider()); json.prop("officialHelmChart", cloudUsage.officialHelmChart()); json.prop("containerRuntime", cloudUsage.containerRuntime()); json.prop("officialImage", cloudUsage.officialImage()); json.endObject(); } @NotNull private static String toUtc(long date) { return DateTimeFormatter.ofPattern(DATETIME_FORMAT) .withZone(ZoneOffset.UTC) .format(Instant.ofEpochMilli(date)); } }
10,120
38.535156
123
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/telemetry/TelemetryDataLoader.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; public interface TelemetryDataLoader { TelemetryData load(); String loadServerId(); void reset(); }
988
33.103448
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/telemetry/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.telemetry; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/AbstractStoppableExecutorService.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.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static java.lang.String.format; /** * Abstract implementation of StoppableExecutorService that implements the * stop() method and delegates all methods to the provided ExecutorService instance. */ public abstract class AbstractStoppableExecutorService<D extends ExecutorService> implements StoppableExecutorService { protected final D delegate; public AbstractStoppableExecutorService(D delegate) { this.delegate = delegate; } @Override public void stop() { // Disable new tasks from being submitted delegate.shutdown(); try { // Wait a while for existing tasks to terminate if (!delegate.awaitTermination(5, TimeUnit.SECONDS)) { // Cancel currently executing tasks delegate.shutdownNow(); // Wait a while for tasks to respond to being canceled if (!delegate.awaitTermination(5, TimeUnit.SECONDS)) { LoggerFactory.getLogger(getClass()).warn(format("Pool %s did not terminate", getClass().getSimpleName())); } } } catch (InterruptedException ie) { LoggerFactory.getLogger(getClass()).warn(format("Termination of pool %s failed", getClass().getSimpleName()), ie); // (Re-)Cancel if current thread also interrupted delegate.shutdownNow(); } } @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate.submit(task, result); } @Override public Future<?> submit(Runnable task) { return delegate.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { delegate.execute(command); } }
4,178
29.727941
120
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/AbstractStoppableScheduledExecutorServiceImpl.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 java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public abstract class AbstractStoppableScheduledExecutorServiceImpl<T extends ScheduledExecutorService> extends AbstractStoppableExecutorService<T> implements StoppableScheduledExecutorService { protected AbstractStoppableScheduledExecutorServiceImpl(T delegate) { super(delegate); } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(command, delay, unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return delegate.schedule(callable, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); } }
2,086
38.377358
147
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/OkHttpClientProvider.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 okhttp3.OkHttpClient; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.SonarQubeVersion; import org.sonarqube.ws.client.OkHttpClientBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.HTTP_PROXY_PASSWORD; import static org.sonar.process.ProcessProperties.Property.HTTP_PROXY_USER; /** * Provide a unique instance of {@link OkHttpClient} which configuration: * <ul> * <li>supports HTTPS</li> * <li>supports proxy, including authentication, as defined by the properties like "http.proxyHost" in * conf/sonar.properties</li> * <li>has connect and read timeouts of 10 seconds each</li> * <li>sends automatically the HTTP header "User-Agent" with value "SonarQube/{version}", for instance "SonarQube/6.2"</li> * </ul> */ @ServerSide @ComputeEngineSide public class OkHttpClientProvider { private static final int DEFAULT_CONNECT_TIMEOUT_IN_MS = 10_000; private static final int DEFAULT_READ_TIMEOUT_IN_MS = 10_000; /** * @return a {@link OkHttpClient} singleton */ @Primary @Bean("OkHttpClient") public OkHttpClient provide(Configuration config, SonarQubeVersion version) { OkHttpClientBuilder builder = new OkHttpClientBuilder(); builder.setConnectTimeoutMs(DEFAULT_CONNECT_TIMEOUT_IN_MS); builder.setReadTimeoutMs(DEFAULT_READ_TIMEOUT_IN_MS); // no need to define proxy URL as system-wide proxy is used and properly // configured by bootstrap process. builder.setProxyLogin(config.get(HTTP_PROXY_USER.getKey()).orElse(null)); builder.setProxyPassword(config.get(HTTP_PROXY_PASSWORD.getKey()).orElse(null)); builder.setUserAgent(format("SonarQube/%s", version)); return builder.build(); } }
2,818
39.855072
125
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/Paths2.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 java.net.URI; import java.nio.file.Path; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; /** * An interface exposing with the same interface as {@link java.nio.file.Paths} which classes can get injected * with instead of statically binding to {@link java.nio.file.Paths} class. * <p> * This interface can be used to improve testability of classes. */ @ServerSide @ComputeEngineSide public interface Paths2 { /** * @see java.nio.file.Paths#get(String, String...) */ Path get(String first, String... more); /** * @see java.nio.file.Paths#get(URI) */ Path get(URI uri); boolean exists(String first, String... more); }
1,565
31.625
110
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/Paths2Impl.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 java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import static java.nio.file.Path.of; public final class Paths2Impl implements Paths2 { private static final Paths2 INSTANCE = new Paths2Impl(); private Paths2Impl() { // prevents instantiation and subclassing, use getInstance() instead } public static Paths2 getInstance() { return INSTANCE; } @Override public Path get(String first, String... more) { return Paths.get(first, more); } @Override public Path get(URI uri) { return Paths.get(uri); } @Override public boolean exists(String first, String... more){ return of(first, more).toFile().exists(); } }
1,562
27.944444
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/StoppableExecutorService.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 java.util.concurrent.ExecutorService; import org.sonar.api.Startable; /** * ExecutorService that exposes a {@code stop} method which can be invoked by the ioc container to shutdown properly * the service. */ public interface StoppableExecutorService extends ExecutorService, Startable { @Override default void start() { // nothing to do } }
1,238
33.416667
116
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/StoppableScheduledExecutorService.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 java.util.concurrent.ScheduledExecutorService; /** * ScheduledExecutorService that exposes a {@code stop} method which can be invoked by the ioc container to shutdown * properly the service. */ public interface StoppableScheduledExecutorService extends ScheduledExecutorService, StoppableExecutorService { }
1,195
37.580645
116
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/util/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.util; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewDoc.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.view.index; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sonar.server.es.BaseDoc; import static org.sonar.server.view.index.ViewIndexDefinition.TYPE_VIEW; public class ViewDoc extends BaseDoc { public ViewDoc(Map<String, Object> fields) { super(TYPE_VIEW, fields); } public ViewDoc() { super(TYPE_VIEW, new HashMap<>()); } @Override public String getId() { return uuid(); } /** * Uuid of the view. * It may or may not be the root view (Qualifiers SVW, SW, APP). */ public String uuid() { return getField(ViewIndexDefinition.FIELD_UUID); } public List<String> projectBranchUuids() { return getField(ViewIndexDefinition.FIELD_PROJECTS); } /** * Uuid of the view. * It may or may not be the root view (Qualifiers SVW, SW, APP). */ public ViewDoc setUuid(String s) { setField(ViewIndexDefinition.FIELD_UUID, s); return this; } public ViewDoc setProjectBranchUuids(List<String> s) { setField(ViewIndexDefinition.FIELD_PROJECTS, s); return this; } }
1,947
26.828571
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndex.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.view.index; import java.util.ArrayList; import java.util.List; import org.elasticsearch.action.search.ClearScrollRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.core.TimeValue; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.server.es.EsClient; import static com.google.common.collect.Lists.newArrayList; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; /** * The View Index indexes all views, root and not root (APP, VW, SVW), and all projects that are computed under each view. * It's based on the computation results, coming from the components table, not on the definition of those views. */ @ServerSide @ComputeEngineSide public class ViewIndex { private static final int SCROLL_TIME_IN_MINUTES = 3; private final EsClient esClient; public ViewIndex(EsClient esClient) { this.esClient = esClient; } public List<String> findAllViewUuids() { SearchRequest esSearch = EsClient.prepareSearch(ViewIndexDefinition.TYPE_VIEW) .source(new SearchSourceBuilder() .sort("_doc", SortOrder.ASC) .fetchSource(false) .size(100) .query(matchAllQuery())) .scroll(TimeValue.timeValueMinutes(SCROLL_TIME_IN_MINUTES)); SearchResponse response = esClient.search(esSearch); List<String> result = new ArrayList<>(); while (true) { List<SearchHit> hits = newArrayList(response.getHits()); for (SearchHit hit : hits) { result.add(hit.getId()); } String scrollId = response.getScrollId(); response = esClient.scroll(new SearchScrollRequest().scrollId(scrollId).scroll(TimeValue.timeValueMinutes(SCROLL_TIME_IN_MINUTES))); // Break condition: No hits are returned if (response.getHits().getHits().length == 0) { ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); esClient.clearScroll(clearScrollRequest); break; } } return result; } }
3,204
37.154762
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndexDefinition.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.view.index; import org.sonar.api.config.Configuration; 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.IndexType.IndexMainType; import org.sonar.server.es.newindex.NewRegularIndex; import org.sonar.server.es.newindex.TypeMapping; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; /** * Definition of ES index "views", including settings and fields. */ public class ViewIndexDefinition implements IndexDefinition { public static final Index DESCRIPTOR = Index.simple("views"); public static final IndexMainType TYPE_VIEW = IndexType.main(DESCRIPTOR, "view"); public static final String FIELD_UUID = "uuid"; public static final String FIELD_PROJECTS = "projects"; private final Configuration config; public ViewIndexDefinition(Configuration config) { this.config = config; } /** * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ public static ViewIndexDefinition createForTest() { return new ViewIndexDefinition(new MapSettings().asConfig()); } @Override public void define(IndexDefinitionContext context) { NewRegularIndex index = context.create( DESCRIPTOR, newBuilder(config) .setDefaultNbOfShards(5) .build()) // storing source is required because some search queries on issue index use terms lookup query onto the view index // and this requires source to be stored (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html#query-dsl-terms-lookup) .setEnableSource(true); // type "view" TypeMapping mapping = index.createTypeMapping(TYPE_VIEW); mapping.keywordFieldBuilder(FIELD_UUID).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_PROJECTS).disableNorms().build(); } }
2,833
37.297297
162
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndexer.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.view.index; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.action.index.IndexRequest; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.UuidWithBranchUuidDto; 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.IndexType; import org.sonar.server.es.IndexingListener; import org.sonar.server.es.IndexingResult; import org.sonar.server.es.OneToOneResilientIndexingListener; import org.sonar.server.es.ResilientIndexer; import static org.sonar.server.view.index.ViewIndexDefinition.TYPE_VIEW; public class ViewIndexer implements ResilientIndexer { private final DbClient dbClient; private final EsClient esClient; public ViewIndexer(DbClient dbClient, EsClient esClient) { this.dbClient = dbClient; this.esClient = esClient; } @Override public Set<IndexType> getIndexTypes() { return Set.of(TYPE_VIEW); } @Override public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) { indexAll(Size.LARGE); } public void indexAll() { indexAll(Size.REGULAR); } private void indexAll(Size bulkSize) { try (DbSession dbSession = dbClient.openSession(false)) { Map<String, String> rootViewUuidByViewUuid = new HashMap<>(); for (UuidWithBranchUuidDto uuidWithBranchUuidDto : dbClient.componentDao().selectAllViewsAndSubViews(dbSession)) { rootViewUuidByViewUuid.put(uuidWithBranchUuidDto.getUuid(), uuidWithBranchUuidDto.getBranchUuid()); } index(dbSession, rootViewUuidByViewUuid, false, bulkSize); } } /** * Index a root view : it will fetch a view and its subviews from the DB and index them. * Used by the compute engine to reindex a root view. * <p/> * The views lookup cache will be cleared */ public void index(String rootViewUuid) { try (DbSession dbSession = dbClient.openSession(false)) { Map<String, String> viewAndRootViewUuidMap = new HashMap<>(); for (ComponentDto viewOrSubView : dbClient.componentDao().selectEnabledViewsFromRootView(dbSession, rootViewUuid)) { viewAndRootViewUuidMap.put(viewOrSubView.uuid(), viewOrSubView.branchUuid()); } index(dbSession, viewAndRootViewUuidMap, true, Size.REGULAR); } } /** * Index a single document. * <p/> * The views lookup cache will be cleared */ public void index(ViewDoc viewDoc) { BulkIndexer bulk = new BulkIndexer(esClient, TYPE_VIEW, Size.REGULAR); bulk.start(); doIndex(bulk, viewDoc, true); bulk.stop(); } private void index(DbSession dbSession, Map<String, String> rootViewUuidByViewUuid, boolean needClearCache, Size bulkSize) { BulkIndexer bulk = new BulkIndexer(esClient, TYPE_VIEW, bulkSize); bulk.start(); for (Map.Entry<String, String> entry : rootViewUuidByViewUuid.entrySet()) { String viewUuid = entry.getKey(); String rootViewUuid = entry.getValue(); List<String> projectBranchUuids = dbClient.componentDao().selectProjectBranchUuidsFromView(dbSession, viewUuid, rootViewUuid); doIndex(bulk, new ViewDoc() .setUuid(viewUuid) .setProjectBranchUuids(projectBranchUuids), needClearCache); } bulk.stop(); } private void doIndex(BulkIndexer bulk, ViewDoc viewDoc, boolean needClearCache) { bulk.add(newIndexRequest(viewDoc)); if (needClearCache) { clearLookupCache(viewDoc.uuid()); } } private static IndexRequest newIndexRequest(ViewDoc doc) { return new IndexRequest(TYPE_VIEW.getIndex().getName()) .id(doc.getId()) .routing(doc.getRouting().orElse(null)) .source(doc.getFields()); } private void clearLookupCache(String viewUuid) { try { esClient.clearCache(new ClearIndicesCacheRequest().queryCache(true)); } catch (Exception e) { throw new IllegalStateException(String.format("Unable to clear lookup cache of view '%s'", viewUuid), e); } } /** * This is based on the fact that a WebService is only calling {@link ViewIndexer#delete(DbSession, Collection)} * So the resiliency is only taking in account a deletion of view component * A safety check is done by not deleting any component that still exist in database. * This should not occur but prevent any misuse on this resiliency */ @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } Set<String> viewUuids = items .stream() .map(EsQueueDto::getDocId) .collect(Collectors.toSet()); BulkIndexer bulkIndexer = newBulkIndexer(Size.REGULAR, new OneToOneResilientIndexingListener(dbClient, dbSession, items)); bulkIndexer.start(); // Safety check to remove all views that may not have been deleted viewUuids.removeAll(dbClient.componentDao().selectExistingUuids(dbSession, viewUuids)); viewUuids.forEach(v -> bulkIndexer.addDeletion(TYPE_VIEW, v)); return bulkIndexer.stop(); } public void delete(DbSession dbSession, Collection<String> viewUuids) { List<EsQueueDto> items = viewUuids.stream() .map(l -> EsQueueDto.create(TYPE_VIEW.format(), l)) .toList(); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); index(dbSession, items); } private BulkIndexer newBulkIndexer(Size bulkSize, IndexingListener listener) { return new BulkIndexer(esClient, TYPE_VIEW, bulkSize, listener); } }
6,682
35.320652
132
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/view/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.view.index; import javax.annotation.ParametersAreNonnullByDefault;
968
37.76
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/Analysis.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.webhook; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public final class Analysis { private final String uuid; private final long date; @Nullable private final String revision; public Analysis(String uuid, long date, @Nullable String revision) { this.uuid = requireNonNull(uuid, "uuid must not be null"); this.date = date; this.revision = revision; } public String getUuid() { return uuid; } public long getDate() { return date; } public Optional<String> getRevision() { return Optional.ofNullable(revision); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Analysis analysis = (Analysis) o; return date == analysis.date && uuid.equals(analysis.uuid) && Objects.equals(revision, analysis.revision); } @Override public int hashCode() { return Objects.hash(uuid, date, revision); } @Override public String toString() { return "Analysis{" + "uuid='" + uuid + '\'' + ", date=" + date + ", revision=" + revision + '}'; } }
2,124
25.5625
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/Branch.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.webhook; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public final class Branch { private final boolean main; private final String name; private final Type type; public Branch(boolean main, @Nullable String name, Type type) { this.main = main; this.name = name; this.type = requireNonNull(type, "type can't be null"); } public boolean isMain() { return main; } public Optional<String> getName() { return Optional.ofNullable(name); } public Type getType() { return type; } public enum Type { PULL_REQUEST, BRANCH } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Branch branch = (Branch) o; return main == branch.main && Objects.equals(name, branch.name) && type == branch.type; } @Override public int hashCode() { return Objects.hash(main, name, type); } @Override public String toString() { return "Branch{" + "main=" + main + ", name='" + name + '\'' + ", type=" + type + '}'; } }
2,095
24.253012
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/CeTask.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.webhook; import static java.util.Objects.requireNonNull; public record CeTask(String id, Status status) { public CeTask(String id, Status status) { this.id = requireNonNull(id, "id can't be null"); this.status = requireNonNull(status, "status can't be null"); } public enum Status { SUCCESS, FAILED } @Override public String toString() { return "CeTask{" + "id='" + id + '\'' + ", status=" + status + '}'; } }
1,331
29.976744
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/HttpUrlHelper.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.webhook; import com.google.common.base.Supplier; import java.util.Objects; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import okhttp3.HttpUrl; import static com.google.common.base.Preconditions.checkState; import static org.apache.commons.lang.StringUtils.repeat; public final class HttpUrlHelper { private HttpUrlHelper() { // prevents instantiation } public static String obfuscateCredentials(String originalUrl) { HttpUrl parsedUrl = HttpUrl.parse(originalUrl); if (parsedUrl != null) { return obfuscateCredentials(originalUrl, parsedUrl); } return originalUrl; } /** * According to inline comment in {@link okhttp3.HttpUrl.Builder#parse(HttpUrl base, String input)}: * <blockquote> * Username, password and port are optional. * [username[:password]@]host[:port] * </blockquote> * <p> * This function replaces the chars of the username and the password from the {@code originalUrl} by '*' chars * based on username and password parsed in {@code parsedUrl}. */ static String obfuscateCredentials(String originalUrl, HttpUrl parsedUrl) { String username = parsedUrl.username(); String password = parsedUrl.password(); if (username.isEmpty() && password.isEmpty()) { return originalUrl; } if (!username.isEmpty() && !password.isEmpty()) { String encodedUsername = parsedUrl.encodedUsername(); String encodedPassword = parsedUrl.encodedPassword(); return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, password), () -> replaceOrDie(originalUrl, encodedUsername, encodedPassword), () -> replaceOrDie(originalUrl, encodedUsername, password), () -> replaceOrDie(originalUrl, username, encodedPassword)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } if (!username.isEmpty()) { return Stream.<Supplier<String>>of( () -> replaceOrDie(originalUrl, username, null), () -> replaceOrDie(originalUrl, parsedUrl.encodedUsername(), null)) .map(Supplier::get) .filter(Objects::nonNull) .findFirst() .orElse(originalUrl); } checkState(password.isEmpty(), "having a password without a username should never occur"); return originalUrl; } @CheckForNull private static String replaceOrDie(String original, String username, @Nullable String password) { return replaceOrDieImpl(original, authentStringOf(username, password), obfuscatedAuthentStringOf(username, password)); } private static String authentStringOf(String username, @Nullable String password) { if (password == null) { return username + "@"; } return username + ":" + password + "@"; } private static String obfuscatedAuthentStringOf(String userName, @Nullable String password) { return authentStringOf(repeat("*", userName.length()), password == null ? null : repeat("*", password.length())); } @CheckForNull private static String replaceOrDieImpl(String original, String target, String replacement) { String res = original.replace(target, replacement); if (!res.equals(original)) { return res; } return null; } }
4,174
35.946903
122
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/NetworkInterfaceProvider.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.webhook; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.List; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide public class NetworkInterfaceProvider { public List<InetAddress> getNetworkInterfaceAddresses() throws SocketException { return Collections.list(NetworkInterface.getNetworkInterfaces()) .stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .toList(); } }
1,445
34.268293
82
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/Project.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.webhook; import java.util.Objects; import javax.annotation.concurrent.Immutable; @Immutable public class Project { private final String uuid; private final String key; private final String name; public Project(String uuid, String key, String name) { this.uuid = uuid; this.key = key; this.name = name; } public String getUuid() { return uuid; } public String getKey() { return key; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Project project = (Project) o; return Objects.equals(uuid, project.uuid) && Objects.equals(key, project.key) && Objects.equals(name, project.name); } @Override public int hashCode() { return Objects.hash(uuid, key, name); } @Override public String toString() { StringBuilder sb = new StringBuilder("Project{"); sb.append("uuid='").append(uuid).append('\''); sb.append(", key='").append(key).append('\''); sb.append(", name='").append(name).append('\''); sb.append('}'); return sb.toString(); } }
2,079
25
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/ProjectAnalysis.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.webhook; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static com.google.common.collect.ImmutableMap.copyOf; import static java.util.Objects.requireNonNull; public class ProjectAnalysis { private final Project project; private final CeTask ceTask; private final Branch branch; private final EvaluatedQualityGate qualityGate; private final Long updatedAt; private final Map<String, String> properties; private final Analysis analysis; public ProjectAnalysis(Project project, @Nullable CeTask ceTask, @Nullable Analysis analysis, @Nullable Branch branch, @Nullable EvaluatedQualityGate qualityGate, @Nullable Long updatedAt, Map<String, String> properties) { this.project = requireNonNull(project, "project can't be null"); this.ceTask = ceTask; this.branch = branch; this.qualityGate = qualityGate; this.updatedAt = updatedAt; this.properties = copyOf(requireNonNull(properties, "properties can't be null")); this.analysis = analysis; } public Optional<CeTask> getCeTask() { return Optional.ofNullable(ceTask); } public Project getProject() { return project; } public Optional<Branch> getBranch() { return Optional.ofNullable(branch); } public Optional<EvaluatedQualityGate> getQualityGate() { return Optional.ofNullable(qualityGate); } public Map<String, String> getProperties() { return properties; } public Optional<Analysis> getAnalysis() { return Optional.ofNullable(analysis); } public Optional<Long> getUpdatedAt() { return Optional.ofNullable(updatedAt); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProjectAnalysis that = (ProjectAnalysis) o; return Objects.equals(project, that.project) && Objects.equals(ceTask, that.ceTask) && Objects.equals(branch, that.branch) && Objects.equals(qualityGate, that.qualityGate) && Objects.equals(updatedAt, that.updatedAt) && Objects.equals(properties, that.properties) && Objects.equals(analysis, that.analysis); } @Override public int hashCode() { return Objects.hash(project, ceTask, branch, qualityGate, updatedAt, properties, analysis); } @Override public String toString() { return "ProjectAnalysis{" + "project=" + project + ", ceTask=" + ceTask + ", branch=" + branch + ", qualityGate=" + qualityGate + ", updatedAt=" + updatedAt + ", properties=" + properties + ", analysis=" + analysis + '}'; } }
3,614
30.163793
98
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebHooks.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.webhook; import java.util.function.Supplier; import javax.annotation.Nullable; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import org.sonar.api.config.Configuration; import org.sonar.db.project.ProjectDto; import static java.util.Objects.requireNonNull; public interface WebHooks { /** * Tells whether any webHook is configured for the specified {@link Configuration}. * * <p> * This can be used to not do consuming operations before calling * {@link #sendProjectAnalysisUpdate(Analysis, Supplier, PostProjectAnalysisTask.LogStatistics)} */ boolean isEnabled(ProjectDto projectDto); /** * Calls all WebHooks configured in the specified {@link Configuration} for the specified analysis with the * {@link WebhookPayload} provided by the specified Supplier. */ void sendProjectAnalysisUpdate(Analysis analysis, Supplier<WebhookPayload> payloadSupplier); /** * Override to be called from a {@link PostProjectAnalysisTask} implementation. */ void sendProjectAnalysisUpdate(Analysis analysis, Supplier<WebhookPayload> payloadSupplier, PostProjectAnalysisTask.LogStatistics taskLogStatistics); record Analysis(String projectUuid, String analysisUuid, String ceTaskUuid) { public Analysis(String projectUuid, @Nullable String analysisUuid, @Nullable String ceTaskUuid) { this.projectUuid = requireNonNull(projectUuid, "projectUuid can't be null"); this.analysisUuid = analysisUuid; this.ceTaskUuid = ceTaskUuid; } @Override public String toString() { return "Analysis{" + "projectUuid='" + projectUuid + '\'' + ", ceTaskUuid='" + ceTaskUuid + '\'' + '}'; } } }
2,560
36.661765
151
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebHooksImpl.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.webhook; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDao; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.async.AsyncExecution; import static java.lang.String.format; @ServerSide @ComputeEngineSide public class WebHooksImpl implements WebHooks { private static final Logger LOGGER = LoggerFactory.getLogger(WebHooksImpl.class); private final WebhookCaller caller; private final WebhookDeliveryStorage deliveryStorage; private final AsyncExecution asyncExecution; private final DbClient dbClient; public WebHooksImpl(WebhookCaller caller, WebhookDeliveryStorage deliveryStorage, AsyncExecution asyncExecution, DbClient dbClient) { this.caller = caller; this.deliveryStorage = deliveryStorage; this.asyncExecution = asyncExecution; this.dbClient = dbClient; } @Override public boolean isEnabled(ProjectDto projectDto) { return readWebHooksFrom(projectDto.getUuid(), null) .findAny() .isPresent(); } private Stream<WebhookDto> readWebHooksFrom(String projectUuid, @CheckForNull PostProjectAnalysisTask.LogStatistics taskLogStatistics) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<ProjectDto> optionalProjectDto = dbClient.projectDao().selectByUuid(dbSession, projectUuid); ProjectDto projectDto = checkStateWithOptional(optionalProjectDto, "the requested project '%s' was not found", projectUuid); WebhookDao dao = dbClient.webhookDao(); List<WebhookDto> projectWebhooks = dao.selectByProject(dbSession, projectDto); List<WebhookDto> globalWebhooks = dao.selectGlobalWebhooks(dbSession); if (taskLogStatistics != null) { taskLogStatistics.add("globalWebhooks", globalWebhooks.size()); taskLogStatistics.add("projectWebhooks", projectWebhooks.size()); } return Stream.concat(projectWebhooks.stream(), globalWebhooks.stream()); } } private static <T> T checkStateWithOptional(Optional<T> value, String message, Object... messageArguments) { if (!value.isPresent()) { throw new IllegalStateException(format(message, messageArguments)); } return value.get(); } @Override public void sendProjectAnalysisUpdate(Analysis analysis, Supplier<WebhookPayload> payloadSupplier) { sendProjectAnalysisUpdateImpl(analysis, payloadSupplier, null); } @Override public void sendProjectAnalysisUpdate(Analysis analysis, Supplier<WebhookPayload> payloadSupplier, PostProjectAnalysisTask.LogStatistics taskLogStatistics) { sendProjectAnalysisUpdateImpl(analysis, payloadSupplier, taskLogStatistics); } private void sendProjectAnalysisUpdateImpl(Analysis analysis, Supplier<WebhookPayload> payloadSupplier, @Nullable PostProjectAnalysisTask.LogStatistics taskLogStatistics) { List<Webhook> webhooks = readWebHooksFrom(analysis.projectUuid(), taskLogStatistics) .map(dto -> new Webhook(dto.getUuid(), analysis.projectUuid(), analysis.ceTaskUuid(), analysis.analysisUuid(), dto.getName(), dto.getUrl(), dto.getSecret())) .toList(); if (webhooks.isEmpty()) { return; } WebhookPayload payload = payloadSupplier.get(); webhooks.forEach(webhook -> asyncExecution.addToQueue(() -> { WebhookDelivery delivery = caller.call(webhook, payload); log(delivery); deliveryStorage.persist(delivery); })); asyncExecution.addToQueue(() -> deliveryStorage.purge(analysis.projectUuid())); } private static void log(WebhookDelivery delivery) { Optional<String> error = delivery.getErrorMessage(); if (error.isPresent()) { LOGGER.debug("Failed to send webhook '{}' | url={} | message={}", delivery.getWebhook().getName(), delivery.getWebhook().getUrl(), error.get()); } else { LOGGER.debug("Sent webhook '{}' | url={} | time={}ms | status={}", delivery.getWebhook().getName(), delivery.getWebhook().getUrl(), delivery.getDurationInMs().orElse(-1), delivery.getHttpStatus().orElse(-1)); } } }
5,350
38.932836
159
java