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-process/src/main/java/org/sonar/process/logging/Log4JPropertiesBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import java.io.File; import java.util.List; import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.process.MessageException; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.lang.String.valueOf; import static java.util.Optional.ofNullable; import static org.sonar.process.ProcessProperties.Property.LOG_LEVEL; import static org.sonar.process.ProcessProperties.Property.LOG_MAX_FILES; import static org.sonar.process.ProcessProperties.Property.LOG_ROLLING_POLICY; public class Log4JPropertiesBuilder extends AbstractLogHelper { private static final String PATTERN_LAYOUT = "PatternLayout"; private static final String ROOT_LOGGER_NAME = "rootLogger"; private static final int UNLIMITED_MAX_FILES = 100_000; private final Properties log4j2Properties = new Properties(); private final Props props; private RootLoggerConfig config; private String logPattern; private boolean allLogsToConsole; private File logDir; private LogLevelConfig logLevelConfig; private boolean jsonOutput; public Log4JPropertiesBuilder(Props props) { super("%logger{1.}"); this.props = Objects.requireNonNull(props, "Props can't be null"); internalLogLevel(Level.ERROR); } @Override public String getRootLoggerName() { return ROOT_LOGGER_NAME; } public Log4JPropertiesBuilder rootLoggerConfig(RootLoggerConfig config) { this.config = config; return this; } public Log4JPropertiesBuilder logPattern(String logPattern) { this.logPattern = logPattern; return this; } public Log4JPropertiesBuilder enableAllLogsToConsole(boolean allLogsToConsoleEnabled) { allLogsToConsole = allLogsToConsoleEnabled; return this; } public Log4JPropertiesBuilder jsonOutput(boolean jsonOutput) { this.jsonOutput = jsonOutput; return this; } public Log4JPropertiesBuilder logDir(File logDir) { this.logDir = logDir; return this; } public Log4JPropertiesBuilder logLevelConfig(LogLevelConfig logLevelConfig) { this.logLevelConfig = logLevelConfig; return this; } public Properties build() { checkNotNull(logDir, config); checkState(jsonOutput || (logPattern != null), "log pattern must be specified if not using json output"); configureGlobalFileLog(); if (allLogsToConsole) { configureGlobalStdoutLog(); } ofNullable(logLevelConfig).ifPresent(this::applyLogLevelConfiguration); Properties res = new Properties(); res.putAll(log4j2Properties); return res; } public Log4JPropertiesBuilder internalLogLevel(Level level) { putProperty("status", level.toString()); return this; } private void putProperty(String key, String value) { log4j2Properties.put(key, value); } private void putProperty(String prefix, String key, @Nullable String value) { log4j2Properties.put(prefix + key, value); } /** * Make log4j2 configuration for a process to push all its logs to a log file. * <p> * <ul> * <li>the file's name will use the prefix defined in {@link RootLoggerConfig#getProcessId()#getLogFilenamePrefix()}.</li> * <li>the file will follow the rotation policy defined in property {@link ProcessProperties.Property#LOG_ROLLING_POLICY} and * the max number of files defined in property {@link org.sonar.process.ProcessProperties.Property#LOG_MAX_FILES}</li> * <li>the logs will follow the specified log pattern</li> * </ul> * </p> * * @see #buildLogPattern(RootLoggerConfig) */ private void configureGlobalFileLog() { String appenderName = "file_" + config.getProcessId().getLogFilenamePrefix(); RollingPolicy rollingPolicy = createRollingPolicy(logDir, config.getProcessId().getLogFilenamePrefix()); writeFileAppender(appenderName, rollingPolicy, logPattern, jsonOutput); putProperty(ROOT_LOGGER_NAME + ".appenderRef." + appenderName + ".ref", appenderName); } private void configureGlobalStdoutLog() { String appenderName = "stdout"; writeConsoleAppender(appenderName, logPattern, jsonOutput); putProperty(ROOT_LOGGER_NAME + ".appenderRef." + appenderName + ".ref", appenderName); } private RollingPolicy createRollingPolicy(File logDir, String filenamePrefix) { String rollingPolicy = props.value(LOG_ROLLING_POLICY.getKey(), "time:yyyy-MM-dd"); int maxFiles = props.valueAsInt(LOG_MAX_FILES.getKey(), 7); if (maxFiles <= 0) { maxFiles = UNLIMITED_MAX_FILES; } if (rollingPolicy.startsWith("time:")) { return new TimeRollingPolicy(filenamePrefix, logDir, maxFiles, StringUtils.substringAfter(rollingPolicy, "time:")); } else if (rollingPolicy.startsWith("size:")) { return new SizeRollingPolicy(filenamePrefix, logDir, maxFiles, StringUtils.substringAfter(rollingPolicy, "size:")); } else if ("none".equals(rollingPolicy)) { return new NoRollingPolicy(filenamePrefix, logDir); } else { throw new MessageException(format("Unsupported value for property %s: %s", LOG_ROLLING_POLICY.getKey(), rollingPolicy)); } } private void applyLogLevelConfiguration(LogLevelConfig logLevelConfig) { if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) { throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\""); } Level propertyValueAsLevel = getPropertyValueAsLevel(props, LOG_LEVEL.getKey()); boolean traceGloballyEnabled = propertyValueAsLevel == Level.TRACE; List<String> loggerNames = Stream.of( logLevelConfig.getConfiguredByProperties().keySet().stream(), logLevelConfig.getConfiguredByHardcodedLevel().keySet().stream(), logLevelConfig.getOffUnlessTrace().stream().filter(k -> !traceGloballyEnabled)) .flatMap(s -> s) .filter(loggerName -> !ROOT_LOGGER_NAME.equals(loggerName)) .distinct() .sorted() .toList(); if (!loggerNames.isEmpty()) { putProperty("loggers", loggerNames.stream().collect(Collectors.joining(","))); } logLevelConfig.getConfiguredByProperties().forEach((loggerName, value) -> applyLevelByProperty(props, loggerName, value)); logLevelConfig.getConfiguredByHardcodedLevel().forEach(this::applyHardcodedLevel); logLevelConfig.getOffUnlessTrace().stream().filter(k -> !traceGloballyEnabled).forEach(logger -> applyHardcodedLevel(logger, Level.OFF)); } private void applyLevelByProperty(Props props, String loggerKey, List<String> properties) { putLevel(loggerKey, resolveLevel(props, properties.toArray(new String[0]))); } private void applyHardcodedLevel(String loggerName, Level newLevel) { putLevel(loggerName, newLevel); } private void putLevel(String loggerName, Level level) { if (loggerName.equals(ROOT_LOGGER_NAME)) { putProperty(loggerName + ".level", level.toString()); } else { putProperty("logger." + loggerName + ".name", loggerName); putProperty("logger." + loggerName + ".level", level.toString()); } } private void writeFileAppender(String appenderName, RollingPolicy rollingPolicy, @Nullable String logPattern, boolean jsonOutput) { String prefix = "appender." + appenderName + "."; putProperty(prefix, "name", appenderName); writeAppenderLayout(logPattern, jsonOutput, prefix); rollingPolicy.writePolicy(prefix); } private void writeConsoleAppender(String appenderName, @Nullable String logPattern, boolean jsonOutput) { String prefix = "appender." + appenderName + "."; putProperty(prefix, "type", "Console"); putProperty(prefix, "name", appenderName); writeAppenderLayout(logPattern, jsonOutput, prefix); } private void writeAppenderLayout(@Nullable String logPattern, boolean jsonOutput, String prefix) { putProperty(prefix, "layout.type", PATTERN_LAYOUT); if (!jsonOutput) { putProperty(prefix, "layout.pattern", logPattern); } else { putProperty(prefix, "layout.pattern", getJsonPattern()); } } /** * json pattern based on https://github.com/elastic/elasticsearch/blob/7.13/server/src/main/java/org/elasticsearch/common/logging/ESJsonLayout.java */ private String getJsonPattern() { String json = "{"; if (!"".equals(config.getNodeNameField())) { json = json + jsonKey("nodename") + inQuotes(config.getNodeNameField()) + ","; } return json + jsonKey("process") + inQuotes(config.getProcessId().getKey()) + "," + jsonKey("timestamp") + inQuotes("%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ}") + "," + jsonKey("severity") + inQuotes("%p") + "," + jsonKey("logger") + inQuotes("%c{1.}") + "," + jsonKey("message") + inQuotes("%notEmpty{%enc{%marker}{JSON} }%enc{%.-10000m}{JSON}") + "%exceptionAsJson " + "}" + System.lineSeparator(); } private static CharSequence jsonKey(String s) { return inQuotes(s) + ": "; } private static String inQuotes(String s) { return "\"" + s + "\""; } private abstract class RollingPolicy { final String filenamePrefix; final File logsDir; RollingPolicy(String filenamePrefix, File logsDir) { this.filenamePrefix = filenamePrefix; this.logsDir = logsDir; } abstract void writePolicy(String propertyPrefix); void writeTypeProperty(String propertyPrefix, String type) { putProperty(propertyPrefix + "type", type); } void writeFileNameProperty(String propertyPrefix) { putProperty(propertyPrefix + "fileName", new File(logsDir, filenamePrefix + ".log").getAbsolutePath()); } void writeFilePatternProperty(String propertyPrefix, String pattern) { putProperty(propertyPrefix + "filePattern", new File(logsDir, filenamePrefix + "." + pattern + ".log").getAbsolutePath()); } } /** * Log files are not rotated, for example when unix command logrotate is in place. */ private class NoRollingPolicy extends RollingPolicy { private NoRollingPolicy(String filenamePrefix, File logsDir) { super(filenamePrefix, logsDir); } @Override public void writePolicy(String propertyPrefix) { writeTypeProperty(propertyPrefix, "File"); writeFileNameProperty(propertyPrefix); } } private class TimeRollingPolicy extends RollingPolicy { private final String datePattern; private final int maxFiles; private TimeRollingPolicy(String filenamePrefix, File logsDir, int maxFiles, String datePattern) { super(filenamePrefix, logsDir); this.datePattern = datePattern; this.maxFiles = maxFiles; } @Override public void writePolicy(String propertyPrefix) { writeTypeProperty(propertyPrefix, "RollingFile"); writeFileNameProperty(propertyPrefix); writeFilePatternProperty(propertyPrefix, "%d{" + datePattern + "}"); putProperty(propertyPrefix + "policies.type", "Policies"); putProperty(propertyPrefix + "policies.time.type", "TimeBasedTriggeringPolicy"); putProperty(propertyPrefix + "policies.time.interval", "1"); putProperty(propertyPrefix + "policies.time.modulate", "true"); putProperty(propertyPrefix + "strategy.type", "DefaultRolloverStrategy"); putProperty(propertyPrefix + "strategy.fileIndex", "nomax"); putProperty(propertyPrefix + "strategy.action.type", "Delete"); putProperty(propertyPrefix + "strategy.action.basepath", logsDir.getAbsolutePath()); putProperty(propertyPrefix + "strategy.action.maxDepth", valueOf(1)); putProperty(propertyPrefix + "strategy.action.condition.type", "IfFileName"); putProperty(propertyPrefix + "strategy.action.condition.glob", filenamePrefix + "*"); putProperty(propertyPrefix + "strategy.action.condition.nested_condition.type", "IfAccumulatedFileCount"); putProperty(propertyPrefix + "strategy.action.condition.nested_condition.exceeds", valueOf(maxFiles)); } } private class SizeRollingPolicy extends RollingPolicy { private final String size; private final int maxFiles; private SizeRollingPolicy(String filenamePrefix, File logsDir, int maxFiles, String size) { super(filenamePrefix, logsDir); this.size = size; this.maxFiles = maxFiles; } @Override public void writePolicy(String propertyPrefix) { writeTypeProperty(propertyPrefix, "RollingFile"); writeFileNameProperty(propertyPrefix); writeFilePatternProperty(propertyPrefix, "%i"); putProperty(propertyPrefix + "policies.type", "Policies"); putProperty(propertyPrefix + "policies.size.type", "SizeBasedTriggeringPolicy"); putProperty(propertyPrefix + "policies.size.size", size); putProperty(propertyPrefix + "strategy.type", "DefaultRolloverStrategy"); putProperty(propertyPrefix + "strategy.max", valueOf(maxFiles)); } } }
14,112
36.735294
149
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/LogDomain.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; public enum LogDomain { SQL("sql"), ES("es"), JMX("jmx"), AUTH_EVENT("auth.event"); private final String key; LogDomain(String key) { this.key = key; } public String getKey() { return key; } }
1,101
28
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/LogLevelConfig.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.sonar.process.ProcessId; import static java.util.Objects.requireNonNull; import static org.sonar.process.ProcessProperties.Property.LOG_LEVEL; public final class LogLevelConfig { private static final String SONAR_LOG_LEVEL_PROPERTY = LOG_LEVEL.getKey(); private static final String PROCESS_NAME_PLACEHOLDER = "XXXX"; private static final String SONAR_PROCESS_LOG_LEVEL_PROPERTY = SONAR_LOG_LEVEL_PROPERTY + "." + PROCESS_NAME_PLACEHOLDER; private final Map<String, List<String>> configuredByProperties; private final Map<String, Level> configuredByHardcodedLevel; private final Set<String> offUnlessTrace; private final String rootLoggerName; private LogLevelConfig(Builder builder) { this.configuredByProperties = Collections.unmodifiableMap(builder.configuredByProperties); this.configuredByHardcodedLevel = Collections.unmodifiableMap(builder.configuredByHardcodedLevel); this.offUnlessTrace = Collections.unmodifiableSet(builder.offUnlessTrace); this.rootLoggerName = builder.rootLoggerName; } Map<String, List<String>> getConfiguredByProperties() { return configuredByProperties; } Map<String, Level> getConfiguredByHardcodedLevel() { return configuredByHardcodedLevel; } Set<String> getOffUnlessTrace() { return offUnlessTrace; } String getRootLoggerName() { return rootLoggerName; } public static Builder newBuilder(String rootLoggerName) { return new Builder(rootLoggerName); } public static final class Builder { private final Map<String, List<String>> configuredByProperties = new HashMap<>(); private final Map<String, Level> configuredByHardcodedLevel = new HashMap<>(); private final Set<String> offUnlessTrace = new HashSet<>(); private final String rootLoggerName; private Builder(String rootLoggerName) { this.rootLoggerName = requireNonNull(rootLoggerName, "rootLoggerName can't be null"); } /** * Configure the log level of the root logger to be read from the value of properties {@link #SONAR_LOG_LEVEL_PROPERTY} and * {@link #SONAR_PROCESS_LOG_LEVEL_PROPERTY}. */ public Builder rootLevelFor(ProcessId processId) { checkProcessId(processId); levelByProperty(rootLoggerName, SONAR_LOG_LEVEL_PROPERTY, SONAR_PROCESS_LOG_LEVEL_PROPERTY.replace(PROCESS_NAME_PLACEHOLDER, processId.getKey())); return this; } /** * Configure the log level of the logger with the specified name to be read from the value of properties * {@code sonar.log.level}, {@code sonar.log.level.[process_name]} and {@code sonar.log.level.[process_name].[LogDomain#getKey()]}. */ public Builder levelByDomain(String loggerName, ProcessId processId, LogDomain domain) { checkLoggerName(loggerName); checkProcessId(processId); requireNonNull(domain, "LogDomain can't be null"); String processProperty = SONAR_PROCESS_LOG_LEVEL_PROPERTY.replace(PROCESS_NAME_PLACEHOLDER, processId.getKey()); levelByProperty(loggerName, SONAR_LOG_LEVEL_PROPERTY, processProperty, processProperty + "." + domain.getKey()); return this; } private void levelByProperty(String loggerName, String property, String... otherProperties) { ensureUniqueConfiguration(loggerName); configuredByProperties.put(loggerName, Stream.concat(Stream.of(property), Arrays.stream(otherProperties)).toList()); } /** * Configure the log level of the logger with the specified name to be the specified one and it should never be * changed. */ public Builder immutableLevel(String loggerName, Level level) { checkLoggerName(loggerName); requireNonNull(level, "level can't be null"); ensureUniqueConfiguration(loggerName); configuredByHardcodedLevel.put(loggerName, level); return this; } private void ensureUniqueConfiguration(String loggerName) { if (configuredByProperties.containsKey(loggerName)) { throw new IllegalStateException("Configuration by property already registered for " + loggerName); } if (configuredByHardcodedLevel.containsKey(loggerName)) { throw new IllegalStateException("Configuration hardcoded level already registered for " + loggerName); } if (offUnlessTrace.contains(loggerName)) { throw new IllegalStateException("Configuration off unless TRACE already registered for " + loggerName); } } private static void checkProcessId(ProcessId processId) { requireNonNull(processId, "ProcessId can't be null"); } private static void checkLoggerName(String loggerName) { requireNonNull(loggerName, "loggerName can't be null"); if (loggerName.isEmpty()) { throw new IllegalArgumentException("loggerName can't be empty"); } } public Builder offUnlessTrace(String loggerName) { checkLoggerName(loggerName); ensureUniqueConfiguration(loggerName); offUnlessTrace.add(loggerName); return this; } public LogLevelConfig build() { return new LogLevelConfig(this); } } }
6,227
38.169811
152
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/LogbackHelper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.classic.jul.LevelChangePropagator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.Context; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; import ch.qos.logback.core.util.FileSize; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.logging.LogManager; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import org.sonar.process.MessageException; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import static java.lang.String.format; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.LOG_CONSOLE; import static org.sonar.process.ProcessProperties.Property.LOG_JSON_OUTPUT; import static org.sonar.process.ProcessProperties.Property.LOG_LEVEL; import static org.sonar.process.ProcessProperties.Property.LOG_MAX_FILES; import static org.sonar.process.ProcessProperties.Property.LOG_ROLLING_POLICY; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; /** * Helps to configure Logback in a programmatic way, without using XML. */ public class LogbackHelper extends AbstractLogHelper { private static final String LOGBACK_LOGGER_NAME_PATTERN = "%logger{20}"; public LogbackHelper() { super(LOGBACK_LOGGER_NAME_PATTERN); } public static Collection<Level> allowedLogLevels() { return Arrays.asList(ALLOWED_ROOT_LOG_LEVELS); } @Override public String getRootLoggerName() { return ROOT_LOGGER_NAME; } public LoggerContext getRootContext() { org.slf4j.Logger logger; while (!((logger = LoggerFactory.getLogger(ROOT_LOGGER_NAME)) instanceof Logger)) { // It occurs when the initialization step is still not finished because of a race condition // on ILoggerFactory.getILoggerFactory // http://jira.qos.ch/browse/SLF4J-167 // Substitute loggers are used. // http://www.slf4j.org/codes.html#substituteLogger // Bug is not fixed in SLF4J 1.7.14. try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } return ((Logger) logger).getLoggerContext(); } public LoggerContextListener enableJulChangePropagation(LoggerContext loggerContext) { LogManager.getLogManager().reset(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); propagator.start(); loggerContext.addListener(propagator); return propagator; } /** * Applies the specified {@link LogLevelConfig} reading the specified {@link Props}. * * @throws IllegalArgumentException if the any level specified in a property is not one of {@link #ALLOWED_ROOT_LOG_LEVELS} */ public LoggerContext apply(LogLevelConfig logLevelConfig, Props props) { if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) { throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\""); } LoggerContext rootContext = getRootContext(); logLevelConfig.getConfiguredByProperties().forEach((key, value) -> applyLevelByProperty(props, rootContext.getLogger(key), value)); logLevelConfig.getConfiguredByHardcodedLevel().forEach((key, value) -> applyHardcodedLevel(rootContext, key, value)); Level propertyValueAsLevel = getPropertyValueAsLevel(props, LOG_LEVEL.getKey()); boolean traceGloballyEnabled = propertyValueAsLevel == Level.TRACE; logLevelConfig.getOffUnlessTrace().forEach(logger -> applyHardUnlessTrace(rootContext, logger, traceGloballyEnabled)); return rootContext; } private static void applyLevelByProperty(Props props, Logger logger, List<String> properties) { logger.setLevel(resolveLevel(props, properties.toArray(new String[0]))); } private static void applyHardcodedLevel(LoggerContext rootContext, String loggerName, Level newLevel) { rootContext.getLogger(loggerName).setLevel(newLevel); } private static void applyHardUnlessTrace(LoggerContext rootContext, String logger, boolean traceGloballyEnabled) { if (!traceGloballyEnabled) { rootContext.getLogger(logger).setLevel(Level.OFF); } } public void changeRoot(LogLevelConfig logLevelConfig, Level newLevel) { ensureSupportedLevel(newLevel); LoggerContext rootContext = getRootContext(); rootContext.getLogger(ROOT_LOGGER_NAME).setLevel(newLevel); logLevelConfig.getConfiguredByProperties().forEach((key, value) -> rootContext.getLogger(key).setLevel(newLevel)); } private static void ensureSupportedLevel(Level newLevel) { if (!isAllowed(newLevel)) { throw new IllegalArgumentException(format("%s log level is not supported (allowed levels are %s)", newLevel, Arrays.toString(ALLOWED_ROOT_LOG_LEVELS))); } } /** * Creates a new {@link ConsoleAppender} to {@code System.out} with the specified name and log encoder. */ public ConsoleAppender<ILoggingEvent> newConsoleAppender(Context loggerContext, String name, Encoder<ILoggingEvent> encoder) { ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>(); consoleAppender.setContext(loggerContext); consoleAppender.setEncoder(encoder); consoleAppender.setName(name); consoleAppender.setTarget("System.out"); consoleAppender.start(); return consoleAppender; } /** * Make logback configuration for a process to push all its logs to a log file. * <p> * <ul> * <li>the file's name will use the prefix defined in {@link RootLoggerConfig#getProcessId()#getLogFilenamePrefix()}.</li> * <li>the file will follow the rotation policy defined in property {@link ProcessProperties.Property#LOG_ROLLING_POLICY} and * the max number of files defined in property {@link org.sonar.process.ProcessProperties.Property#LOG_MAX_FILES}</li> * <li>the logs will follow the specified log encoder</li> * </ul> * </p> */ public void configureGlobalFileLog(Props props, RootLoggerConfig config, Encoder<ILoggingEvent> encoder) { LoggerContext ctx = getRootContext(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); FileAppender<ILoggingEvent> fileAppender = newFileAppender(ctx, props, config, encoder); rootLogger.addAppender(fileAppender); } public FileAppender<ILoggingEvent> newFileAppender(LoggerContext ctx, Props props, RootLoggerConfig config, Encoder<ILoggingEvent> encoder) { RollingPolicy rollingPolicy = createRollingPolicy(ctx, props, config.getProcessId().getLogFilenamePrefix()); FileAppender<ILoggingEvent> fileAppender = rollingPolicy.createAppender("file_" + config.getProcessId().getLogFilenamePrefix()); fileAppender.setContext(ctx); fileAppender.setEncoder(encoder); fileAppender.start(); return fileAppender; } /** * Make the logback configuration for a sub process to correctly push all its logs to be read by a stream gobbler * on the sub process's System.out. */ public void configureForSubprocessGobbler(Props props, Encoder<ILoggingEvent> encoder) { if (isAllLogsToConsoleEnabled(props)) { LoggerContext ctx = getRootContext(); ctx.getLogger(ROOT_LOGGER_NAME).addAppender(newConsoleAppender(ctx, "root_console", encoder)); } } /** * Finds out whether we are in testing environment (usually ITs) and logs of all processes must be forward to * App's System.out. This is specified by the value of property {@link ProcessProperties.Property#LOG_CONSOLE}. */ public boolean isAllLogsToConsoleEnabled(Props props) { return props.valueAsBoolean(LOG_CONSOLE.getKey(), false); } public Level getLoggerLevel(String loggerName) { return getRootContext().getLogger(loggerName).getLevel(); } /** * Generally used to reset logback in logging tests */ public void resetFromXml(String xmlResourcePath) throws JoranException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(LogbackHelper.class.getResource(xmlResourcePath)); } public Encoder<ILoggingEvent> createEncoder(Props props, RootLoggerConfig config, LoggerContext context) { if (props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), Boolean.parseBoolean(LOG_JSON_OUTPUT.getDefaultValue()))) { LayoutWrappingEncoder encoder = new LayoutWrappingEncoder<>(); encoder.setLayout(new LogbackJsonLayout(config.getProcessId().getKey(), config.getNodeNameField())); encoder.setContext(context); encoder.start(); return encoder; } PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern(buildLogPattern(config)); encoder.start(); return encoder; } public RollingPolicy createRollingPolicy(Context ctx, Props props, String filenamePrefix) { String rollingPolicy = props.value(LOG_ROLLING_POLICY.getKey(), "time:yyyy-MM-dd"); int maxFiles = props.valueAsInt(LOG_MAX_FILES.getKey(), 7); File logsDir = props.nonNullValueAsFile(PATH_LOGS.getKey()); if (rollingPolicy.startsWith("time:")) { return new TimeRollingPolicy(ctx, filenamePrefix, logsDir, maxFiles, StringUtils.substringAfter(rollingPolicy, "time:")); } else if (rollingPolicy.startsWith("size:")) { return new SizeRollingPolicy(ctx, filenamePrefix, logsDir, maxFiles, StringUtils.substringAfter(rollingPolicy, "size:")); } else if ("none".equals(rollingPolicy)) { return new NoRollingPolicy(ctx, filenamePrefix, logsDir, maxFiles); } else { throw new MessageException(format("Unsupported value for property %s: %s", LOG_ROLLING_POLICY.getKey(), rollingPolicy)); } } public abstract static class RollingPolicy { protected final Context context; final String filenamePrefix; final File logsDir; final int maxFiles; RollingPolicy(Context context, String filenamePrefix, File logsDir, int maxFiles) { this.context = context; this.filenamePrefix = filenamePrefix; this.logsDir = logsDir; this.maxFiles = maxFiles; } public abstract FileAppender<ILoggingEvent> createAppender(String appenderName); } /** * Log files are not rotated, for example when unix command logrotate is in place. */ private static class NoRollingPolicy extends RollingPolicy { private NoRollingPolicy(Context context, String filenamePrefix, File logsDir, int maxFiles) { super(context, filenamePrefix, logsDir, maxFiles); } @Override public FileAppender<ILoggingEvent> createAppender(String appenderName) { FileAppender<ILoggingEvent> appender = new FileAppender<>(); appender.setContext(context); appender.setFile(new File(logsDir, filenamePrefix + ".log").getAbsolutePath()); appender.setName(appenderName); return appender; } } /** * Log files are rotated according to time (one file per day, month or year). * See http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy */ private static class TimeRollingPolicy extends RollingPolicy { private final String datePattern; private TimeRollingPolicy(Context context, String filenamePrefix, File logsDir, int maxFiles, String datePattern) { super(context, filenamePrefix, logsDir, maxFiles); this.datePattern = datePattern; } @Override public FileAppender<ILoggingEvent> createAppender(String appenderName) { RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>(); appender.setContext(context); appender.setName(appenderName); String filePath = new File(logsDir, filenamePrefix + ".log").getAbsolutePath(); appender.setFile(filePath); TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy(); rollingPolicy.setContext(context); rollingPolicy.setFileNamePattern(StringUtils.replace(filePath, filenamePrefix + ".log", filenamePrefix + ".%d{" + datePattern + "}.log")); rollingPolicy.setMaxHistory(maxFiles); rollingPolicy.setParent(appender); rollingPolicy.start(); appender.setRollingPolicy(rollingPolicy); return appender; } } /** * Log files are rotated according to their size. * See http://logback.qos.ch/manual/appenders.html#FixedWindowRollingPolicy */ private static class SizeRollingPolicy extends RollingPolicy { private final String size; private SizeRollingPolicy(Context context, String filenamePrefix, File logsDir, int maxFiles, String parameter) { super(context, filenamePrefix, logsDir, maxFiles); this.size = parameter; } @Override public FileAppender<ILoggingEvent> createAppender(String appenderName) { RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>(); appender.setContext(context); appender.setName(appenderName); String filePath = new File(logsDir, filenamePrefix + ".log").getAbsolutePath(); appender.setFile(filePath); SizeBasedTriggeringPolicy<ILoggingEvent> trigger = new SizeBasedTriggeringPolicy<>(); trigger.setMaxFileSize(FileSize.valueOf(size)); trigger.setContext(context); trigger.start(); appender.setTriggeringPolicy(trigger); FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy(); rollingPolicy.setContext(context); rollingPolicy.setFileNamePattern(StringUtils.replace(filePath, filenamePrefix + ".log", filenamePrefix + ".%i.log")); rollingPolicy.setMinIndex(1); rollingPolicy.setMaxIndex(maxFiles); rollingPolicy.setParent(appender); rollingPolicy.start(); appender.setRollingPolicy(rollingPolicy); return appender; } } }
15,588
40.905914
158
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/LogbackJsonLayout.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.StackTraceElementProxy; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.LayoutBase; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringWriter; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Formats logs in JSON. * <p> * Strongly inspired by https://github.com/qos-ch/logback/blob/master/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultThrowableRenderer.java */ public class LogbackJsonLayout extends LayoutBase<ILoggingEvent> { static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME .withLocale(Locale.US) .withZone(ZoneId.systemDefault()); private static final Pattern NEWLINE_REGEXP = Pattern.compile("\n"); private final String processKey; private final String nodeName; public LogbackJsonLayout(String processKey, String nodeName) { this.processKey = requireNonNull(processKey); this.nodeName = nodeName; } String getProcessKey() { return processKey; } @Override public String doLayout(ILoggingEvent event) { StringWriter output = new StringWriter(); try (JsonWriter json = new JsonWriter(output)) { json.beginObject(); if (!"".equals(nodeName)) { json.name("nodename").value(nodeName); } json.name("process").value(processKey); for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) { if (entry.getValue() != null) { json.name(entry.getKey()).value(entry.getValue()); } } json .name("timestamp").value(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))) .name("severity").value(event.getLevel().toString()) .name("logger").value(event.getLoggerName()) .name("message").value(NEWLINE_REGEXP.matcher(event.getFormattedMessage()).replaceAll("\r")); IThrowableProxy tp = event.getThrowableProxy(); if (tp != null) { json.name("stacktrace").beginArray(); int nbOfTabs = 0; while (tp != null) { printFirstLine(json, tp, nbOfTabs); render(json, tp, nbOfTabs); tp = tp.getCause(); nbOfTabs++; } json.endArray(); } json.endObject(); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("BUG - fail to create JSON", e); } output.write(System.lineSeparator()); return output.toString(); } private static void render(JsonWriter output, IThrowableProxy tp, int nbOfTabs) throws IOException { String tabs = StringUtils.repeat("\t", nbOfTabs); int commonFrames = tp.getCommonFrames(); StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); for (int i = 0; i < stepArray.length - commonFrames; i++) { StackTraceElementProxy step = stepArray[i]; output.value(tabs + step.toString()); } if (commonFrames > 0) { output.value(tabs + "... " + commonFrames + " common frames omitted"); } for (IThrowableProxy suppressed : tp.getSuppressed()) { output.value(format("%sSuppressed: %s: %s", tabs, suppressed.getClassName(), suppressed.getMessage())); render(output, suppressed, nbOfTabs + 1); } } private static void printFirstLine(JsonWriter output, IThrowableProxy tp, int nbOfTabs) throws IOException { String tabs = StringUtils.repeat("\t", nbOfTabs); int commonFrames = tp.getCommonFrames(); if (commonFrames > 0) { output.value(tabs + CoreConstants.CAUSED_BY); } output.value(tabs + tp.getClassName() + ": " + tp.getMessage()); } }
4,891
35.237037
157
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/PatternLayoutEncoder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.pattern.PatternLayoutEncoderBase; import java.util.Map; public class PatternLayoutEncoder extends PatternLayoutEncoderBase<ILoggingEvent> { @Override public void start() { PatternLayout patternLayout = new PatternLayout(); patternLayout.getDefaultConverterMap().putAll(getEscapedMessageConverterConfig()); patternLayout.setContext(context); patternLayout.setPattern(getPattern()); patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); patternLayout.start(); this.layout = patternLayout; super.start(); } private static Map<String, String> getEscapedMessageConverterConfig() { return Map.of( "m", EscapedMessageConverter.class.getName(), "msg", EscapedMessageConverter.class.getName(), "message", EscapedMessageConverter.class.getName()); } }
1,819
36.142857
86
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/RootLoggerConfig.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.process.ProcessId; import static java.util.Objects.requireNonNull; public final class RootLoggerConfig { private final ProcessId processId; private final String threadIdFieldPattern; private final String nodeNameField; private RootLoggerConfig(Builder builder) { this.processId = requireNonNull(builder.processId); this.threadIdFieldPattern = builder.threadIdFieldPattern; this.nodeNameField = Optional.ofNullable(builder.nodeNameField).orElse(""); } public static Builder newRootLoggerConfigBuilder() { return new Builder(); } public String getNodeNameField() { return nodeNameField; } public ProcessId getProcessId() { return processId; } public String getThreadIdFieldPattern() { return threadIdFieldPattern; } public static final class Builder { @CheckForNull private ProcessId processId; private String threadIdFieldPattern = ""; private String nodeNameField; private Builder() { // prevents instantiation outside RootLoggerConfig, use static factory method } public Builder setNodeNameField(@Nullable String nodeNameField) { this.nodeNameField = nodeNameField; return this; } public Builder setProcessId(ProcessId processId) { this.processId = processId; return this; } public Builder setThreadIdFieldPattern(String threadIdFieldPattern) { this.threadIdFieldPattern = requireNonNull(threadIdFieldPattern, "threadIdFieldPattern can't be null"); return this; } public RootLoggerConfig build() { return new RootLoggerConfig(this); } } }
2,610
29.360465
109
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/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.process.logging; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/sharedmemoryfile/AllProcessesCommands.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.sharedmemoryfile; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.rightPad; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; /** * Process inter-communication to : * <ul> * <li>share status of child process</li> * <li>stop/restart child process</li> * </ul> * * <p> * It relies on a single file accessed by all processes through a {@link MappedByteBuffer}.<br/> * Following alternatives were considered but not selected : * <ul> * <li>JMX beans over RMI: network issues (mostly because of Java reverse-DNS) + requires to configure and open a new port</li> * <li>simple socket protocol: same drawbacks are RMI connection</li> * <li>java.lang.Process#destroy(): shutdown hooks are not executed on some OS (mostly MSWindows)</li> * <li>execute OS-specific commands (for instance kill on *nix): OS-specific, so hell to support. Moreover how to get identify a process ?</li> * </ul> * </p> * * <p> * The file contains {@link ProcessCommands#MAX_PROCESSES} groups of {@link #BYTE_LENGTH_FOR_ONE_PROCESS} bits. * Each group of byte is used as follow: * <ul> * <li>First byte contains {@link #EMPTY} until process is UP and writes {@link #UP}</li> * <li>Second byte contains {@link #EMPTY} until any process requests current one to hard stop by writing value {@link #HARD_STOP}</li> * <li>Third byte contains {@link #EMPTY} until any process requests current one to stop by writing value {@link #STOP}</li> * <li>Fourth byte contains {@link #EMPTY} until any process requests current one to restart by writing value {@link #RESTART}. * Process acknowledges restart by writing back {@link #EMPTY}</li> * <li>Fifth byte will always contain {@link #EMPTY} unless process declares that it is operational by writing {@link #OPERATIONAL}. * This does not imply that it is done starting.</li> * <li>The next 8 bytes contains a long (value of {@link System#currentTimeMillis()}) which represents the date of the last ping</li> * </ul> * </p> */ public class AllProcessesCommands implements AutoCloseable { private static final int UP_BYTE_OFFSET = 0; private static final int HARD_STOP_BYTE_OFFSET = 1; private static final int STOP_BYTE_OFFSET = 2; private static final int RESTART_BYTE_OFFSET = 3; private static final int OPERATIONAL_BYTE_OFFSET = 4; private static final int PING_BYTE_OFFSET = 5; private static final int SYSTEM_INFO_URL_BYTE_OFFSET = PING_BYTE_OFFSET + 8; private static final int SYSTEM_INFO_URL_SIZE_IN_BYTES = 500; private static final int BYTE_LENGTH_FOR_ONE_PROCESS = 1 + 1 + 1 + 1 + 1 + 8 + SYSTEM_INFO_URL_SIZE_IN_BYTES; // With this shared memory we can handle up to MAX_PROCESSES processes private static final int MAX_SHARED_MEMORY = BYTE_LENGTH_FOR_ONE_PROCESS * MAX_PROCESSES; private static final byte HARD_STOP = (byte) 0xFF; private static final byte STOP = (byte) 0xD2; private static final byte RESTART = (byte) 0xAA; private static final byte OPERATIONAL = (byte) 0x59; private static final byte UP = (byte) 0x01; private static final byte EMPTY = (byte) 0x00; // VisibleForTesting final MappedByteBuffer mappedByteBuffer; private final RandomAccessFile sharedMemory; public AllProcessesCommands(File directory) { if (!directory.isDirectory() || !directory.exists()) { throw new IllegalArgumentException("Not a valid directory: " + directory); } try { sharedMemory = new RandomAccessFile(new File(directory, "sharedmemory"), "rw"); mappedByteBuffer = sharedMemory.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, MAX_SHARED_MEMORY); } catch (IOException e) { throw new IllegalArgumentException("Unable to create shared memory : ", e); } } public void clean() { for (int i = 0; i < MAX_PROCESSES; i++) { cleanData(i); } } public ProcessCommands create(int processNumber) { return createForProcess(processNumber, false); } public ProcessCommands createAfterClean(int processNumber) { return createForProcess(processNumber, true); } private ProcessCommands createForProcess(int processNumber, boolean clean) { checkProcessNumber(processNumber); ProcessCommands processCommands = new ProcessCommandsImpl(processNumber); if (clean) { cleanData(processNumber); } return processCommands; } boolean isUp(int processNumber) { return readByte(processNumber, UP_BYTE_OFFSET) == UP; } /** * To be executed by child process to declare that it is done starting */ void setUp(int processNumber) { writeByte(processNumber, UP_BYTE_OFFSET, UP); } boolean isOperational(int processNumber) { return readByte(processNumber, OPERATIONAL_BYTE_OFFSET) == OPERATIONAL; } /** * To be executed by child process to declare that it is started and fully operational */ void setOperational(int processNumber) { writeByte(processNumber, OPERATIONAL_BYTE_OFFSET, OPERATIONAL); } void ping(int processNumber) { writeLong(processNumber, PING_BYTE_OFFSET, System.currentTimeMillis()); } long getLastPing(int processNumber) { return readLong(processNumber, PING_BYTE_OFFSET); } String getSystemInfoUrl(int processNumber) { byte[] urlBytes = readBytes(processNumber, SYSTEM_INFO_URL_BYTE_OFFSET, SYSTEM_INFO_URL_SIZE_IN_BYTES); return new String(urlBytes, StandardCharsets.US_ASCII).trim(); } void setSystemInfoUrl(int processNumber, String url) { byte[] urlBytes = rightPad(url, SYSTEM_INFO_URL_SIZE_IN_BYTES).getBytes(StandardCharsets.US_ASCII); if (urlBytes.length > SYSTEM_INFO_URL_SIZE_IN_BYTES) { throw new IllegalArgumentException(format("System Info URL is too long. Max is %d bytes. Got: %s", SYSTEM_INFO_URL_SIZE_IN_BYTES, url)); } writeBytes(processNumber, SYSTEM_INFO_URL_BYTE_OFFSET, urlBytes); } /** * To be executed by monitor process to ask for graceful child process termination */ void askForStop(int processNumber) { writeByte(processNumber, STOP_BYTE_OFFSET, STOP); } boolean askedForStop(int processNumber) { return readByte(processNumber, STOP_BYTE_OFFSET) == STOP; } /** * To be executed by monitor process to ask for quick child process termination */ void askForHardStop(int processNumber) { writeByte(processNumber, HARD_STOP_BYTE_OFFSET, HARD_STOP); } boolean askedForHardStop(int processNumber) { return readByte(processNumber, HARD_STOP_BYTE_OFFSET) == HARD_STOP; } void askForRestart(int processNumber) { writeByte(processNumber, RESTART_BYTE_OFFSET, RESTART); } boolean askedForRestart(int processNumber) { return readByte(processNumber, RESTART_BYTE_OFFSET) == RESTART; } void acknowledgeAskForRestart(int processNumber) { writeByte(processNumber, RESTART_BYTE_OFFSET, EMPTY); } @Override public void close() { IOUtils.closeQuietly(sharedMemory); } public void checkProcessNumber(int processNumber) { if (processNumber < 0 || processNumber >= MAX_PROCESSES) { throw new IllegalArgumentException(format("Process number %s is not valid", processNumber)); } } private void cleanData(int processNumber) { for (int i = 0; i < BYTE_LENGTH_FOR_ONE_PROCESS; i++) { writeByte(processNumber, i, EMPTY); } } private void writeByte(int processNumber, int offset, byte value) { mappedByteBuffer.put(offset(processNumber) + offset, value); } private void writeBytes(int processNumber, int offset, byte[] value) { int bufferOffset = offset(processNumber) + offset; for (int i = 0; i < value.length; i++) { mappedByteBuffer.put(bufferOffset + i, value[i]); } } private byte readByte(int processNumber, int offset) { return mappedByteBuffer.get(offset(processNumber) + offset); } private byte[] readBytes(int processNumber, int offset, int length) { int bufferOffset = offset(processNumber) + offset; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = mappedByteBuffer.get(bufferOffset + i); } return bytes; } private void writeLong(int processNumber, int offset, long value) { mappedByteBuffer.putLong(offset(processNumber) + offset, value); } private long readLong(int processNumber, int offset) { return mappedByteBuffer.getLong(offset(processNumber) + offset); } // VisibleForTesting int offset(int processNumber) { return BYTE_LENGTH_FOR_ONE_PROCESS * processNumber; } private class ProcessCommandsImpl implements ProcessCommands { private final int processNumber; public ProcessCommandsImpl(int processNumber) { this.processNumber = processNumber; } @Override public boolean isUp() { return AllProcessesCommands.this.isUp(processNumber); } @Override public void setUp() { AllProcessesCommands.this.setUp(processNumber); } @Override public boolean isOperational() { return AllProcessesCommands.this.isOperational(processNumber); } @Override public void setOperational() { AllProcessesCommands.this.setOperational(processNumber); } @Override public void ping() { AllProcessesCommands.this.ping(processNumber); } @Override public long getLastPing() { return AllProcessesCommands.this.getLastPing(processNumber); } @Override public void setHttpUrl(String s) { AllProcessesCommands.this.setSystemInfoUrl(processNumber, s); } @Override public String getHttpUrl() { return AllProcessesCommands.this.getSystemInfoUrl(processNumber); } @Override public void askForStop() { AllProcessesCommands.this.askForStop(processNumber); } @Override public boolean askedForStop() { return AllProcessesCommands.this.askedForStop(processNumber); } @Override public void askForHardStop() { AllProcessesCommands.this.askForHardStop(processNumber); } @Override public boolean askedForHardStop() { return AllProcessesCommands.this.askedForHardStop(processNumber); } @Override public void askForRestart() { AllProcessesCommands.this.askForRestart(processNumber); } @Override public boolean askedForRestart() { return AllProcessesCommands.this.askedForRestart(processNumber); } @Override public void acknowledgeAskForRestart() { AllProcessesCommands.this.acknowledgeAskForRestart(processNumber); } @Override public void endWatch() { throw new UnsupportedOperationException("ProcessCommands created from AllProcessesCommands can not be closed directly. Close AllProcessesCommands instead"); } } }
11,884
32.860399
162
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommands.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.sharedmemoryfile; import java.io.File; import org.slf4j.LoggerFactory; /** * Default implementation of {@link ProcessCommands} based on a {@link AllProcessesCommands} of which will request a * single {@link ProcessCommands} to use as delegate for the specified processNumber. */ public class DefaultProcessCommands implements ProcessCommands, AutoCloseable { private final AllProcessesCommands allProcessesCommands; private final ProcessCommands delegate; private DefaultProcessCommands(File directory, int processNumber, boolean clean) { this.allProcessesCommands = new AllProcessesCommands(directory); this.delegate = clean ? allProcessesCommands.createAfterClean(processNumber) : allProcessesCommands.create(processNumber); } /** * Main DefaultProcessCommands will clear the shared memory space of the specified process number when created and will * then write and/or read to it. * Therefore there should be only one main DefaultProcessCommands. */ public static DefaultProcessCommands main(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, true); } /** * Secondary DefaultProcessCommands will read and write to the shared memory space but will not clear it. Therefore, there * can be any number of them. */ public static DefaultProcessCommands secondary(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, false); } /** * Clears the shared memory space of the specified process number. */ public static void reset(File directory, int processNumber) { try (DefaultProcessCommands processCommands = new DefaultProcessCommands(directory, processNumber, true)) { // nothing else to do than open file and reset the space of specified process } } @Override public boolean isUp() { return delegate.isUp(); } @Override public void setUp() { delegate.setUp(); } @Override public boolean isOperational() { return delegate.isOperational(); } @Override public void setOperational() { delegate.setOperational(); } @Override public void ping() { delegate.ping(); } @Override public long getLastPing() { return delegate.getLastPing(); } @Override public void setHttpUrl(String s) { delegate.setHttpUrl(s); } @Override public String getHttpUrl() { return delegate.getHttpUrl(); } @Override public void askForStop() { delegate.askForStop(); } @Override public boolean askedForStop() { return delegate.askedForStop(); } @Override public void askForHardStop() { delegate.askForHardStop(); } @Override public boolean askedForHardStop() { return delegate.askedForHardStop(); } @Override public void askForRestart() { delegate.askForRestart(); } @Override public boolean askedForRestart() { return delegate.askedForRestart(); } @Override public void acknowledgeAskForRestart() { delegate.acknowledgeAskForRestart(); } @Override public void endWatch() { try { close(); } catch (Exception e) { LoggerFactory.getLogger(getClass()).error("Failed to close DefaultProcessCommands", e); } } @Override public void close() { allProcessesCommands.close(); } }
4,193
26.411765
126
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/sharedmemoryfile/ProcessCommands.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.sharedmemoryfile; import java.io.File; /** * Process inter-communication to : * <ul> * <li>share status of specific process</li> * <li>stop/restart a specific processes</li> * </ul> * * @see DefaultProcessCommands#main(File, int) * @see DefaultProcessCommands#secondary(File, int) */ public interface ProcessCommands { int MAX_PROCESSES = 5; boolean isUp(); /** * To be executed by child process to declare that it is done starting */ void setUp(); boolean isOperational(); /** * To be executed by child process to declare that it is done starting and fully operational. * * @throws IllegalStateException if {@link #setUp()} has not been called */ void setOperational(); void ping(); long getLastPing(); void setHttpUrl(String s); String getHttpUrl(); /** * To be executed by monitor process to ask for graceful child process termination */ void askForStop(); boolean askedForStop(); /** * To be executed by monitor process to ask for quick child process termination */ void askForHardStop(); boolean askedForHardStop(); /** * To be executed by child process to ask for restart of all child processes */ void askForRestart(); /** * Can be called by child or monitor process to know whether child process asked for restart */ boolean askedForRestart(); /** * To be executed by monitor process to acknowledge restart request from child process. */ void acknowledgeAskForRestart(); void endWatch(); }
2,395
24.763441
95
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/sharedmemoryfile/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.process.sharedmemoryfile; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/BaseSectionMBean.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import org.sonar.api.Startable; import org.sonar.process.Jmx; /** * Base implementation of a {@link SystemInfoSection} * that is exported as a JMX bean */ public abstract class BaseSectionMBean implements SystemInfoSection, Startable { /** * Auto-registers to MBean server */ @Override public void start() { Jmx.register(objectName(), this); } /** * Unregister, if needed */ @Override public void stop() { Jmx.unregister(objectName()); } public String objectName() { return "SonarQube:name=" + name(); } /** * Name of section in System Info page */ protected abstract String name(); }
1,529
26.321429
80
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/Global.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; /** * Interface to mark {@link SystemInfoSection} of web server as global. * In case of cluster mode, all the processes and nodes would return * the same values, so it's loaded once on the web server that receives * the user request. */ public interface Global { }
1,152
37.433333
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/JvmPropertiesSection.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; /** * Dumps {@link System#getProperties()} */ public class JvmPropertiesSection implements SystemInfoSection { private final String name; public JvmPropertiesSection(String name) { this.name = name; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName(name); Map<Object, Object> sortedProperties = new TreeMap<>(System.getProperties()); for (Map.Entry<Object, Object> systemProp : sortedProperties.entrySet()) { if (systemProp.getValue() != null) { setAttribute(protobuf, Objects.toString(systemProp.getKey()), Objects.toString(systemProp.getValue())); } } return protobuf.build(); } }
1,860
33.462963
111
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/JvmStateSection.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.util.Locale; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static java.lang.String.format; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; /** * Dumps state of JVM (memory, threads) */ public class JvmStateSection implements SystemInfoSection { private static final long MEGABYTE = 1024L * 1024L; private final String name; public JvmStateSection(String name) { this.name = name; } @Override public ProtobufSystemInfo.Section toProtobuf() { return toProtobuf(ManagementFactory.getMemoryMXBean()); } // Visible for testing ProtobufSystemInfo.Section toProtobuf(MemoryMXBean memoryBean) { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName(name); addAttributeInMb(protobuf,"Max Memory (MB)", Runtime.getRuntime().maxMemory()); addAttributeInMb(protobuf, "Free Memory (MB)", Runtime.getRuntime().freeMemory()); MemoryUsage heap = memoryBean.getHeapMemoryUsage(); addAttributeInMb(protobuf, "Heap Committed (MB)", heap.getCommitted()); addAttributeInMb(protobuf, "Heap Init (MB)", heap.getInit()); addAttributeInMb(protobuf, "Heap Max (MB)", heap.getMax()); addAttributeInMb(protobuf, "Heap Used (MB)", heap.getUsed()); MemoryUsage nonHeap = memoryBean.getNonHeapMemoryUsage(); addAttributeInMb(protobuf, "Non Heap Committed (MB)", nonHeap.getCommitted()); addAttributeInMb(protobuf, "Non Heap Init (MB)", nonHeap.getInit()); addAttributeInMb(protobuf, "Non Heap Max (MB)", nonHeap.getMax()); addAttributeInMb(protobuf, "Non Heap Used (MB)", nonHeap.getUsed()); OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); setAttribute(protobuf,"System Load Average", format(Locale.ENGLISH, "%.1f%% (last minute)", os.getSystemLoadAverage() * 100.0)); ThreadMXBean thread = ManagementFactory.getThreadMXBean(); setAttribute(protobuf, "Threads", thread.getThreadCount()); return protobuf.build(); } private static void addAttributeInMb(ProtobufSystemInfo.Section.Builder protobuf, String key, long valueInBytes) { if (valueInBytes >= 0L) { setAttribute(protobuf, key, valueInBytes / MEGABYTE); } } }
3,359
41.531646
132
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/SystemInfoSection.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; public interface SystemInfoSection { ProtobufSystemInfo.Section toProtobuf(); }
1,032
34.62069
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/SystemInfoUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import static java.util.Arrays.stream; public class SystemInfoUtils { private static final Joiner COMMA_JOINER = Joiner.on(", "); private SystemInfoUtils() { // prevent instantiation } public static void setAttribute(Section.Builder section, String key, @Nullable String value) { if (value != null) { section.addAttributesBuilder() .setKey(key) .setStringValue(value) .build(); } } public static void setAttribute(Section.Builder section, String key, @Nullable Collection<String> values) { if (values != null) { section.addAttributesBuilder() .setKey(key) .addAllStringValues(values) .build(); } } public static void setAttribute(Section.Builder section, String key, @Nullable Boolean value) { if (value != null) { section.addAttributesBuilder() .setKey(key) .setBooleanValue(value) .build(); } } public static void setAttribute(Section.Builder section, String key, long value) { section.addAttributesBuilder() .setKey(key) .setLongValue(value) .build(); } @CheckForNull public static ProtobufSystemInfo.Attribute attribute(Section section, String key) { for (ProtobufSystemInfo.Attribute attribute : section.getAttributesList()) { if (attribute.getKey().equals(key)) { return attribute; } } return null; } public static List<Section> order(Collection<Section> sections, String... orderedNames) { Map<String, Section> alphabeticalOrderedMap = new TreeMap<>(); sections.forEach(section -> alphabeticalOrderedMap.put(section.getName(), section)); List<Section> result = new ArrayList<>(sections.size()); stream(orderedNames).forEach(name -> { Section section = alphabeticalOrderedMap.remove(name); if (section != null) { result.add(section); } }); result.addAll(alphabeticalOrderedMap.values()); return result; } public static void addIfNotEmpty(ProtobufSystemInfo.Section.Builder protobuf, String key, @Nullable List<String> values) { if (values != null && !values.isEmpty()) { setAttribute(protobuf, key, COMMA_JOINER.join(values)); } } }
3,485
31.277778
124
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/systeminfo/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.process.systeminfo; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/AbstractStopperThreadTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.util.concurrent.TimeUnit; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; public class AbstractStopperThreadTest { private Monitored monitored = mock(Monitored.class); @Test public void stop_in_a_timely_fashion() { // max stop timeout is 5 seconds, but test fails after 3 seconds // -> guarantees that stop is immediate AbstractStopperThread stopper = new AbstractStopperThread("theThreadName", () -> monitored.hardStop(), 5000L){}; stopper.start(); verify(monitored, timeout(3000)).hardStop(); assertThat(stopper.getName()).isEqualTo("theThreadName"); } @Test public void stop_timeout() { doAnswer(invocationOnMock -> { await().atMost(10, TimeUnit.SECONDS).until(() -> false); return null; }).when(monitored).hardStop(); // max stop timeout is 100 milliseconds AbstractStopperThread stopper = new AbstractStopperThread("theThreadName", () -> monitored.hardStop(), 5000L){}; stopper.start(); verify(monitored, timeout(3000)).hardStop(); assertThat(stopper.getName()).isEqualTo("theThreadName"); } @Test public void stopIt_interrupts_worker() { doAnswer(invocationOnMock -> { await().atMost(10, TimeUnit.SECONDS).until(() -> false); return null; }).when(monitored).hardStop(); // max stop timeout is 100 milliseconds AbstractStopperThread stopper = new AbstractStopperThread("theThreadName", () -> monitored.hardStop(), 5000L){}; stopper.start(); verify(monitored, timeout(3_000)).hardStop(); stopper.stopIt(); await().atMost(3, TimeUnit.SECONDS).until(() -> !stopper.isAlive()); assertThat(stopper.isAlive()).isFalse(); } }
2,799
34.443038
116
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/ConfigurationUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.test.TestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class ConfigurationUtilsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void shouldInterpolateVariables() { Properties input = new Properties(); input.setProperty("hello", "world"); input.setProperty("url", "${env:SONAR_JDBC_URL}"); input.setProperty("do_not_change", "${SONAR_JDBC_URL}"); Map<String, String> variables = new HashMap<>(); variables.put("SONAR_JDBC_URL", "jdbc:h2:mem"); Properties output = ConfigurationUtils.interpolateVariables(input, variables); assertThat(output).hasSize(3); assertThat(output.getProperty("hello")).isEqualTo("world"); assertThat(output.getProperty("url")).isEqualTo("jdbc:h2:mem"); assertThat(output.getProperty("do_not_change")).isEqualTo("${SONAR_JDBC_URL}"); // input is not changed assertThat(input).hasSize(3); assertThat(input.getProperty("hello")).isEqualTo("world"); assertThat(input.getProperty("url")).isEqualTo("${env:SONAR_JDBC_URL}"); assertThat(input.getProperty("do_not_change")).isEqualTo("${SONAR_JDBC_URL}"); } @Test public void loadPropsFromCommandLineArgs_missing_argument() { try { ConfigurationUtils.loadPropsFromCommandLineArgs(new String[0]); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).startsWith("Only a single command-line argument is accepted"); } } @Test public void loadPropsFromCommandLineArgs_load_properties_from_file() throws Exception { File propsFile = temp.newFile(); FileUtils.write(propsFile, "foo=bar", StandardCharsets.UTF_8); Props result = ConfigurationUtils.loadPropsFromCommandLineArgs(new String[] {propsFile.getAbsolutePath()}); assertThat(result.value("foo")).isEqualTo("bar"); assertThat(result.rawProperties()).hasSize(1); } @Test public void loadPropsFromCommandLineArgs_file_does_not_exist() throws Exception { File propsFile = temp.newFile(); FileUtils.deleteQuietly(propsFile); try { ConfigurationUtils.loadPropsFromCommandLineArgs(new String[] {propsFile.getAbsolutePath()}); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Could not read properties from file: " + propsFile.getAbsolutePath()); } } @Test public void private_constructor() { assertThat(TestUtils.hasOnlyPrivateConstructors(ConfigurationUtils.class)).isTrue(); } }
3,682
35.107843
111
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/FileUtils2Test.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import javax.annotation.CheckForNull; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assume.assumeTrue; public class FileUtils2Test { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void cleanDirectory_throws_NPE_if_file_is_null() throws IOException { expectDirectoryCanNotBeNullNPE(() -> FileUtils2.cleanDirectory(null)); } @Test public void cleanDirectory_does_nothing_if_argument_does_not_exist() throws IOException { FileUtils2.cleanDirectory(new File("/a/b/ToDoSSS")); } @Test public void cleanDirectory_throws_IAE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); assertThatThrownBy(() -> FileUtils2.cleanDirectory(file)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'" + file.getAbsolutePath() + "' is not a directory"); } @Test public void cleanDirectory_removes_directories_and_files_in_target_directory_but_not_target_directory() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); // on supporting FileSystem, target will change if directory is recreated Object targetKey = getFileKey(target); FileUtils2.cleanDirectory(target.toFile()); assertThat(target).isDirectory(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); assertThat(getFileKey(target)).isEqualTo(targetKey); } @Test public void cleanDirectory_follows_symlink_to_target_directory() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path target = temporaryFolder.newFolder().toPath(); Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(symToDir).isSymbolicLink(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); // on supporting FileSystem, target will change if directory is recreated Object targetKey = getFileKey(target); Object symLinkKey = getFileKey(symToDir); FileUtils2.cleanDirectory(symToDir.toFile()); assertThat(target).isDirectory(); assertThat(symToDir).isSymbolicLink(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); assertThat(getFileKey(target)).isEqualTo(targetKey); assertThat(getFileKey(symToDir)).isEqualTo(symLinkKey); } @Test public void deleteQuietly_does_not_fail_if_argument_is_null() { FileUtils2.deleteQuietly(null); } @Test public void deleteQuietly_does_not_fail_if_file_does_not_exist() throws IOException { File file = new File(temporaryFolder.newFolder(), "blablabl"); assertThat(file).doesNotExist(); FileUtils2.deleteQuietly(file); } @Test public void deleteQuietly_deletes_directory_and_content() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); FileUtils2.deleteQuietly(target.toFile()); assertThat(target).doesNotExist(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); } @Test public void deleteQuietly_deletes_symbolicLink() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path folder = temporaryFolder.newFolder().toPath(); Path file1 = Files.createFile(folder.resolve("file1.txt")); Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1); assertThat(file1).isRegularFile(); assertThat(symLink).isSymbolicLink(); FileUtils2.deleteQuietly(symLink.toFile()); assertThat(symLink).doesNotExist(); assertThat(file1).isRegularFile(); } @Test public void deleteDirectory_throws_NPE_if_argument_is_null() throws IOException { expectDirectoryCanNotBeNullNPE(() -> FileUtils2.deleteDirectory(null)); } @Test public void deleteDirectory_does_not_fail_if_file_does_not_exist() throws IOException { File file = new File(temporaryFolder.newFolder(), "foo.d"); FileUtils2.deleteDirectory(file); } @Test public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); assertThatThrownBy(() -> FileUtils2.deleteDirectory(file)) .isInstanceOf(IOException.class) .hasMessage("Directory '" + file.getAbsolutePath() + "' is a file"); } @Test public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path folder = temporaryFolder.newFolder().toPath(); Path file1 = Files.createFile(folder.resolve("file1.txt")); Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1); assertThat(file1).isRegularFile(); assertThat(symLink).isSymbolicLink(); assertThatThrownBy(() -> FileUtils2.deleteDirectory(symLink.toFile())) .isInstanceOf(IOException.class) .hasMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link"); } @Test public void deleteDirectory_deletes_directory_and_content() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFile(childDir1.resolve("file2.txt")); Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2")); assertThat(target).isDirectory(); assertThat(childFile1).isRegularFile(); assertThat(childDir1).isDirectory(); assertThat(childFile2).isRegularFile(); assertThat(childDir2).isDirectory(); FileUtils2.deleteQuietly(target.toFile()); assertThat(target).doesNotExist(); assertThat(childFile1).doesNotExist(); assertThat(childDir1).doesNotExist(); assertThat(childFile2).doesNotExist(); assertThat(childDir2).doesNotExist(); } @Test public void sizeOf_sums_sizes_of_all_files_in_directory() throws IOException { File dir = temporaryFolder.newFolder(); File child = new File(dir, "child.txt"); File grandChild1 = new File(dir, "grand/child1.txt"); File grandChild2 = new File(dir, "grand/child2.txt"); FileUtils.write(child, "foo", UTF_8); FileUtils.write(grandChild1, "bar", UTF_8); FileUtils.write(grandChild2, "baz", UTF_8); long childSize = FileUtils2.sizeOf(child.toPath()); assertThat(childSize).isPositive(); long grandChild1Size = FileUtils2.sizeOf(grandChild1.toPath()); assertThat(grandChild1Size).isPositive(); long grandChild2Size = FileUtils2.sizeOf(grandChild2.toPath()); assertThat(grandChild2Size).isPositive(); assertThat(FileUtils2.sizeOf(dir.toPath())) .isEqualTo(childSize + grandChild1Size + grandChild2Size); // sanity check by comparing commons-io assertThat(FileUtils2.sizeOf(dir.toPath())) .isEqualTo(FileUtils.sizeOfDirectory(dir)); } @Test public void sizeOf_is_zero_on_empty_files() throws IOException { File file = temporaryFolder.newFile(); assertThat(FileUtils2.sizeOf(file.toPath())).isZero(); } @Test public void sizeOf_throws_IOE_if_path_does_not_exist() throws IOException { Path path = temporaryFolder.newFile().toPath(); Files.delete(path); assertThatThrownBy(() -> FileUtils2.sizeOf(path)) .isInstanceOf(IOException.class); } @Test public void sizeOf_ignores_size_of_non_regular_files() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); File outside = temporaryFolder.newFile(); FileUtils.write(outside, "outside!!!", UTF_8); File dir = temporaryFolder.newFolder(); File child = new File(dir, "child1.txt"); FileUtils.write(child, "inside!!!", UTF_8); File symlink = new File(dir, "child2.txt"); Files.createSymbolicLink(symlink.toPath(), outside.toPath()); assertThat(FileUtils2.sizeOf(dir.toPath())) .isPositive() .isEqualTo(FileUtils2.sizeOf(child.toPath())); } private void expectDirectoryCanNotBeNullNPE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(NullPointerException.class) .hasMessage("Directory can not be null"); } @CheckForNull private static Object getFileKey(Path path) throws IOException { BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); return attrs.fileKey(); } }
11,359
36.491749
126
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/JmxTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.lang.management.ManagementFactory; import javax.annotation.CheckForNull; import javax.management.InstanceNotFoundException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.Test; import org.sonar.process.jmx.Fake; import org.sonar.process.jmx.FakeMBean; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class JmxTest { static final String FAKE_NAME = "SonarQube:name=Fake"; FakeMBean mbean = new Fake(); @Test public void register_and_unregister() throws Exception { assertThat(lookupMBean()).isNull(); Jmx.register(FAKE_NAME, mbean); assertThat(lookupMBean()).isNotNull(); Jmx.unregister(FAKE_NAME); assertThat(lookupMBean()).isNull(); } @Test public void do_not_fail_when_unregistering_a_non_registered_bean() throws Exception { Jmx.unregister(FAKE_NAME); assertThat(lookupMBean()).isNull(); } @Test public void register_fails_if_mbean_interface_can_not_be_found() { assertThatThrownBy(() -> Jmx.register(FAKE_NAME, "not a mbean")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can not find the MBean interface of class java.lang.String"); } @Test public void register_fails_if_name_is_not_valid() { assertThatThrownBy(() -> Jmx.register("/", new Fake())) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not register MBean [/]"); } @Test public void support_implementation_in_different_package_than_interface() throws Exception { assertThat(lookupMBean()).isNull(); Jmx.register(FAKE_NAME, new org.sonar.process.jmx.test.Fake()); assertThat(lookupMBean()).isNotNull(); Jmx.unregister(FAKE_NAME); assertThat(lookupMBean()).isNull(); } @CheckForNull private ObjectInstance lookupMBean() throws Exception { try { return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(FAKE_NAME)); } catch (InstanceNotFoundException e) { return null; } } }
2,961
30.849462
101
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/LifecycleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.process.Lifecycle.State; import static org.sonar.process.Lifecycle.State.HARD_STOPPING; import static org.sonar.process.Lifecycle.State.INIT; import static org.sonar.process.Lifecycle.State.OPERATIONAL; import static org.sonar.process.Lifecycle.State.RESTARTING; import static org.sonar.process.Lifecycle.State.STARTED; import static org.sonar.process.Lifecycle.State.STARTING; import static org.sonar.process.Lifecycle.State.STOPPED; import static org.sonar.process.Lifecycle.State.STOPPING; import static org.sonar.process.Lifecycle.State.values; public class LifecycleTest { @Test public void equals_and_hashcode() { Lifecycle init = new Lifecycle(); assertThat(init.equals(init)).isTrue(); assertThat(init.equals(new Lifecycle())).isTrue(); assertThat(init.equals("INIT")).isFalse(); assertThat(init.equals(null)).isFalse(); assertThat(init).hasSameHashCodeAs(new Lifecycle()); // different state Lifecycle stopping = new Lifecycle(); stopping.tryToMoveTo(STARTING); assertThat(stopping).isNotEqualTo(init); } @Test public void try_to_move_does_not_support_jumping_states() { Lifecycle lifecycle = new Lifecycle(); assertThat(lifecycle.isCurrentState(INIT)).isTrue(); assertThat(lifecycle.tryToMoveTo(STARTED)).isFalse(); assertThat(lifecycle.isCurrentState(INIT)).isTrue(); assertThat(lifecycle.tryToMoveTo(STARTING)).isTrue(); assertThat(lifecycle.isCurrentState(STARTING)).isTrue(); } @Test public void no_state_can_not_move_to_itself() { for (State state : values()) { assertThat(newLifeCycle(state).tryToMoveTo(state)).isFalse(); } } @Test public void can_move_to_STOPPING_from_STARTING_STARTED_OPERATIONAL_only() { for (State state : values()) { boolean tryToMoveTo = newLifeCycle(state).tryToMoveTo(STOPPING); if (state == STARTING || state == STARTED || state == OPERATIONAL) { assertThat(tryToMoveTo).describedAs("from state " + state).isTrue(); } else { assertThat(tryToMoveTo).describedAs("from state " + state).isFalse(); } } } @Test public void can_move_to_OPERATIONAL_from_STARTED_only() { for (State state : values()) { boolean tryToMoveTo = newLifeCycle(state).tryToMoveTo(OPERATIONAL); if (state == STARTED) { assertThat(tryToMoveTo).describedAs("from state " + state).isTrue(); } else { assertThat(tryToMoveTo).describedAs("from state " + state).isFalse(); } } } @Test public void can_move_to_STARTING_from_RESTARTING() { assertThat(newLifeCycle(RESTARTING).tryToMoveTo(STARTING)).isTrue(); } @Test public void can_move_to_STOPPING_only_from_STARTING_STARTED_and_OPERATIONAL() { for (State state : values()) { boolean tryToMoveTo = newLifeCycle(state).tryToMoveTo(STOPPING); if (state == STARTING || state == STARTED || state == OPERATIONAL) { assertThat(tryToMoveTo).describedAs("from state " + state).isTrue(); } else { assertThat(tryToMoveTo).describedAs("from state " + state).isFalse(); } } } @Test public void can_move_to_HARD_STOPPING_from_any_step_but_from_INIT_HARD_STOPPING_and_STOPPED() { for (State state : values()) { boolean tryToMoveTo = newLifeCycle(state).tryToMoveTo(HARD_STOPPING); if (state == INIT || state == STOPPED || state == HARD_STOPPING) { assertThat(tryToMoveTo).describedAs("from state " + state).isFalse(); } else { assertThat(tryToMoveTo).describedAs("from state " + state).isTrue(); } } } /** * Creates a Lifecycle object in the specified state emulating that the shortest path to this state has been followed * to reach it. */ private static Lifecycle newLifeCycle(State state) { switch (state) { case INIT: return new Lifecycle(); case STARTING: return newLifeCycle(INIT, state); case STARTED: return newLifeCycle(STARTING, state); case OPERATIONAL: return newLifeCycle(STARTED, state); case RESTARTING: return newLifeCycle(OPERATIONAL, state); case STOPPING: return newLifeCycle(OPERATIONAL, state); case HARD_STOPPING: return newLifeCycle(STARTING, state); case STOPPED: return newLifeCycle(STOPPING, state); default: throw new IllegalArgumentException("Unsupported state " + state); } } private static Lifecycle newLifeCycle(State from, State to) { Lifecycle lifecycle; lifecycle = newLifeCycle(from); assertThat(lifecycle.tryToMoveTo(to)).isTrue(); return lifecycle; } }
5,615
34.1
119
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/LoggingRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.joran.spi.JoranException; import java.util.List; import org.junit.rules.ExternalResource; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.sonar.process.logging.LogbackHelper; public class LoggingRule extends ExternalResource { private final Class loggerClass; public LoggingRule(Class loggerClass) { this.loggerClass = loggerClass; } @Override protected void before() throws Throwable { new LogbackHelper().resetFromXml("/org/sonar/process/logback-test.xml"); TestLogbackAppender.events.clear(); setLevel(Level.INFO); } @Override protected void after() { TestLogbackAppender.events.clear(); setLevel(Level.INFO); try { new LogbackHelper().resetFromXml("/logback-test.xml"); } catch (JoranException e) { e.printStackTrace(); } } public LoggingRule setLevel(Level level) { Logger logbackLogger = (Logger) LoggerFactory.getLogger(loggerClass); ch.qos.logback.classic.Level l = ch.qos.logback.classic.Level.valueOf(level.name()); logbackLogger.setLevel(l); return this; } public List<String> getLogs() { return TestLogbackAppender.events.stream() .filter(e -> e.getLoggerName().equals(loggerClass.getName())) .map(LoggingEvent::getFormattedMessage) .toList(); } public List<String> getLogs(Level level) { return TestLogbackAppender.events.stream() .filter(e -> e.getLoggerName().equals(loggerClass.getName())) .filter(e -> e.getLevel().levelStr.equals(level.name())) .map(LoggingEvent::getFormattedMessage) .toList(); } public boolean hasLog(Level level, String message) { return TestLogbackAppender.events.stream() .filter(e -> e.getLoggerName().equals(loggerClass.getName())) .filter(e -> e.getLevel().levelStr.equals(level.name())) .anyMatch(e -> e.getFormattedMessage().equals(message)); } public boolean hasLog(String message) { return TestLogbackAppender.events.stream() .filter(e -> e.getLoggerName().equals(loggerClass.getName())) .anyMatch(e -> e.getFormattedMessage().equals(message)); } }
3,105
32.76087
88
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/MinimumViableSystemTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.collect.ImmutableMap; import java.io.File; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class MinimumViableSystemTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); MinimumViableSystem underTest = new MinimumViableSystem(); @Test public void checkRequiredJavaOptions() { String key = "MinimumViableEnvironmentTest.test.prop"; try { System.setProperty(key, "false"); underTest.checkRequiredJavaOptions(ImmutableMap.of(key, "true")); fail(); } catch (MessageException e) { assertThat(e).hasMessage("JVM option '" + key + "' must be set to 'true'. Got 'false'"); } System.setProperty(key, "true"); // do not fail underTest.checkRequiredJavaOptions(ImmutableMap.of(key, "true")); } @Test public void checkWritableTempDir() throws Exception { File dir = temp.newFolder(); underTest.checkWritableDir(dir.getAbsolutePath()); dir.delete(); try { underTest.checkWritableDir(dir.getAbsolutePath()); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Temp directory is not writable: " + dir.getAbsolutePath()); } } }
2,200
30.442857
94
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeThat; public class NetworkUtilsImplTest { private NetworkUtilsImpl underTest = new NetworkUtilsImpl(); @Test public void getNextAvailablePort_returns_a_port() throws Exception { String localhost = InetAddress.getLocalHost().getHostName(); int port = underTest.getNextAvailablePort(localhost).getAsInt(); assertThat(port) .isGreaterThan(1_023) .isLessThanOrEqualTo(65_535); } @Test public void getNextAvailablePort_does_not_return_twice_the_same_port() throws Exception { String localhost = InetAddress.getLocalHost().getHostName(); Set<Integer> ports = new HashSet<>(Arrays.asList( underTest.getNextAvailablePort(localhost).getAsInt(), underTest.getNextAvailablePort(localhost).getAsInt(), underTest.getNextAvailablePort(localhost).getAsInt())); assertThat(ports).hasSize(3); } @Test public void getLocalNonLoopbackIpv4Address_returns_a_valid_local_and_non_loopback_ipv4() { Optional<InetAddress> address = underTest.getLocalNonLoopbackIpv4Address(); // address is empty on offline builds assumeThat(address.isPresent(), CoreMatchers.is(true)); assertThat(address.get()).isInstanceOf(Inet4Address.class); assertThat(address.get().isLoopbackAddress()).isFalse(); } @Test public void getHostname_returns_hostname_of_localhost_otherwise_a_constant() { try { InetAddress localHost = InetAddress.getLocalHost(); assertThat(underTest.getHostname()).isEqualTo(localHost.getHostName()); } catch (UnknownHostException e) { // no localhost on host running the UT assertThat(underTest.getHostname()).isEqualTo("unresolved hostname"); } } @Test public void getLocalInetAddress_filters_local_addresses() { InetAddress address = underTest.getLocalInetAddress(InetAddress::isLoopbackAddress).get(); assertThat(address.isLoopbackAddress()).isTrue(); } @Test public void getLocalInetAddress_returns_empty_if_no_local_addresses_match() { Optional<InetAddress> address = underTest.getLocalInetAddress(a -> false); assertThat(address).isEmpty(); } @Test public void toInetAddress_supports_host_names() { assertThat(underTest.toInetAddress("localhost")).isNotEmpty(); // do not test values that require DNS calls. Build must support offline mode. } @Test public void toInetAddress_supports_ipv4() { assertThat(underTest.toInetAddress("1.2.3.4")).isNotEmpty(); } @Test public void toInetAddress_supports_ipv6() { assertThat(underTest.toInetAddress("2a01:e34:ef1f:dbb0:c2f6:a978:c5c0:9ccb")).isNotEmpty(); assertThat(underTest.toInetAddress("[2a01:e34:ef1f:dbb0:c2f6:a978:c5c0:9ccb]")).isNotEmpty(); } @Test public void toInetAddress_returns_empty_on_unvalid_IP_and_hostname() { assertThat(underTest.toInetAddress(randomAlphabetic(32))).isEmpty(); } @Test public void isLoopback_returns_true_on_loopback_address_or_host() { InetAddress loopback = InetAddress.getLoopbackAddress(); assertThat(underTest.isLoopback(loopback.getHostAddress())).isTrue(); assertThat(underTest.isLoopback(loopback.getHostName())).isTrue(); } @Test public void isLoopback_returns_true_on_localhost_address_or_host_if_loopback() { try { InetAddress localHost = InetAddress.getLocalHost(); boolean isLoopback = localHost.isLoopbackAddress(); assertThat(underTest.isLoopback(localHost.getHostAddress())).isEqualTo(isLoopback); assertThat(underTest.isLoopback(localHost.getHostName())).isEqualTo(isLoopback); } catch (UnknownHostException e) { // ignore, host running the test has no localhost } } @Test public void isLocal_returns_true_on_loopback_address_or_host() { InetAddress loopback = InetAddress.getLoopbackAddress(); assertThat(underTest.isLocal(loopback.getHostAddress())).isTrue(); assertThat(underTest.isLocal(loopback.getHostName())).isTrue(); } @Test public void isLocal_returns_true_on_localhost_address_or_host() { try { InetAddress localHost = InetAddress.getLocalHost(); assertThat(underTest.isLocal(localHost.getHostAddress())).isTrue(); assertThat(underTest.isLocal(localHost.getHostName())).isTrue(); } catch (UnknownHostException e) { // ignore, host running the test has no localhost } } }
5,618
35.019231
97
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/PluginFileWriteRuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.FilePermission; import java.nio.file.Path; import java.nio.file.Paths; import java.util.PropertyPermission; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PluginFileWriteRuleTest { private final Path home = Paths.get("/path/to/home"); private final Path tmp = Paths.get("/path/to/home/tmp"); private final PluginFileWriteRule rule = new PluginFileWriteRule(home, tmp); @Test public void policy_restricts_modifying_home() { assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "write"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "execute"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "delete"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "read"))).isTrue(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "readlink"))).isTrue(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/extensions/file").toAbsolutePath().toString(), "write"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue(); } @Test public void policy_implies_other_permissions() { assertThat(rule.implies(new PropertyPermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue(); } }
2,479
45.792453
140
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/PluginSecurityManagerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.security.Permission; import java.security.Policy; import java.security.ProtectionDomain; import java.util.Arrays; import javax.management.MBeanPermission; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class PluginSecurityManagerTest { private final ClassLoader classRealm = mock(ClassLoader.class, RETURNS_DEEP_STUBS); private final ProtectionDomain pd = new ProtectionDomain(null, null, classRealm, null); private final Permission permission = mock(Permission.class); private final PluginPolicyRule rule1 = mock(PluginPolicyRule.class); private final PluginPolicyRule rule2 = mock(PluginPolicyRule.class); @Test public void constructor_dontSetAnyPolicy() { Policy policy = Policy.getPolicy(); new PluginSecurityManager(); assertThat(policy).isEqualTo(Policy.getPolicy()); } @Test public void protection_domain_can_have_no_classloader() { PluginSecurityManager.PluginPolicy policy = new PluginSecurityManager.PluginPolicy(Arrays.asList(rule1, rule2)); ProtectionDomain domain = new ProtectionDomain(null, null, null, null); Permission permission = new MBeanPermission("com.sun.management.internal.HotSpotThreadImpl", "getMBeanInfo"); assertThat(policy.implies(domain, permission)).isTrue(); verifyNoInteractions(rule1, rule2); } @Test public void policy_doesnt_restrict_other_classloaders() { PluginSecurityManager.PluginPolicy policy = new PluginSecurityManager.PluginPolicy(Arrays.asList(rule1, rule2)) { @Override String getDomainClassLoaderName(ProtectionDomain domain) { return "classloader"; } }; policy.implies(pd, permission); verifyNoInteractions(rule1, rule2); } @Test public void policy_restricts_class_realm_classloader() { when(rule1.implies(permission)).thenReturn(true); PluginSecurityManager.PluginPolicy policy = new PluginSecurityManager.PluginPolicy(Arrays.asList(rule1, rule2)) { @Override String getDomainClassLoaderName(ProtectionDomain domain) { return "org.sonar.classloader.ClassRealm"; } }; policy.implies(pd, permission); verify(rule1).implies(permission); verify(rule2).implies(permission); verifyNoMoreInteractions(rule1, rule2); } }
3,455
35.765957
117
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/ProcessEntryPointTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.mockito.ArgumentCaptor; import org.sonar.process.Lifecycle.State; import org.sonar.process.sharedmemoryfile.ProcessCommands; import org.sonar.process.test.StandardProcess; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.process.ProcessEntryPoint.PROPERTY_GRACEFUL_STOP_TIMEOUT_MS; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_KEY; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; public class ProcessEntryPointTest { private SystemExit exit = mock(SystemExit.class); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Rule public TemporaryFolder temp = new TemporaryFolder(); private ProcessCommands commands = new OperationalFlagOnlyProcessCommands(); private Runtime runtime; @Before public void setUp() { runtime = mock(Runtime.class); } @Test public void load_properties_from_file() throws Exception { File propsFile = temp.newFile(); FileUtils.write(propsFile, "sonar.foo=bar\nprocess.key=web\nprocess.index=1\nprocess.sharedDir=" + temp.newFolder().getAbsolutePath().replaceAll("\\\\", "/")); ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(new String[] {propsFile.getAbsolutePath()}); assertThat(entryPoint.getProps().value("sonar.foo")).isEqualTo("bar"); assertThat(entryPoint.getProps().value("process.key")).isEqualTo("web"); } @Test public void test_initial_state() throws Exception { Props props = createProps(); ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); assertThat(entryPoint.getProps()).isSameAs(props); } @Test public void fail_to_launch_multiple_times() throws IOException { Props props = createProps(); ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); entryPoint.launch(new NoopProcess()); try { entryPoint.launch(new NoopProcess()); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Already started"); } } @Test public void launch_then_request_graceful_stop() throws Exception { Props props = createProps(); final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); final StandardProcess process = new StandardProcess(); new Thread(() -> entryPoint.launch(process)).start(); waitForOperational(process, commands); // requests for graceful stop -> waits until down // Should terminate before the timeout of 30s entryPoint.stop(); assertThat(process.getState()).isEqualTo(State.STOPPED); assertThat(process.wasStopped()).isTrue(); assertThat(process.wasHardStopped()).isFalse(); } @Test public void launch_then_request_hard_stop() throws Exception { Props props = createProps(); final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); final StandardProcess process = new StandardProcess(); // starts and waits until terminated Thread runner = new Thread(() -> entryPoint.launch(process)); runner.start(); waitForOperational(process, commands); // requests for stop hardly waiting entryPoint.hardStop(); assertThat(process.getState()).isEqualTo(State.STOPPED); assertThat(process.wasHardStopped()).isTrue(); } @Test public void terminate_if_unexpected_shutdown() throws Exception { Props props = createProps(); final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); final StandardProcess process = new StandardProcess(); Thread runner = new Thread(() -> { // starts and waits until terminated entryPoint.launch(process); }); runner.start(); waitForOperational(process, commands); // emulate signal to shutdown process ArgumentCaptor<Thread> shutdownHookCaptor = ArgumentCaptor.forClass(Thread.class); verify(runtime).addShutdownHook(shutdownHookCaptor.capture()); shutdownHookCaptor.getValue().start(); while (process.getState() != State.STOPPED) { Thread.sleep(10L); } // exit before test timeout, ok ! } @Test public void terminate_if_startup_error() throws IOException { Props props = createProps(); final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime); final Monitored process = mock(Monitored.class); doThrow(IllegalStateException.class).when(process).start(); entryPoint.launch(process); } private static void waitForOperational(StandardProcess process, ProcessCommands commands) throws InterruptedException { while (!(process.getState() == State.STARTED && commands.isOperational())) { Thread.sleep(10L); } } private Props createProps() throws IOException { Props props = new Props(new Properties()); props.set(PROPERTY_SHARED_PATH, temp.newFolder().getAbsolutePath()); props.set(PROPERTY_PROCESS_INDEX, "1"); props.set(PROPERTY_PROCESS_KEY, ProcessId.COMPUTE_ENGINE.getKey()); props.set(PROPERTY_GRACEFUL_STOP_TIMEOUT_MS, "30000"); return props; } private static class NoopProcess implements Monitored { @Override public void start() { } @Override public Status getStatus() { return Status.OPERATIONAL; } @Override public void awaitStop() { } @Override public void stop() { } @Override public void hardStop() { } } private static class OperationalFlagOnlyProcessCommands implements ProcessCommands { private final AtomicBoolean operational = new AtomicBoolean(false); @Override public boolean isUp() { return false; } @Override public void setUp() { } @Override public boolean isOperational() { return operational.get(); } @Override public void setOperational() { operational.set(true); } @Override public void ping() { } @Override public long getLastPing() { return 0; } @Override public void setHttpUrl(String s) { } @Override public String getHttpUrl() { return null; } @Override public void askForStop() { } @Override public boolean askedForStop() { return false; } @Override public void askForHardStop() { } @Override public boolean askedForHardStop() { return false; } @Override public void askForRestart() { } @Override public boolean askedForRestart() { return false; } @Override public void acknowledgeAskForRestart() { } @Override public void endWatch() { } } }
8,226
26.51505
163
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/ProcessIdTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.util.HashSet; import java.util.Set; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProcessIdTest { @Test public void test_constants() { assertThat(ProcessId.COMPUTE_ENGINE.getKey()).isEqualTo("ce"); assertThat(ProcessId.COMPUTE_ENGINE.getIpcIndex()).isEqualTo(3); } @Test public void all_values_are_unique() { Set<Integer> ipcIndices = new HashSet<>(); Set<String> keys = new HashSet<>(); Set<String> humanReadableNames = new HashSet<>(); for (ProcessId processId : ProcessId.values()) { ipcIndices.add(processId.getIpcIndex()); keys.add(processId.getKey()); humanReadableNames.add(processId.getHumanReadableName()); } assertThat(ipcIndices).hasSize(ProcessId.values().length); assertThat(keys).hasSize(ProcessId.values().length); assertThat(humanReadableNames).hasSize(ProcessId.values().length); } @Test public void fromKey_searches_process_by_its_key() { assertThat(ProcessId.fromKey("app")).isEqualTo(ProcessId.APP); assertThat(ProcessId.fromKey("ce")).isEqualTo(ProcessId.COMPUTE_ENGINE); assertThat(ProcessId.fromKey("es")).isEqualTo(ProcessId.ELASTICSEARCH); assertThat(ProcessId.fromKey("web")).isEqualTo(ProcessId.WEB_SERVER); } @Test public void fromKey_throws_IAE_if_key_is_null() { assertThatThrownBy(() -> ProcessId.fromKey(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process [null] does not exist"); } @Test public void fromKey_throws_IAE_if_key_does_not_exist() { assertThatThrownBy(() -> ProcessId.fromKey("foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process [foo] does not exist"); } }
2,688
34.381579
76
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/ProcessPropertiesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.net.InetAddress; import java.util.Map; import java.util.Properties; import org.junit.Test; import org.sonar.core.extension.CoreExtension; import org.sonar.core.extension.ServiceLoaderWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.parseTimeoutMs; public class ProcessPropertiesTest { private final ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); private final ProcessProperties processProperties = new ProcessProperties(serviceLoaderWrapper); @Test public void completeDefaults_adds_default_values() { Props props = new Props(new Properties()); processProperties.completeDefaults(props); assertThat(props.value("sonar.search.javaOpts")).contains("-Xmx"); assertThat(props.valueAsInt("sonar.jdbc.maxActive")).isEqualTo(60); assertThat(props.valueAsBoolean("sonar.updatecenter.activate")).isTrue(); } @Test public void completeDefaults_does_not_override_existing_properties() { Properties p = new Properties(); p.setProperty("sonar.jdbc.username", "angela"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.value("sonar.jdbc.username")).isEqualTo("angela"); } @Test public void completeDefaults_sets_default_values_for_sonar_search_host_and_sonar_search_port_and_random_port_for_sonar_es_port_in_non_cluster_mode() throws Exception { Properties p = new Properties(); p.setProperty("sonar.cluster.enabled", "false"); Props props = new Props(p); processProperties.completeDefaults(props); String address = props.value("sonar.search.host"); assertThat(address).isNotEmpty(); assertThat(InetAddress.getByName(address).isLoopbackAddress()).isTrue(); assertThat(props.valueAsInt("sonar.search.port")).isEqualTo(9001); assertThat(props.valueAsInt("sonar.es.port")).isPositive(); } @Test public void completeDefaults_does_not_set_default_values_for_sonar_search_host_and_sonar_search_port_and_sonar_es_port_in_cluster_mode() { Properties p = new Properties(); p.setProperty("sonar.cluster.enabled", "true"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.contains("sonar.search.port")).isFalse(); assertThat(props.contains("sonar.search.port")).isFalse(); assertThat(props.contains("sonar.es.port")).isFalse(); } @Test public void completeDefaults_sets_the_http_port_of_elasticsearch_if_value_is_zero_in_standalone_mode() { Properties p = new Properties(); p.setProperty("sonar.search.port", "0"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.valueAsInt("sonar.search.port")).isPositive(); } @Test public void completeDefaults_does_not_fall_back_to_default_if_transport_port_of_elasticsearch_set_in_standalone_mode() { Properties p = new Properties(); p.setProperty("sonar.es.port", "9002"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.valueAsInt("sonar.es.port")).isEqualTo(9002); } @Test public void completeDefaults_does_not_set_the_http_port_of_elasticsearch_if_value_is_zero_in_search_node_in_cluster() { Properties p = new Properties(); p.setProperty("sonar.cluster.enabled", "true"); p.setProperty("sonar.search.port", "0"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.valueAsInt("sonar.search.port")).isZero(); } @Test public void completeDefaults_does_not_set_the_transport_port_of_elasticsearch_if_value_is_zero_in_search_node_in_cluster() { Properties p = new Properties(); p.setProperty("sonar.cluster.enabled", "true"); p.setProperty("sonar.es.port", "0"); Props props = new Props(p); processProperties.completeDefaults(props); assertThat(props.valueAsInt("sonar.es.port")).isZero(); } @Test public void defaults_loads_properties_defaults_from_base_and_extensions() { Props p = new Props(new Properties()); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of(new FakeExtension1(), new FakeExtension3())); processProperties.completeDefaults(p); assertThat(p.value("sonar.some.property")).isEqualTo("1"); assertThat(p.value("sonar.some.property2")).isEqualTo("455"); assertThat(p.value("sonar.some.property4")).isEqualTo("abc"); assertThat(p.value("sonar.some.property5")).isEqualTo("def"); assertThat(p.value("sonar.some.property5")).isEqualTo("def"); assertThat(p.value("sonar.search.port")).isEqualTo("9001"); } @Test public void defaults_throws_exception_on_same_property_defined_more_than_once_in_extensions() { Props p = new Props(new Properties()); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of(new FakeExtension1(), new FakeExtension2())); assertThatThrownBy(() -> processProperties.completeDefaults(p)) .isInstanceOf(IllegalStateException.class) .hasMessage("Configuration error: property definition named 'sonar.some.property2' found in multiple extensions."); } private static class FakeExtension1 implements CoreExtension { @Override public String getName() { return "fakeExt1"; } @Override public void load(Context context) { // do nothing } @Override public Map<String, String> getExtensionProperties() { return ImmutableMap.of( "sonar.some.property", "1", "sonar.some.property2", "455"); } } private static class FakeExtension2 implements CoreExtension { @Override public String getName() { return "fakeExt2"; } @Override public void load(Context context) { // do nothing } @Override public Map<String, String> getExtensionProperties() { return ImmutableMap.of( "sonar.some.property2", "5435", "sonar.some.property3", "32131"); } } private static class FakeExtension3 implements CoreExtension { @Override public String getName() { return "fakeExt3"; } @Override public void load(Context context) { // do nothing } @Override public Map<String, String> getExtensionProperties() { return ImmutableMap.of( "sonar.some.property4", "abc", "sonar.some.property5", "def"); } } @Test public void parseTimeoutMs_throws_NumberFormat_exception_if_value_is_not_long() { assertThatThrownBy(() -> parseTimeoutMs(ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT, "tru")) .isInstanceOf(NumberFormatException.class); } @Test public void parseTimeoutMs_returns_long_from_value() { long expected = 5_999_664; long res = parseTimeoutMs(ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT, expected + ""); assertThat(res).isEqualTo(expected); } @Test public void parseTimeoutMs_throws_ISE_if_value_is_0() { assertThatThrownBy(() -> parseTimeoutMs(ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT, 0 + "")) .isInstanceOf(IllegalStateException.class) .hasMessage("value of WEB_GRACEFUL_STOP_TIMEOUT must be >= 1"); } @Test public void parseTimeoutMs_throws_ISE_if_value_is_less_than_0() { int timeoutValue = -5_999_664; assertThatThrownBy(() -> parseTimeoutMs(ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT, timeoutValue + "")) .isInstanceOf(IllegalStateException.class) .hasMessage("value of WEB_GRACEFUL_STOP_TIMEOUT must be >= 1"); } }
8,674
33.288538
169
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.util.Properties; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @RunWith(DataProviderRunner.class) public class PropsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test @UseDataProvider("beforeAndAfterBlanks") public void constructor_trims_key_and_values_from_Properties_argument(String blankBefore, String blankAfter) { Properties properties = new Properties(); String key = RandomStringUtils.randomAlphanumeric(3); String value = RandomStringUtils.randomAlphanumeric(3); properties.put(blankBefore + key + blankAfter, blankBefore + value + blankAfter); Props underTest = new Props(properties); if (!blankBefore.isEmpty() || !blankAfter.isEmpty()) { assertThat(underTest.contains(blankBefore + key + blankAfter)).isFalse(); } assertThat(underTest.value(key)).isEqualTo(value); } @Test @UseDataProvider("beforeAndAfterBlanks") public void value(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty(blankBefore + "foo" + blankAfter, blankBefore + "bar" + blankAfter); p.setProperty("blank", blankBefore + blankAfter); Props props = new Props(p); assertThat(props.value("foo")).isEqualTo("bar"); assertThat(props.value("foo", "default value")).isEqualTo("bar"); assertThat(props.value("blank")).isEmpty(); assertThat(props.value("blank", "default value")).isEmpty(); assertThat(props.value("unknown")).isNull(); assertThat(props.value("unknown", "default value")).isEqualTo("default value"); } @Test @UseDataProvider("beforeAndAfterBlanks") public void nonNullValue(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty("foo", blankBefore + "bar" + blankAfter); Props props = new Props(p); assertThat(props.nonNullValue("foo")).isEqualTo("bar"); } @Test public void nonNullValue_throws_IAE_on_non_existing_key() { Props props = new Props(new Properties()); assertThatThrownBy(() -> props.nonNullValue("other")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property: other"); } @Test @UseDataProvider("beforeAndAfterBlanks") public void nonNullValue_return_empty_string_IAE_on_existing_key_with_blank_value(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty("blank", blankBefore + blankAfter); Props props = new Props(p); assertThat(props.nonNullValue("blank")).isEmpty(); } @Test @UseDataProvider("beforeAndAfterBlanks") public void valueAsInt(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty("foo", blankBefore + "33" + blankAfter); p.setProperty("blank", blankBefore + blankAfter); Props props = new Props(p); assertThat(props.valueAsInt("foo")).isEqualTo(33); assertThat(props.valueAsInt("foo", 44)).isEqualTo(33); assertThat(props.valueAsInt("blank")).isNull(); assertThat(props.valueAsInt("blank", 55)).isEqualTo(55); assertThat(props.valueAsInt("unknown")).isNull(); assertThat(props.valueAsInt("unknown", 44)).isEqualTo(44); } @Test @UseDataProvider("beforeAndAfterBlanks") public void valueAsInt_not_integer(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty("foo", blankBefore + "bar" + blankAfter); Props props = new Props(p); try { props.valueAsInt("foo"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Value of property foo is not an integer: bar"); } } @Test @UseDataProvider("beforeAndAfterBlanks") public void booleanOf(String blankBefore, String blankAfter) { Properties p = new Properties(); p.setProperty("foo", blankBefore + "True" + blankAfter); p.setProperty("bar", blankBefore + "false" + blankAfter); Props props = new Props(p); assertThat(props.valueAsBoolean("foo")).isTrue(); assertThat(props.valueAsBoolean("bar")).isFalse(); assertThat(props.valueAsBoolean("foo", false)).isTrue(); assertThat(props.valueAsBoolean("bar", true)).isFalse(); assertThat(props.valueAsBoolean("unknown")).isFalse(); assertThat(props.valueAsBoolean("unset", false)).isFalse(); assertThat(props.valueAsBoolean("unset", true)).isTrue(); } @Test public void setDefault() { Properties p = new Properties(); p.setProperty("foo", "foo_value"); Props props = new Props(p); props.setDefault("foo", "foo_def"); props.setDefault("bar", "bar_def"); assertThat(props.value("foo")).isEqualTo("foo_value"); assertThat(props.value("bar")).isEqualTo("bar_def"); assertThat(props.value("other")).isNull(); } @Test public void set() { Properties p = new Properties(); p.setProperty("foo", "old_foo"); Props props = new Props(p); props.set("foo", "new_foo"); props.set("bar", "new_bar"); assertThat(props.value("foo")).isEqualTo("new_foo"); assertThat(props.value("bar")).isEqualTo("new_bar"); } @Test public void raw_properties() { Properties p = new Properties(); p.setProperty("encrypted_prop", "{aes}abcde"); p.setProperty("clear_prop", "foo"); Props props = new Props(p); assertThat(props.rawProperties()).hasSize(2); // do not decrypt assertThat(props.rawProperties()).containsEntry("encrypted_prop", "{aes}abcde"); assertThat(props.rawProperties()).containsEntry("clear_prop", "foo"); } @Test public void nonNullValueAsFile() throws IOException { File file = temp.newFile(); Props props = new Props(new Properties()); props.set("path", file.getAbsolutePath()); assertThat(props.nonNullValueAsFile("path")).isEqualTo(file); try { props.nonNullValueAsFile("other_path"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Property other_path is not set"); } } @DataProvider public static Object[][] beforeAndAfterBlanks() { return new Object[][] { {"", ""}, {" ", ""}, {"", " "}, {" ", " "}, }; } }
7,505
33.589862
124
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/StopWatcherTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class StopWatcherTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Test public void stop_if_receive_command() throws Exception { ProcessCommands commands = mock(ProcessCommands.class); when(commands.askedForHardStop()).thenReturn(false, true); Stoppable stoppable = mock(Stoppable.class); StopWatcher underTest = new StopWatcher("TheThreadName", stoppable::hardStopAsync, commands::askedForHardStop, 1L); underTest.start(); while (underTest.isAlive()) { Thread.sleep(1L); } verify(stoppable).hardStopAsync(); assertThat(underTest.getName()).isEqualTo("TheThreadName"); } @Test public void stop_watching_on_interruption() throws Exception { ProcessCommands commands = mock(ProcessCommands.class); when(commands.askedForHardStop()).thenReturn(false); Stoppable stoppable = mock(Stoppable.class); StopWatcher underTest = new StopWatcher("TheThreadName", stoppable::hardStopAsync, commands::askedForHardStop, 1L); underTest.start(); underTest.interrupt(); while (underTest.isAlive()) { Thread.sleep(1L); } verify(stoppable, never()).hardStopAsync(); assertThat(underTest.getName()).isEqualTo("TheThreadName"); } }
2,572
33.77027
119
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/SystemExitTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SystemExitTest { @Test public void do_not_exit_if_in_shutdown_hook() { SystemExit systemExit = new SystemExit(); systemExit.setInShutdownHook(); assertThat(systemExit.isInShutdownHook()).isTrue(); systemExit.exit(0); // still there } @Test public void exit_if_not_in_shutdown_hook() { final AtomicInteger got = new AtomicInteger(); SystemExit systemExit = new SystemExit() { @Override void doExit(int code) { got.set(code); } }; assertThat(systemExit.isInShutdownHook()).isFalse(); systemExit.exit(1); assertThat(got.get()).isOne(); } }
1,642
28.339286
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/TestLogbackAppender.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.ArrayList; import java.util.List; public class TestLogbackAppender extends AppenderBase<LoggingEvent> { static List<LoggingEvent> events = new ArrayList<>(); @Override protected void append(LoggingEvent e) { events.add(e); } }
1,219
32.888889
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/NodeTypeTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NodeTypeTest { @Test public void test_parse() { assertThat(NodeType.parse("application")).isEqualTo(NodeType.APPLICATION); assertThat(NodeType.parse("search")).isEqualTo(NodeType.SEARCH); } @Test public void parse_an_unknown_value_must_throw_IAE() { assertThatThrownBy(() -> NodeType.parse("XYZ")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid value: XYZ"); } }
1,463
33.046512
78
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/health/HealthStateRefresherTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.hazelcast.core.HazelcastInstanceNotActiveException; import java.util.Random; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.process.LoggingRule; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.DEBUG; import static org.slf4j.event.Level.ERROR; public class HealthStateRefresherTest { @Rule public LoggingRule logging = new LoggingRule(HealthStateRefresher.class); private Random random = new Random(); private NodeDetailsTestSupport testSupport = new NodeDetailsTestSupport(random); private HealthStateRefresherExecutorService executorService = mock(HealthStateRefresherExecutorService.class); private NodeHealthProvider nodeHealthProvider = mock(NodeHealthProvider.class); private SharedHealthState sharedHealthState = mock(SharedHealthState.class); private HealthStateRefresher underTest = new HealthStateRefresher(executorService, nodeHealthProvider, sharedHealthState); @Test public void start_adds_runnable_with_10_second_delay_and_initial_delay_putting_NodeHealth_from_provider_into_SharedHealthState() { ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); NodeHealth[] nodeHealths = { testSupport.randomNodeHealth(), testSupport.randomNodeHealth(), testSupport.randomNodeHealth() }; Error expected = new Error("Simulating exception raised by NodeHealthProvider"); when(nodeHealthProvider.get()) .thenReturn(nodeHealths[0]) .thenReturn(nodeHealths[1]) .thenReturn(nodeHealths[2]) .thenThrow(expected); underTest.start(); verify(executorService).scheduleWithFixedDelay(runnableCaptor.capture(), eq(1L), eq(10L), eq(TimeUnit.SECONDS)); Runnable runnable = runnableCaptor.getValue(); runnable.run(); runnable.run(); runnable.run(); verify(sharedHealthState).writeMine(nodeHealths[0]); verify(sharedHealthState).writeMine(nodeHealths[1]); verify(sharedHealthState).writeMine(nodeHealths[2]); try { runnable.run(); } catch (IllegalStateException e) { fail("Runnable should catch any Throwable"); } } @Test public void stop_has_no_effect() { underTest.stop(); verify(sharedHealthState).clearMine(); verifyNoInteractions(executorService, nodeHealthProvider); } @Test public void do_not_log_errors_when_hazelcast_is_not_active() { logging.setLevel(DEBUG); doThrow(new HazelcastInstanceNotActiveException()).when(sharedHealthState).writeMine(any()); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); underTest.start(); verify(executorService).scheduleWithFixedDelay(runnableCaptor.capture(), eq(1L), eq(10L), eq(TimeUnit.SECONDS)); Runnable runnable = runnableCaptor.getValue(); runnable.run(); assertThat(logging.getLogs(ERROR)).isEmpty(); assertThat(logging.hasLog(DEBUG, "Hazelcast is no more active")).isTrue(); } }
4,300
37.061947
132
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Random; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; public class NodeDetailsTest { private Random random = new Random(); private NodeDetailsTestSupport testSupport = new NodeDetailsTestSupport(random); private NodeDetails.Type randomType = testSupport.randomType(); private NodeDetails.Builder builderUnderTest = newNodeDetailsBuilder(); @Test public void setType_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> builderUnderTest.setType(null)) .isInstanceOf(NullPointerException.class) .hasMessage("type can't be null"); } @Test public void setName_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> builderUnderTest.setName(null)) .isInstanceOf(NullPointerException.class) .hasMessage("name can't be null"); } @Test public void setName_throws_IAE_if_arg_is_empty() { assertThatThrownBy(() -> builderUnderTest.setName("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("name can't be empty"); } @Test public void setName_throws_IAE_if_arg_is_empty_after_trim() { assertThatThrownBy(() -> builderUnderTest.setName(" ")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("name can't be empty"); } @Test public void setHost_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> builderUnderTest.setHost(null)) .isInstanceOf(NullPointerException.class) .hasMessage("host can't be null"); } @Test public void setHost_throws_IAE_if_arg_is_empty() { assertThatThrownBy(() -> builderUnderTest.setHost("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("host can't be empty"); } @Test public void setHost_throws_IAE_if_arg_is_empty_after_trim() { assertThatThrownBy(() -> builderUnderTest.setHost(" ")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("host can't be empty"); } @Test public void setPort_throws_IAE_if_arg_is_less_than_1() { assertThatThrownBy(() -> builderUnderTest.setPort(-random.nextInt(5))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("port must be > 0"); } @Test public void setStarted_throws_IAE_if_arg_is_less_than_1() { assertThatThrownBy(() -> builderUnderTest.setStartedAt(-random.nextInt(5))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("startedAt must be > 0"); } @Test public void build_throws_NPE_if_type_is_null() { assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) .hasMessage("type can't be null"); } @Test public void build_throws_NPE_if_name_is_null() { builderUnderTest .setType(randomType); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) .hasMessage("name can't be null"); } @Test public void build_throws_NPE_if_host_is_null() { builderUnderTest .setType(randomType) .setName(randomAlphanumeric(2)); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) .hasMessage("host can't be null"); } @Test public void build_throws_IAE_if_setPort_not_called() { builderUnderTest .setType(randomType) .setName(randomAlphanumeric(2)) .setHost(randomAlphanumeric(3)); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("port must be > 0"); } @Test public void build_throws_IAE_if_setStarted_not_called() { builderUnderTest .setType(randomType) .setName(randomAlphanumeric(2)) .setHost(randomAlphanumeric(3)) .setPort(1 + random.nextInt(33)); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("startedAt must be > 0"); } @Test public void equals_is_based_on_content() { NodeDetails.Builder builder = testSupport.randomNodeDetailsBuilder(); NodeDetails underTest = builder.build(); assertThat(underTest).isEqualTo(underTest); assertThat(builder.build()) .isEqualTo(underTest) .isNotSameAs(underTest); assertThat(underTest) .isNotNull() .isNotEqualTo(new Object()); } @Test public void hashcode_is_based_on_content() { NodeDetails.Builder builder = testSupport.randomNodeDetailsBuilder(); NodeDetails underTest = builder.build(); assertThat(builder.build().hashCode()) .isEqualTo(underTest.hashCode()); } @Test public void NodeDetails_is_Externalizable() throws IOException, ClassNotFoundException { NodeDetails source = testSupport.randomNodeDetails(); byte[] byteArray = NodeDetailsTestSupport.serialize(source); NodeDetails underTest = (NodeDetails) new ObjectInputStream(new ByteArrayInputStream(byteArray)).readObject(); assertThat(underTest).isEqualTo(source); } @Test public void verify_toString() { String name = randomAlphanumeric(3); String host = randomAlphanumeric(10); int port = 1 + random.nextInt(10); long startedAt = 1 + random.nextInt(666); NodeDetails underTest = builderUnderTest .setType(randomType) .setName(name) .setHost(host) .setPort(port) .setStartedAt(startedAt) .build(); assertThat(underTest.toString()) .isEqualTo("NodeDetails{type=" + randomType + ", name='" + name + "', host='" + host + "', port=" + port + ", startedAt=" + startedAt + "}"); } @Test public void verify_getters() { String name = randomAlphanumeric(3); String host = randomAlphanumeric(10); int port = 1 + random.nextInt(10); long startedAt = 1 + random.nextInt(666); NodeDetails underTest = builderUnderTest .setType(randomType) .setName(name) .setHost(host) .setPort(port) .setStartedAt(startedAt) .build(); assertThat(underTest.getType()).isEqualTo(randomType); assertThat(underTest.getName()).isEqualTo(name); assertThat(underTest.getHost()).isEqualTo(host); assertThat(underTest.getPort()).isEqualTo(port); assertThat(underTest.getStartedAt()).isEqualTo(startedAt); } }
7,457
31.146552
147
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTestSupport.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Random; import java.util.stream.IntStream; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class NodeDetailsTestSupport { private final Random random; public NodeDetailsTestSupport() { this(new Random()); } NodeDetailsTestSupport(Random random) { this.random = random; } NodeHealth.Status randomStatus() { return NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]; } NodeHealth randomNodeHealth() { return randomBuilder().build(); } NodeHealth.Builder randomBuilder() { return randomBuilder(0); } NodeHealth.Builder randomBuilder(int minCauseCount) { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(randomStatus()) .setDetails(randomNodeDetails()); IntStream.range(0, minCauseCount + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).forEach(builder::addCause); return builder; } NodeDetails randomNodeDetails() { return randomNodeDetailsBuilder() .build(); } NodeDetails.Builder randomNodeDetailsBuilder() { return newNodeDetailsBuilder() .setType(randomType()) .setName(randomAlphanumeric(3)) .setHost(randomAlphanumeric(10)) .setPort(1 + random.nextInt(10)) .setStartedAt(1 + random.nextInt(666)); } NodeDetails.Type randomType() { return NodeDetails.Type.values()[random.nextInt(NodeDetails.Type.values().length)]; } static byte[] serialize(Object source) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(out)) { objectOutputStream.writeObject(source); } return out.toByteArray(); } }
2,903
31.629213
122
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class NodeHealthTest { private Random random = new Random(); private NodeDetailsTestSupport testSupport = new NodeDetailsTestSupport(random); private NodeHealth.Status randomStatus = testSupport.randomStatus(); private NodeHealth.Builder builderUnderTest = newNodeHealthBuilder(); @Test public void setStatus_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> builderUnderTest.setStatus(null)) .isInstanceOf(NullPointerException.class) .hasMessage("status can't be null"); } @Test public void setDetails_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> builderUnderTest.setDetails(null)) .isInstanceOf(NullPointerException.class) .hasMessage("details can't be null"); } @Test public void build_throws_NPE_if_status_is_null() { assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) .hasMessage("status can't be null"); } @Test public void build_throws_NPE_if_details_is_null() { builderUnderTest.setStatus(randomStatus); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) .hasMessage("details can't be null"); } @Test public void clearClauses_clears_clauses_of_builder() { NodeHealth.Builder underTest = testSupport.randomBuilder(); NodeHealth original = underTest .addCause(randomAlphanumeric(3)) .build(); underTest.clearCauses(); NodeHealth second = underTest.build(); assertThat(second.getStatus()).isEqualTo(original.getStatus()); assertThat(second.getDetails()).isEqualTo(original.getDetails()); assertThat(second.getCauses()).isEmpty(); } @Test public void builder_can_be_reused() { NodeHealth.Builder builder = testSupport.randomBuilder(1); NodeHealth original = builder.build(); NodeHealth second = builder.build(); NodeHealth.Status newRandomStatus = NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]; NodeDetails newNodeDetails = testSupport.randomNodeDetails(); builder .clearCauses() .setStatus(newRandomStatus) .setDetails(newNodeDetails); String[] newCauses = IntStream.range(0, 1 + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); Arrays.stream(newCauses).forEach(builder::addCause); NodeHealth newNodeHealth = builder.build(); assertThat(second).isEqualTo(original); assertThat(newNodeHealth.getStatus()).isEqualTo(newRandomStatus); assertThat(newNodeHealth.getDetails()).isEqualTo(newNodeDetails); assertThat(newNodeHealth.getCauses()).containsOnly(newCauses); } @Test public void equals_is_based_on_content() { NodeHealth.Builder builder = testSupport.randomBuilder(); NodeHealth underTest = builder.build(); assertThat(underTest).isEqualTo(underTest); assertThat(builder.build()) .isEqualTo(underTest) .isNotSameAs(underTest); assertThat(underTest) .isNotNull() .isNotEqualTo(new Object()); } @Test public void hashcode_is_based_on_content() { NodeHealth.Builder builder = testSupport.randomBuilder(); NodeHealth underTest = builder.build(); assertThat(builder.build().hashCode()) .isEqualTo(underTest.hashCode()); } @Test public void class_is_serializable_with_causes() throws IOException, ClassNotFoundException { NodeHealth source = testSupport.randomBuilder(1).build(); byte[] bytes = NodeDetailsTestSupport.serialize(source); NodeHealth underTest = (NodeHealth) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); assertThat(underTest).isEqualTo(source); } @Test public void class_is_serializable_without_causes() throws IOException, ClassNotFoundException { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(randomStatus) .setDetails(testSupport.randomNodeDetails()); NodeHealth source = builder.build(); byte[] bytes = NodeDetailsTestSupport.serialize(source); NodeHealth underTest = (NodeHealth) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); assertThat(underTest).isEqualTo(source); } @Test public void verify_toString() { NodeDetails nodeDetails = testSupport.randomNodeDetails(); String cause = randomAlphanumeric(4); NodeHealth.Builder builder = builderUnderTest .setStatus(randomStatus) .setDetails(nodeDetails) .addCause(cause); NodeHealth underTest = builder.build(); assertThat(underTest.toString()) .isEqualTo("NodeHealth{status=" + randomStatus + ", causes=[" + cause + "], details=" + nodeDetails + "}"); } @Test public void verify_getters() { NodeDetails nodeDetails = testSupport.randomNodeDetails(); NodeHealth.Builder builder = builderUnderTest .setStatus(randomStatus) .setDetails(nodeDetails); String[] causes = IntStream.range(0, random.nextInt(10)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); Arrays.stream(causes).forEach(builder::addCause); NodeHealth underTest = builder.build(); assertThat(underTest.getStatus()).isEqualTo(randomStatus); assertThat(underTest.getDetails()).isEqualTo(nodeDetails); assertThat(underTest.getCauses()).containsOnly(causes); } }
6,696
34.247368
127
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.process.LoggingRule; import org.sonar.process.cluster.hz.HazelcastMember; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class SharedHealthStateImplTest { private static final String MAP_SQ_HEALTH_STATE = "sq_health_state"; @Rule public LoggingRule logging = new LoggingRule(SharedHealthStateImpl.class); private final Random random = new Random(); private long clusterTime = 99 + Math.abs(random.nextInt(9621)); private HazelcastMember hazelcastMember = mock(HazelcastMember.class); private SharedHealthStateImpl underTest = new SharedHealthStateImpl(hazelcastMember); @Test public void write_fails_with_NPE_if_arg_is_null() { assertThatThrownBy(() -> underTest.writeMine(null)) .isInstanceOf(NullPointerException.class) .hasMessage("nodeHealth can't be null"); } @Test public void write_put_arg_into_map_sq_health_state_under_current_client_uuid() { NodeHealth nodeHealth = randomNodeHealth(); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); long clusterTime = random.nextLong(); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(uuid); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); underTest.writeMine(nodeHealth); assertThat(map).hasSize(1); assertThat(map.get(uuid)).isEqualTo(new TimestampedNodeHealth(nodeHealth, clusterTime)); assertThat(logging.getLogs()).isEmpty(); } @Test public void write_logs_map_sq_health_state_content_and_NodeHealth_to_be_added_if_TRACE() { logging.setLevel(Level.TRACE); NodeHealth newNodeHealth = randomNodeHealth(); Map<String, TimestampedNodeHealth> map = new HashMap<>(); map.put(randomAlphanumeric(4), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong())); doReturn(new HashMap<>(map)).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(uuid); underTest.writeMine(newNodeHealth); assertThat(logging.getLogs()).hasSize(1); assertThat(logging.hasLog(Level.TRACE, "Reading " + map + " and adding " + newNodeHealth)).isTrue(); } @Test public void readAll_returns_all_NodeHealth_in_map_sq_health_state_for_existing_client_uuids_aged_less_than_30_seconds() { NodeHealth[] nodeHealths = IntStream.range(0, 1 + random.nextInt(6)).mapToObj(i -> randomNodeHealth()).toArray(NodeHealth[]::new); Map<UUID, TimestampedNodeHealth> allNodeHealths = new HashMap<>(); Map<UUID, NodeHealth> expected = new HashMap<>(); for (NodeHealth nodeHealth : nodeHealths) { UUID memberUuid = UUID.randomUUID(); TimestampedNodeHealth timestampedNodeHealth = new TimestampedNodeHealth(nodeHealth, clusterTime - random.nextInt(30 * 1000)); allNodeHealths.put(memberUuid, timestampedNodeHealth); if (random.nextBoolean()) { expected.put(memberUuid, nodeHealth); } } doReturn(allNodeHealths).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); when(hazelcastMember.getMemberUuids()).thenReturn(expected.keySet()); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); assertThat(underTest.readAll()) .containsOnly(expected.values().toArray(new NodeHealth[0])); assertThat(logging.getLogs()).isEmpty(); } @Test public void readAll_ignores_NodeHealth_of_30_seconds_before_cluster_time() { NodeHealth nodeHealth = randomNodeHealth(); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); UUID memberUuid = UUID.randomUUID(); TimestampedNodeHealth timestampedNodeHealth = new TimestampedNodeHealth(nodeHealth, clusterTime - 30 * 1000); map.put(memberUuid, timestampedNodeHealth); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); when(hazelcastMember.getMemberUuids()).thenReturn(map.keySet()); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); assertThat(underTest.readAll()).isEmpty(); } @Test public void readAll_ignores_NodeHealth_of_more_than_30_seconds_before_cluster_time() { NodeHealth nodeHealth = randomNodeHealth(); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); UUID memberUuid = UUID.randomUUID(); TimestampedNodeHealth timestampedNodeHealth = new TimestampedNodeHealth(nodeHealth, clusterTime - 30 * 1000 - random.nextInt(99)); map.put(memberUuid, timestampedNodeHealth); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); when(hazelcastMember.getMemberUuids()).thenReturn(map.keySet()); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); assertThat(underTest.readAll()).isEmpty(); } @Test public void readAll_logs_map_sq_health_state_content_and_the_content_effectively_returned_if_TRACE() { logging.setLevel(Level.TRACE); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); UUID uuid = UUID.randomUUID(); NodeHealth nodeHealth = randomNodeHealth(); map.put(uuid, new TimestampedNodeHealth(nodeHealth, clusterTime - 1)); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); when(hazelcastMember.getMemberUuids()).thenReturn(singleton(uuid)); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); underTest.readAll(); assertThat(logging.getLogs()).hasSize(1); assertThat(logging.hasLog(Level.TRACE, "Reading " + new HashMap<>(map) + " and keeping " + singleton(nodeHealth))).isTrue(); } @Test public void readAll_logs_message_for_each_non_existing_member_ignored_if_TRACE() { logging.setLevel(Level.TRACE); Map<String, TimestampedNodeHealth> map = new HashMap<>(); String memberUuid1 = randomAlphanumeric(44); String memberUuid2 = randomAlphanumeric(44); map.put(memberUuid1, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1)); map.put(memberUuid2, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1)); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); underTest.readAll(); assertThat(logging.getLogs()).hasSize(3); assertThat(logging.getLogs(Level.TRACE)) .containsOnly( "Reading " + new HashMap<>(map) + " and keeping []", "Ignoring NodeHealth of member " + memberUuid1 + " because it is not part of the cluster at the moment", "Ignoring NodeHealth of member " + memberUuid2 + " because it is not part of the cluster at the moment"); } @Test public void readAll_logs_message_for_each_timed_out_NodeHealth_ignored_if_TRACE() { logging.setLevel(Level.TRACE); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); UUID memberUuid1 = UUID.randomUUID(); UUID memberUuid2 = UUID.randomUUID(); map.put(memberUuid1, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 30 * 1000)); map.put(memberUuid2, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 30 * 1000)); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); when(hazelcastMember.getMemberUuids()).thenReturn(ImmutableSet.of(memberUuid1, memberUuid2)); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); underTest.readAll(); assertThat(logging.getLogs()).hasSize(3); assertThat(logging.getLogs(Level.TRACE)) .containsOnly( "Reading " + new HashMap<>(map) + " and keeping []", "Ignoring NodeHealth of member " + memberUuid1 + " because it is too old", "Ignoring NodeHealth of member " + memberUuid2 + " because it is too old"); } @Test public void clearMine_clears_entry_into_map_sq_health_state_under_current_client_uuid() { Map<UUID, TimestampedNodeHealth> map = mock(Map.class); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(uuid); underTest.clearMine(); verify(map).remove(uuid); verifyNoMoreInteractions(map); assertThat(logging.getLogs()).isEmpty(); } @Test public void clearMine_logs_map_sq_health_state_and_current_client_uuid_if_TRACE() { logging.setLevel(Level.TRACE); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); map.put(UUID.randomUUID(), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong())); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(uuid); underTest.clearMine(); assertThat(logging.getLogs()).hasSize(1); assertThat(logging.hasLog(Level.TRACE, "Reading " + map + " and clearing for " + uuid)).isTrue(); } private NodeHealth randomNodeHealth() { return newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]) .setDetails(newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION) .setName(randomAlphanumeric(30)) .setHost(randomAlphanumeric(10)) .setPort(1 + random.nextInt(666)) .setStartedAt(1 + random.nextInt(852)) .build()) .build(); } }
11,058
43.413655
134
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/DistributedAnswerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import java.io.IOException; import java.util.UUID; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.NODE_NAME; public class DistributedAnswerTest { private final Member member = newMember(UUID.randomUUID()); private final DistributedAnswer<String> underTest = new DistributedAnswer<>(); @Test public void getMembers_return_all_members() { underTest.setAnswer(member, "foo"); underTest.setTimedOut(newMember(UUID.randomUUID())); underTest.setFailed(newMember(UUID.randomUUID()), new IOException("BOOM")); assertThat(underTest.getMembers()).hasSize(3); } @Test public void test_call_with_unknown_member() { assertThat(underTest.getAnswer(member)).isEmpty(); assertThat(underTest.hasTimedOut(member)).isFalse(); assertThat(underTest.getFailed(member)).isEmpty(); } @Test public void test_setAnswer() { underTest.setAnswer(member, "foo"); assertThat(underTest.getAnswer(member)).hasValue("foo"); assertThat(underTest.hasTimedOut(member)).isFalse(); assertThat(underTest.getFailed(member)).isEmpty(); } @Test public void test_setTimedOut() { underTest.setTimedOut(member); assertThat(underTest.getAnswer(member)).isEmpty(); assertThat(underTest.hasTimedOut(member)).isTrue(); assertThat(underTest.getFailed(member)).isEmpty(); } @Test public void test_setFailed() { IOException e = new IOException(); underTest.setFailed(member, e); assertThat(underTest.getAnswer(member)).isEmpty(); assertThat(underTest.hasTimedOut(member)).isFalse(); assertThat(underTest.getFailed(member)).hasValue(e); } @Test public void member_can_be_referenced_multiple_times() { underTest.setTimedOut(member); underTest.setAnswer(member, "foo"); IOException exception = new IOException(); underTest.setFailed(member, exception); assertThat(underTest.hasTimedOut(member)).isTrue(); assertThat(underTest.getAnswer(member)).hasValue("foo"); assertThat(underTest.getFailed(member)).hasValue(exception); } @Test public void propagateExceptions_does_nothing_if_no_members() { // no errors underTest.propagateExceptions(); } @Test public void propagateExceptions_does_nothing_if_no_errors() { underTest.setAnswer(newMember(UUID.randomUUID()), "bar"); // no errors underTest.propagateExceptions(); } @Test public void propagateExceptions_throws_ISE_if_at_least_one_timeout() { UUID uuid = UUID.randomUUID(); UUID otherUuid = UUID.randomUUID(); underTest.setAnswer(newMember(uuid), "baz"); underTest.setTimedOut(newMember(otherUuid)); assertThatThrownBy(underTest::propagateExceptions) .isInstanceOf(IllegalStateException.class) .hasMessage("Distributed cluster action timed out in cluster nodes " + otherUuid); } @Test public void propagateExceptions_throws_ISE_if_at_least_one_failure() { UUID foo = UUID.randomUUID(); UUID bar = UUID.randomUUID(); underTest.setAnswer(newMember(bar), "baz"); underTest.setFailed(newMember(foo), new IOException("BOOM")); assertThatThrownBy(underTest::propagateExceptions) .isInstanceOf(IllegalStateException.class) .hasMessage("Distributed cluster action in cluster nodes " + foo + " (other nodes may have timed out)"); } private static Member newMember(UUID uuid) { Member member = mock(Member.class); when(member.getUuid()).thenReturn(uuid); when(member.getAttribute(NODE_NAME.getKey())).thenReturn(uuid.toString()); return member; } }
4,702
32.119718
110
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/FailedDistributedCall.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; public class FailedDistributedCall implements DistributedCall<Long> { static final AtomicLong COUNTER = new AtomicLong(); @Override public Long call() throws Exception { long value = COUNTER.getAndIncrement(); if (value == 1L) { // only the second call fails throw new IOException("BOOM"); } return value; } }
1,305
33.368421
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberBuilderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import java.net.InetAddress; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class HazelcastMemberBuilderTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); // use loopback for support of offline builds private final InetAddress loopback = InetAddress.getLoopbackAddress(); @Test public void build_tcp_ip_member_hostaddress() { HazelcastMember member = new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP) .setMembers(loopback.getHostAddress()) .setProcessId(ProcessId.COMPUTE_ENGINE) .setNodeName("bar") .setPort(NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort()) .setNetworkInterface(loopback.getHostAddress()) .build(); assertThat(member.getUuid()).isNotNull(); assertThat(member.getClusterTime()).isPositive(); assertThat(member.getCluster().getMembers()).hasSize(1); assertThat(member.getMemberUuids()).containsOnlyOnce(member.getUuid()); assertThat(member.getAtomicReference("baz")).isNotNull(); assertThat(member.getLock("baz")).isNotNull(); assertThat(member.getReplicatedMap("baz")).isNotNull(); member.close(); } @Test public void build_tcp_ip_member_hostname() { HazelcastMember member = new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP) .setMembers(loopback.getHostName()) .setProcessId(ProcessId.COMPUTE_ENGINE) .setNodeName("bar") .setPort(NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort()) .setNetworkInterface(loopback.getHostAddress()) .build(); assertThat(member.getUuid()).isNotNull(); assertThat(member.getClusterTime()).isPositive(); assertThat(member.getCluster().getMembers()).hasSize(1); assertThat(member.getMemberUuids()).containsOnlyOnce(member.getUuid()); assertThat(member.getAtomicReference("baz")).isNotNull(); assertThat(member.getLock("baz")).isNotNull(); assertThat(member.getReplicatedMap("baz")).isNotNull(); member.close(); } @Test public void build_kubernetes_member() { HazelcastMember member = new HazelcastMemberBuilder(JoinConfigurationType.KUBERNETES) .setMembers(loopback.getHostAddress()) .setProcessId(ProcessId.COMPUTE_ENGINE) .setNodeName("bar") .setPort(NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort()) .setNetworkInterface(loopback.getHostAddress()) .build(); assertThat(member.getUuid()).isNotNull(); assertThat(member.getClusterTime()).isPositive(); assertThat(member.getCluster().getMembers()).hasSize(1); assertThat(member.getMemberUuids()).containsOnlyOnce(member.getUuid()); assertThat(member.getAtomicReference("baz")).isNotNull(); assertThat(member.getLock("baz")).isNotNull(); assertThat(member.getReplicatedMap("baz")).isNotNull(); member.close(); } @Test public void fail_if_elasticsearch_process() { var builder = new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP); assertThatThrownBy(() -> builder.setProcessId(ProcessId.ELASTICSEARCH)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Hazelcast must not be enabled on Elasticsearch node"); } }
4,386
36.818966
89
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.memberselector.MemberSelectors; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; public class HazelcastMemberImplTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); // use loopback for support of offline builds private static InetAddress loopback = InetAddress.getLoopbackAddress(); private static HazelcastMember member1; private static HazelcastMember member2; private static HazelcastMember member3; @BeforeClass public static void setUp() { int port1 = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); int port2 = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); int port3 = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); member1 = newHzMember(port1, port2, port3); member2 = newHzMember(port2, port1, port3); member3 = newHzMember(port3, port1, port2); } @AfterClass public static void tearDown() { member1.close(); member2.close(); member3.close(); } @Test public void call_executes_query_on_members() throws Exception { SuccessfulDistributedCall.COUNTER.set(0L); DistributedCall<Long> call = new SuccessfulDistributedCall(); DistributedAnswer<Long> answer = member1.call(call, MemberSelectors.DATA_MEMBER_SELECTOR, 30_000L); assertThat(answer.getMembers()).extracting(Member::getUuid).containsOnlyOnce(member1.getUuid(), member2.getUuid(), member3.getUuid()); assertThat(extractAnswers(answer)).containsOnlyOnce(0L, 1L, 2L); } @Test public void timed_out_calls_do_not_break_other_answers() throws InterruptedException { // member 1 and 3 success, member 2 times-out TimedOutDistributedCall.COUNTER.set(0L); DistributedCall call = new TimedOutDistributedCall(); DistributedAnswer<Long> answer = member1.call(call, MemberSelectors.DATA_MEMBER_SELECTOR, 2_000L); assertThat(extractAnswers(answer)).containsOnlyOnce(0L, 2L); assertThat(extractTimeOuts(answer)).containsExactlyInAnyOrder(false, false, true); } @Test public void failed_calls_do_not_break_other_answers() throws InterruptedException { // member 1 and 3 success, member 2 fails FailedDistributedCall.COUNTER.set(0L); DistributedCall call = new FailedDistributedCall(); DistributedAnswer<Long> answer = member1.call(call, MemberSelectors.DATA_MEMBER_SELECTOR, 2_000L); // 2 successful answers assertThat(extractAnswers(answer)).containsOnlyOnce(0L, 2L); // 1 failure List<Exception> failures = extractFailures(answer); assertThat(failures).hasSize(1); assertThat(failures.get(0)).hasMessageContaining("BOOM"); } private static HazelcastMember newHzMember(int port, int... otherPorts) { return new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP) .setProcessId(ProcessId.COMPUTE_ENGINE) .setNodeName("name" + port) .setPort(port) .setNetworkInterface(loopback.getHostAddress()) .setMembers(Arrays.stream(otherPorts).mapToObj(p -> loopback.getHostAddress() + ":" + p).collect(Collectors.joining(","))) .build(); } private static Set<Long> extractAnswers(DistributedAnswer<Long> answer) { return answer.getMembers().stream() .map(answer::getAnswer) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); } private static List<Exception> extractFailures(DistributedAnswer<Long> answer) { return answer.getMembers().stream() .map(answer::getFailed) .filter(Optional::isPresent) .map(Optional::get) .toList(); } private static List<Boolean> extractTimeOuts(DistributedAnswer<Long> answer) { return answer.getMembers().stream() .map(answer::hasTimedOut) .toList(); } }
5,140
35.460993
138
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberSelectorsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessId.APP; import static org.sonar.process.ProcessId.COMPUTE_ENGINE; import static org.sonar.process.ProcessId.WEB_SERVER; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.PROCESS_KEY; public class HazelcastMemberSelectorsTest { @Test public void selecting_ce_nodes() { Member member = mock(Member.class); MemberSelector underTest = HazelcastMemberSelectors.selectorForProcessIds(COMPUTE_ENGINE); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(COMPUTE_ENGINE.getKey()); assertThat(underTest.select(member)).isTrue(); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(WEB_SERVER.getKey()); assertThat(underTest.select(member)).isFalse(); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(APP.getKey()); assertThat(underTest.select(member)).isFalse(); } @Test public void selecting_web_and_app_nodes() { Member member = mock(Member.class); MemberSelector underTest = HazelcastMemberSelectors.selectorForProcessIds(WEB_SERVER, APP); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(COMPUTE_ENGINE.getKey()); assertThat(underTest.select(member)).isFalse(); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(WEB_SERVER.getKey()); assertThat(underTest.select(member)).isTrue(); when(member.getAttribute(PROCESS_KEY.getKey())).thenReturn(APP.getKey()); assertThat(underTest.select(member)).isTrue(); } }
2,613
38.606061
95
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/SuccessfulDistributedCall.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import java.util.concurrent.atomic.AtomicLong; public class SuccessfulDistributedCall implements DistributedCall<Long> { static final AtomicLong COUNTER = new AtomicLong(); @Override public Long call() { return COUNTER.getAndIncrement(); } }
1,138
34.59375
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/TimedOutDistributedCall.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import java.util.concurrent.atomic.AtomicLong; public class TimedOutDistributedCall implements DistributedCall<Long> { static final AtomicLong COUNTER = new AtomicLong(); @Override public Long call() throws Exception { long value = COUNTER.getAndIncrement(); if (value == 1L) { // only the second call times out Thread.sleep(30_000L); } return value; } }
1,275
33.486486
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/jmx/Fake.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.jmx; public class Fake implements FakeMBean { @Override public void foo() { } }
957
33.214286
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/jmx/FakeMBean.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.jmx; public interface FakeMBean { void foo(); }
920
35.84
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/jmx/test/Fake.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.jmx.test; import org.sonar.process.jmx.FakeMBean; // implementation is in a different package than interface public class Fake implements FakeMBean { @Override public void foo() { } }
1,062
33.290323
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/EscapedMessageConverterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.spi.ILoggingEvent; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class EscapedMessageConverterTest { private final EscapedMessageConverter underTest = new EscapedMessageConverter(); @Test public void convert_null_message() { ILoggingEvent event = createILoggingEvent(null); assertThat(underTest.convert(event)).isNull(); } @Test public void convert_simple_message() { ILoggingEvent event = createILoggingEvent("simple message"); assertThat(underTest.convert(event)).isEqualTo("simple message"); } @Test public void convert_message_with_CR() { ILoggingEvent event = createILoggingEvent("simple\r message\r with\r CR\r"); assertThat(underTest.convert(event)).isEqualTo("simple\\r message\\r with\\r CR\\r"); } @Test public void convert_message_with_LF() { ILoggingEvent event = createILoggingEvent("simple\n message\n with\n LF"); assertThat(underTest.convert(event)).isEqualTo("simple\\n message\\n with\\n LF"); } @Test public void convert_message_with_CRLF() { ILoggingEvent event = createILoggingEvent("simple\n\r\n message\r with\r\n CR LF"); assertThat(underTest.convert(event)).isEqualTo("simple\\n\\r\\n message\\r with\\r\\n CR LF"); } private static ILoggingEvent createILoggingEvent(String message) { return new TestILoggingEvent(message); } }
2,294
33.772727
98
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/Log4JPropertiesBuilderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Properties; import java.util.Random; import java.util.Set; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.MessageException; import org.sonar.process.ProcessId; import org.sonar.process.Props; import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertThrows; import static org.sonar.process.logging.RootLoggerConfig.newRootLoggerConfigBuilder; @RunWith(DataProviderRunner.class) public class Log4JPropertiesBuilderTest { private static final String ROLLING_POLICY_PROPERTY = "sonar.log.rollingPolicy"; private static final String PROPERTY_MAX_FILES = "sonar.log.maxFiles"; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private final RootLoggerConfig esRootLoggerConfig = newRootLoggerConfigBuilder().setProcessId(ProcessId.ELASTICSEARCH).build(); @Test public void constructor_fails_with_NPE_if_Props_is_null() { assertThatThrownBy(() -> new Log4JPropertiesBuilder(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Props can't be null"); } @Test public void constructor_sets_status_to_ERROR() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Properties properties = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build(); assertThat(properties.getProperty("status")).isEqualTo("ERROR"); } @Test public void getRootLoggerName_returns_rootLogger() { assertThat(newLog4JPropertiesBuilder().getRootLoggerName()).isEqualTo("rootLogger"); } @Test public void get_always_returns_a_new_object() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Properties previous = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build(); for (int i = 0; i < 2 + new Random().nextInt(5); i++) { Properties properties = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build(); assertThat(properties).isNotSameAs(previous); previous = properties; } } @Test public void buildLogPattern_puts_process_key_as_process_id() { String pattern = newLog4JPropertiesBuilder().buildLogPattern(newRootLoggerConfigBuilder() .setProcessId(ProcessId.ELASTICSEARCH) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level es[][%logger{1.}] %msg%n"); } @Test public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() { String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5); String pattern = newLog4JPropertiesBuilder().buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.APP) .setThreadIdFieldPattern(threadIdFieldPattern) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level app[" + threadIdFieldPattern + "][%logger{1.}] %msg%n"); } @Test public void buildLogPattern_does_not_put_threadIdFieldPattern_from_RootLoggerConfig_is_null() { String pattern = newLog4JPropertiesBuilder().buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.COMPUTE_ENGINE) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level ce[][%logger{1.}] %msg%n"); } @Test public void buildLogPattern_does_not_put_threadIdFieldPattern_from_RootLoggerConfig_is_empty() { String pattern = newLog4JPropertiesBuilder().buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.WEB_SERVER) .setThreadIdFieldPattern("") .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level web[][%logger{1.}] %msg%n"); } @Test public void configureGlobalFileLog_sets_properties_for_daily_time_rolling_policy_with_max_7_files_for_empty_props() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); var underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyTimeRollingPolicy(underTest, logDir, logPattern, "yyyy-MM-dd", 7); } @Test public void time_rolling_policy_has_large_max_files_if_property_is_zero() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; var underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "time:yyyy-MM-dd", PROPERTY_MAX_FILES, "0") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyTimeRollingPolicy(underTest, logDir, logPattern, "yyyy-MM-dd", 100_000); } @Test public void time_rolling_policy_has_large_max_files_if_property_is_negative() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; var underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "time:yyyy-MM-dd", PROPERTY_MAX_FILES, "-2") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyTimeRollingPolicy(underTest, logDir, logPattern, "yyyy-MM-dd", 100_000); } @Test public void size_rolling_policy_has_large_max_files_if_property_is_zero() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; String sizePattern = "1KB"; var underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern, PROPERTY_MAX_FILES, "0") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, 100_000); } @Test public void size_rolling_policy_has_large_max_files_if_property_is_negative() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; String sizePattern = "1KB"; var underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern, PROPERTY_MAX_FILES, "-2") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, 100_000); } @Test public void configureGlobalFileLog_throws_MessageException_when_property_is_not_supported() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); String invalidPropertyValue = randomAlphanumeric(3); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, invalidPropertyValue) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); assertThatThrownBy(underTest::build) .isInstanceOf(MessageException.class) .hasMessage("Unsupported value for property " + ROLLING_POLICY_PROPERTY + ": " + invalidPropertyValue); } @Test public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_with_max_7_files_when_property_starts_with_time_colon() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); String timePattern = randomAlphanumeric(6); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "time:" + timePattern) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyTimeRollingPolicy(underTest, logDir, logPattern, timePattern, 7); } @Test public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_when_property_starts_with_time_colon_and_specified_max_number_of_files() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); String timePattern = randomAlphanumeric(6); int maxFile = 1 + new Random().nextInt(10); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "time:" + timePattern, PROPERTY_MAX_FILES, valueOf(maxFile)) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyTimeRollingPolicy(underTest, logDir, logPattern, timePattern, maxFile); } @Test public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_with_max_7_files_when_property_starts_with_size_colon() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); String sizePattern = randomAlphanumeric(6); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, 7); } @Test public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_when_property_starts_with_size_colon_and_specified_max_number_of_files() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); String sizePattern = randomAlphanumeric(6); int maxFile = 1 + new Random().nextInt(10); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern, PROPERTY_MAX_FILES, valueOf(maxFile)) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, maxFile); } @Test public void configureGlobalFileLog_sets_properties_for_no_rolling_policy_when_property_is_none() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "none") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern); verifyProperties(underTest.build(), "appender.file_es.type", "File", "appender.file_es.name", "file_es", "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", logPattern, "rootLogger.appenderRef.file_es.ref", "file_es"); } @Test public void enable_all_logs_to_stdout_write_additionally_Console_appender() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(ROLLING_POLICY_PROPERTY, "none") .enableAllLogsToConsole(true) .rootLoggerConfig(esRootLoggerConfig) .logPattern(logPattern) .logDir(logDir); verifyProperties(underTest.build(), "appender.stdout.type", "Console", "appender.stdout.name", "stdout", "appender.stdout.layout.type", "PatternLayout", "appender.stdout.layout.pattern", logPattern, "rootLogger.appenderRef.stdout.ref", "stdout", "appender.file_es.layout.pattern", logPattern, "appender.file_es.layout.type", "PatternLayout", "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.name", "file_es", "rootLogger.appenderRef.file_es.ref", "file_es", "appender.file_es.type", "File"); } @Test public void enable_json_output_should_change_pattern_for_console_and_file_appender() throws IOException { File logDir = temporaryFolder.newFolder(); String expectedPattern = "{\"process\": \"es\",\"timestamp\": \"%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ}\"," + "\"severity\": \"%p\",\"logger\": \"%c{1.}\",\"message\": \"%notEmpty{%enc{%marker}{JSON} }%enc{%.-10000m}{JSON}\"%exceptionAsJson }" + System.lineSeparator(); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(ROLLING_POLICY_PROPERTY, "none") .enableAllLogsToConsole(true) .rootLoggerConfig(esRootLoggerConfig) .jsonOutput(true) .logDir(logDir); verifyProperties(underTest.build(), "appender.stdout.type", "Console", "appender.stdout.name", "stdout", "appender.stdout.layout.type", "PatternLayout", "appender.stdout.layout.pattern", expectedPattern, "rootLogger.appenderRef.stdout.ref", "stdout", "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", expectedPattern, "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.name", "file_es", "rootLogger.appenderRef.file_es.ref", "file_es", "appender.file_es.type", "File"); } @Test public void enable_json_output_should_include_hostname_if_set() throws IOException { File logDir = temporaryFolder.newFolder(); RootLoggerConfig esRootLoggerConfigWithHostname = newRootLoggerConfigBuilder() .setProcessId(ProcessId.ELASTICSEARCH) .setNodeNameField("my-node") .build(); String expectedPattern = "{\"nodename\": \"my-node\",\"process\": \"es\",\"timestamp\": \"%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZ}\"," + "\"severity\": \"%p\",\"logger\": \"%c{1.}\",\"message\": \"%notEmpty{%enc{%marker}{JSON} }%enc{%.-10000m}{JSON}\"%exceptionAsJson }" + System.lineSeparator(); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(ROLLING_POLICY_PROPERTY, "none") .enableAllLogsToConsole(true) .rootLoggerConfig(esRootLoggerConfigWithHostname) .jsonOutput(true) .logDir(logDir); verifyProperties(underTest.build(), "appender.stdout.type", "Console", "appender.stdout.name", "stdout", "appender.stdout.layout.type", "PatternLayout", "appender.stdout.layout.pattern", expectedPattern, "rootLogger.appenderRef.stdout.ref", "stdout", "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", expectedPattern, "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.name", "file_es", "rootLogger.appenderRef.file_es.ref", "file_es", "appender.file_es.type", "File"); } @Test public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_rootLoggerName_of_Log4J() throws IOException { LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(logLevelConfig); assertThatThrownBy(underTest::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of LogLevelConfig#rootLoggerName must be \"rootLogger\""); } @Test public void apply_fails_with_IAE_if_global_property_has_unsupported_level() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "ERROR") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); assertThatThrownBy(underTest::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void apply_fails_with_IAE_if_process_property_has_unsupported_level() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "ERROR") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); assertThatThrownBy(underTest::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void apply_sets_root_logger_to_INFO_if_no_property_is_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); underTest.build(); verifyRootLoggerLevel(underTest, Level.INFO); } @Test public void apply_sets_root_logger_to_global_property_if_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "TRACE") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyRootLoggerLevel(underTest, Level.TRACE); } @Test public void apply_sets_root_logger_to_process_property_if_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "DEBUG") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyRootLoggerLevel(underTest, Level.DEBUG); } @Test public void apply_sets_root_logger_to_process_property_over_global_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "DEBUG", "sonar.log.level.web", "TRACE") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyRootLoggerLevel(underTest, Level.TRACE); } @Test public void apply_sets_domain_property_over_process_and_global_property_if_all_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level", "DEBUG", "sonar.log.level.web", "DEBUG", "sonar.log.level.web.es", "TRACE") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyLoggerProperties(underTest.build(), "foo", Level.TRACE); } @Test public void apply_sets_domain_property_over_process_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level.web", "DEBUG", "sonar.log.level.web.es", "TRACE") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyLoggerProperties(underTest.build(), "foo", Level.TRACE); } @Test public void apply_sets_domain_property_over_global_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level", "DEBUG", "sonar.log.level.web.es", "TRACE") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyLoggerProperties(underTest.build(), "foo", Level.TRACE); } @Test public void apply_fails_with_IAE_if_domain_property_has_unsupported_level() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX).build(); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web.jmx", "ERROR") .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); assertThatThrownBy(underTest::build) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test @UseDataProvider("logbackLevels") public void apply_accepts_any_level_as_hardcoded_level(Level level) throws IOException { LogLevelConfig config = newLogLevelConfig().immutableLevel("bar", level).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); verifyLoggerProperties(underTest.build(), "bar", level); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_not_set() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logLevelConfig(newLogLevelConfig().offUnlessTrace("fii").build()) .logDir(logDir) .logPattern(logPattern); verifyLoggerProperties(underTest.build(), "fii", Level.OFF); } @Test public void fail_if_pattern_not_provided() { Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(new File("dir")); assertThrows(IllegalStateException.class, underTest::build); } @Test public void fail_if_root_logger_config_not_provided() { Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .logPattern("pattern") .logDir(new File("dir")); assertThrows(NullPointerException.class, underTest::build); } @Test public void fail_if_logDir_not_provided() { Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .logPattern("pattern") .rootLoggerConfig(esRootLoggerConfig); assertThrows(NullPointerException.class, underTest::build); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_INFO() throws Exception { setLevelToOff(Level.INFO); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_DEBUG() throws Exception { setLevelToOff(Level.DEBUG); } @Test public void apply_does_not_create_loggers_property_if_only_root_level_is_defined() throws IOException { LogLevelConfig logLevelConfig = newLogLevelConfig().rootLevelFor(ProcessId.APP).build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(logLevelConfig); assertThat(underTest.build().getProperty("loggers")).isNull(); } @Test public void apply_creates_loggers_property_with_logger_names_ordered_but_root() throws IOException { LogLevelConfig config = newLogLevelConfig() .rootLevelFor(ProcessId.WEB_SERVER) .levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX) .levelByDomain("bar", ProcessId.COMPUTE_ENGINE, LogDomain.ES) .immutableLevel("doh", Level.ERROR) .immutableLevel("pif", Level.TRACE) .offUnlessTrace("fii") .build(); File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(config); assertThat(underTest.build().getProperty("loggers")).isEqualTo("bar,doh,fii,foo,pif"); } @Test public void apply_does_not_set_level_if_sonar_global_level_is_TRACE() throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", Level.TRACE.toString()) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(newLogLevelConfig().offUnlessTrace("fii").build()); verifyNoLoggerProperties(underTest.build(), "fii"); } private void setLevelToOff(Level globalLogLevel) throws IOException { File logDir = temporaryFolder.newFolder(); String logPattern = randomAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", globalLogLevel.toString()) .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) .logPattern(logPattern) .logLevelConfig(newLogLevelConfig().offUnlessTrace("fii").build()); verifyLoggerProperties(underTest.build(), "fii", Level.OFF); } private static Log4JPropertiesBuilder newLog4JPropertiesBuilder(String... propertyKeysAndValues) { Properties properties = new Properties(); assertThat(propertyKeysAndValues.length % 2).describedAs("propertyKeysAndValues must have even length").isZero(); for (int i = 0; i < propertyKeysAndValues.length; i++) { properties.put(propertyKeysAndValues[i++], propertyKeysAndValues[i]); } return new Log4JPropertiesBuilder(new Props(properties)); } private void verifyTimeRollingPolicy(Log4JPropertiesBuilder builder, File logDir, String logPattern, String datePattern, int maxFiles) { verifyProperties(builder.build(), "appender.file_es.type", "RollingFile", "appender.file_es.name", "file_es", "appender.file_es.filePattern", new File(logDir, "es.%d{" + datePattern + "}.log").getAbsolutePath(), "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", logPattern, "appender.file_es.policies.type", "Policies", "appender.file_es.policies.time.type", "TimeBasedTriggeringPolicy", "appender.file_es.policies.time.interval", "1", "appender.file_es.policies.time.modulate", "true", "appender.file_es.strategy.type", "DefaultRolloverStrategy", "appender.file_es.strategy.fileIndex", "nomax", "appender.file_es.strategy.action.type", "Delete", "appender.file_es.strategy.action.basepath", logDir.getAbsolutePath(), "appender.file_es.strategy.action.maxDepth", "1", "appender.file_es.strategy.action.condition.type", "IfFileName", "appender.file_es.strategy.action.condition.glob", "es*", "appender.file_es.strategy.action.condition.nested_condition.type", "IfAccumulatedFileCount", "appender.file_es.strategy.action.condition.nested_condition.exceeds", valueOf(maxFiles), "rootLogger.appenderRef.file_es.ref", "file_es"); } private void verifySizeRollingPolicy(Log4JPropertiesBuilder builder, File logDir, String logPattern, String sizePattern, int maxFiles) { verifyProperties(builder.build(), "appender.file_es.type", "RollingFile", "appender.file_es.name", "file_es", "appender.file_es.filePattern", new File(logDir, "es.%i.log").getAbsolutePath(), "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", logPattern, "appender.file_es.policies.type", "Policies", "appender.file_es.policies.size.type", "SizeBasedTriggeringPolicy", "appender.file_es.policies.size.size", sizePattern, "appender.file_es.strategy.type", "DefaultRolloverStrategy", "appender.file_es.strategy.max", valueOf(maxFiles), "rootLogger.appenderRef.file_es.ref", "file_es"); } private void verifyProperties(Properties properties, String... expectedPropertyKeysAndValuesOrdered) { assertThat(properties).containsEntry("status", "ERROR"); if (expectedPropertyKeysAndValuesOrdered.length == 0) { assertThat(properties.size()).isOne(); } else { assertThat(expectedPropertyKeysAndValuesOrdered.length % 2).describedAs("Number of parameters must be even").isZero(); Set<String> keys = new HashSet<>(expectedPropertyKeysAndValuesOrdered.length / 2 + 1); keys.add("status"); for (int i = 0; i < expectedPropertyKeysAndValuesOrdered.length; i++) { String key = expectedPropertyKeysAndValuesOrdered[i++]; String value = expectedPropertyKeysAndValuesOrdered[i]; assertThat(properties.get(key)).describedAs("Unexpected value for property " + key).isEqualTo(value); keys.add(key); } assertThat(properties).containsOnlyKeys(keys.toArray()); } } private LogLevelConfig.Builder newLogLevelConfig() { return LogLevelConfig.newBuilder("rootLogger"); } private void verifyLoggerProperties(Properties properties, String loggerName, Level expectedLevel) { assertThat(properties).containsEntry("logger." + loggerName + ".name", loggerName); assertThat(properties).containsEntry("logger." + loggerName + ".level", expectedLevel.toString()); } private void verifyNoLoggerProperties(Properties properties, String loggerName) { assertThat(properties.get("logger." + loggerName + ".name")).isNull(); assertThat(properties.get("logger." + loggerName + ".level")).isNull(); } private void verifyRootLoggerLevel(Log4JPropertiesBuilder underTest, Level expectedLevel) { assertThat(underTest.build()).containsEntry("rootLogger.level", expectedLevel.toString()); } @DataProvider public static Object[][] logbackLevels() { return new Object[][] { {Level.OFF}, {Level.ERROR}, {Level.WARN}, {Level.INFO}, {Level.DEBUG}, {Level.TRACE}, {Level.ALL} }; } }
32,687
39.911139
168
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import java.util.Collections; import org.apache.commons.lang.RandomStringUtils; import org.junit.Test; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Fail.fail; import static org.sonar.process.logging.LogLevelConfig.newBuilder; public class LogLevelConfigTest { private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20); private LogLevelConfig.Builder underTest = newBuilder(rootLoggerName); @Test public void newBuilder_throws_NPE_if_rootLoggerName_is_null() { assertThatThrownBy(() -> newBuilder(null)) .isInstanceOf(NullPointerException.class) .hasMessage("rootLoggerName can't be null"); } @Test public void getLoggerName_returns_name_passed_to_builder() { String rootLoggerName = RandomStringUtils.randomAlphabetic(32); LogLevelConfig logLevelConfig = newBuilder(rootLoggerName).build(); assertThat(logLevelConfig.getRootLoggerName()).isEqualTo(rootLoggerName); } @Test public void build_can_create_empty_config_and_returned_maps_are_unmodifiable() { LogLevelConfig underTest = newBuilder(rootLoggerName).build(); expectUnsupportedOperationException(() -> underTest.getConfiguredByProperties().put("1", Collections.emptyList())); expectUnsupportedOperationException(() -> underTest.getConfiguredByHardcodedLevel().put("1", Level.ERROR)); } @Test public void builder_rootLevelFor_add_global_and_process_property_in_order_for_root_logger() { LogLevelConfig underTest = newBuilder(rootLoggerName).rootLevelFor(ProcessId.ELASTICSEARCH).build(); assertThat(underTest.getConfiguredByProperties()).hasSize(1); assertThat(underTest.getConfiguredByProperties().get(rootLoggerName)) .containsExactly("sonar.log.level", "sonar.log.level.es"); assertThat(underTest.getConfiguredByHardcodedLevel()).isEmpty(); } @Test public void builder_rootLevelFor_fails_with_ProcessId_if_loggerName_is_null() { assertThatThrownBy(() -> underTest.rootLevelFor(null)) .isInstanceOf(NullPointerException.class) .hasMessage("ProcessId can't be null"); } @Test public void builder_rootLevelFor_fails_with_ISE_if_called_twice() { underTest.rootLevelFor(ProcessId.ELASTICSEARCH); assertThatThrownBy(() -> underTest.rootLevelFor(ProcessId.WEB_SERVER)) .isInstanceOf(IllegalStateException.class) .hasMessage("Configuration by property already registered for " + rootLoggerName); } @Test public void builder_levelByDomain_fails_with_NPE_if_loggerName_is_null() { assertThatThrownBy(() -> underTest.levelByDomain(null, ProcessId.WEB_SERVER, LogDomain.JMX)) .isInstanceOf(NullPointerException.class) .hasMessage("loggerName can't be null"); } @Test public void builder_levelByDomain_fails_with_IAE_if_loggerName_is_empty() { assertThatThrownBy(() -> underTest.levelByDomain("", ProcessId.WEB_SERVER, LogDomain.JMX)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("loggerName can't be empty"); } @Test public void builder_levelByDomain_fails_with_NPE_if_ProcessId_is_null() { assertThatThrownBy(() -> underTest.levelByDomain("bar", null, LogDomain.JMX)) .isInstanceOf(NullPointerException.class) .hasMessage("ProcessId can't be null"); } @Test public void builder_levelByDomain_fails_with_NPE_if_LogDomain_is_null() { assertThatThrownBy(() -> underTest.levelByDomain("bar", ProcessId.WEB_SERVER, null)) .isInstanceOf(NullPointerException.class) .hasMessage("LogDomain can't be null"); } @Test public void builder_levelByDomain_adds_global_process_and_domain_properties_in_order_for_specified_logger() { LogLevelConfig underTest = newBuilder(rootLoggerName) .levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.SQL) .build(); assertThat(underTest.getConfiguredByProperties()).hasSize(1); assertThat(underTest.getConfiguredByProperties().get("foo")) .containsExactly("sonar.log.level", "sonar.log.level.web", "sonar.log.level.web.sql"); assertThat(underTest.getConfiguredByHardcodedLevel()).isEmpty(); } @Test public void builder_levelByDomain_fails_with_ISE_if_loggerName_has_immutableLevel() { underTest.immutableLevel("bar", Level.INFO); assertThatThrownBy(() -> underTest.levelByDomain("bar", ProcessId.WEB_SERVER, LogDomain.JMX)) .isInstanceOf(IllegalStateException.class) .hasMessage("Configuration hardcoded level already registered for bar"); } @Test public void builder_immutableLevel_fails_with_NPE_if_logger_name_is_null() { assertThatThrownBy(() -> underTest.immutableLevel(null, Level.ERROR)) .isInstanceOf(NullPointerException.class) .hasMessage("loggerName can't be null"); } @Test public void builder_immutableLevel_fails_with_IAE_if_logger_name_is_empty() { assertThatThrownBy(() -> underTest.immutableLevel("", Level.ERROR)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("loggerName can't be empty"); } @Test public void builder_immutableLevel_fails_with_NPE_if_level_is_null() { assertThatThrownBy(() -> underTest.immutableLevel("foo", null)) .isInstanceOf(NullPointerException.class) .hasMessage("level can't be null"); } @Test public void builder_immutableLevel_set_specified_level_for_specified_logger() { LogLevelConfig config = underTest.immutableLevel("bar", Level.INFO).build(); assertThat(config.getConfiguredByProperties()).isEmpty(); assertThat(config.getConfiguredByHardcodedLevel()).hasSize(1); assertThat(config.getConfiguredByHardcodedLevel()).containsEntry("bar", Level.INFO); } @Test public void builder_fails_with_ISE_if_immutableLevel_called_twice_for_same_logger() { underTest.immutableLevel("foo", Level.INFO); assertThatThrownBy(() -> underTest.immutableLevel("foo", Level.DEBUG)) .isInstanceOf(IllegalStateException.class) .hasMessage("Configuration hardcoded level already registered for foo"); } @Test public void builder_fails_with_ISE_if_logger_has_domain_config() { underTest.levelByDomain("pop", ProcessId.WEB_SERVER, LogDomain.JMX); assertThatThrownBy(() -> underTest.immutableLevel("pop", Level.DEBUG)) .isInstanceOf(IllegalStateException.class) .hasMessage("Configuration by property already registered for pop"); } private static void expectUnsupportedOperationException(Runnable runnable) { try { runnable.run(); fail("a UnsupportedOperationException should have been raised"); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class); } } }
7,696
38.675258
119
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.Appender; import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.Layout; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; import ch.qos.logback.core.util.FileSize; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.reflect.FieldUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.MessageException; import org.sonar.process.ProcessId; import org.sonar.process.Props; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.logging.RootLoggerConfig.newRootLoggerConfigBuilder; @RunWith(DataProviderRunner.class) public class LogbackHelperTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private Props props = new Props(new Properties()); private LogbackHelper underTest = new LogbackHelper(); @Before public void setUp() throws Exception { File dir = temp.newFolder(); props.set(PATH_LOGS.getKey(), dir.getAbsolutePath()); } @After public void resetLogback() throws Exception { new LogbackHelper().resetFromXml("/org/sonar/process/logging/LogbackHelperTest/logback-test.xml"); } @Test public void getRootContext() { assertThat(underTest.getRootContext()).isNotNull(); } @Test public void buildLogPattern_puts_process_key_as_process_id() { String pattern = underTest.buildLogPattern(newRootLoggerConfigBuilder() .setProcessId(ProcessId.ELASTICSEARCH) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level es[][%logger{20}] %msg%n"); } @Test public void buildLogPattern_adds_nodename() { String pattern = underTest.buildLogPattern(newRootLoggerConfigBuilder() .setProcessId(ProcessId.ELASTICSEARCH) .setNodeNameField("my-nodename") .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level my-nodename es[][%logger{20}] %msg%n"); } @Test public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() { String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5); String pattern = underTest.buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.APP) .setThreadIdFieldPattern(threadIdFieldPattern) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level app[" + threadIdFieldPattern + "][%logger{20}] %msg%n"); } @Test public void buildLogPattern_does_not_put_threadIdFieldPattern_from_RootLoggerConfig_is_null() { String pattern = underTest.buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.COMPUTE_ENGINE) .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level ce[][%logger{20}] %msg%n"); } @Test public void buildLogPattern_does_not_put_threadIdFieldPattern_from_RootLoggerConfig_is_empty() { String pattern = underTest.buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.WEB_SERVER) .setThreadIdFieldPattern("") .build()); assertThat(pattern).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level web[][%logger{20}] %msg%n"); } @Test public void enableJulChangePropagation() { LoggerContext ctx = underTest.getRootContext(); int countListeners = ctx.getCopyOfListenerList().size(); LoggerContextListener propagator = underTest.enableJulChangePropagation(ctx); assertThat(ctx.getCopyOfListenerList()).hasSize(countListeners + 1); ctx.removeListener(propagator); } @Test public void verify_jul_initialization() { LoggerContext ctx = underTest.getRootContext(); String logbackRootLoggerName = underTest.getRootLoggerName(); LogLevelConfig config = LogLevelConfig.newBuilder(logbackRootLoggerName) .levelByDomain(logbackRootLoggerName, ProcessId.WEB_SERVER, LogDomain.JMX).build(); props.set("sonar.log.level.web", "TRACE"); underTest.apply(config, props); MemoryAppender memoryAppender = new MemoryAppender(); memoryAppender.start(); underTest.getRootContext().getLogger(logbackRootLoggerName).addAppender(memoryAppender); java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("com.ms.sqlserver.jdbc.DTV"); julLogger.finest("Message1"); julLogger.finer("Message1"); julLogger.fine("Message1"); julLogger.info("Message1"); julLogger.warning("Message1"); julLogger.severe("Message1"); // JUL bridge has not been initialized, nothing in logs assertThat(memoryAppender.getLogs().stream().filter(l -> l.getMessage().equals("Message1")).collect(toList())).isEmpty(); // Enabling JUL bridge LoggerContextListener propagator = underTest.enableJulChangePropagation(ctx); julLogger.finest("Message2"); julLogger.finer("Message2"); julLogger.fine("Message2"); julLogger.info("Message2"); julLogger.warning("Message2"); julLogger.severe("Message2"); assertThat(julLogger.isLoggable(java.util.logging.Level.FINEST)).isTrue(); assertThat(julLogger.isLoggable(java.util.logging.Level.FINER)).isTrue(); assertThat(julLogger.isLoggable(java.util.logging.Level.FINE)).isTrue(); assertThat(julLogger.isLoggable(java.util.logging.Level.INFO)).isTrue(); assertThat(julLogger.isLoggable(java.util.logging.Level.SEVERE)).isTrue(); assertThat(julLogger.isLoggable(java.util.logging.Level.WARNING)).isTrue(); // We are expecting messages from info to severe assertThat(memoryAppender.getLogs().stream().filter(l -> l.getMessage().equals("Message2")).collect(toList())).hasSize(6); memoryAppender.clear(); ctx.getLogger(logbackRootLoggerName).setLevel(Level.INFO); julLogger.finest("Message3"); julLogger.finer("Message3"); julLogger.fine("Message3"); julLogger.info("Message3"); julLogger.warning("Message3"); julLogger.severe("Message3"); // We are expecting messages from finest to severe in TRACE mode assertThat(memoryAppender.getLogs().stream().filter(l -> l.getMessage().equals("Message3")).collect(toList())).hasSize(3); memoryAppender.clear(); memoryAppender.stop(); ctx.removeListener(propagator); } @Test public void newConsoleAppender() { LoggerContext ctx = underTest.getRootContext(); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(ctx); encoder.setPattern("%msg%n"); encoder.start(); ConsoleAppender<?> appender = underTest.newConsoleAppender(ctx, "MY_APPENDER", encoder); assertThat(appender.getName()).isEqualTo("MY_APPENDER"); assertThat(appender.getContext()).isSameAs(ctx); assertThat(appender.isStarted()).isTrue(); assertThat(((PatternLayoutEncoder) appender.getEncoder()).getPattern()).isEqualTo("%msg%n"); assertThat(appender.getCopyOfAttachedFiltersList()).isEmpty(); } @Test public void createRollingPolicy_defaults() { LoggerContext ctx = underTest.getRootContext(); LogbackHelper.RollingPolicy policy = underTest.createRollingPolicy(ctx, props, "sonar"); FileAppender appender = policy.createAppender("SONAR_FILE"); assertThat(appender).isInstanceOf(RollingFileAppender.class); // max 5 daily files RollingFileAppender fileAppender = (RollingFileAppender) appender; TimeBasedRollingPolicy triggeringPolicy = (TimeBasedRollingPolicy) fileAppender.getTriggeringPolicy(); assertThat(triggeringPolicy.getMaxHistory()).isEqualTo(7); assertThat(triggeringPolicy.getFileNamePattern()).endsWith("sonar.%d{yyyy-MM-dd}.log"); } @Test public void createRollingPolicy_none() { props.set("sonar.log.rollingPolicy", "none"); LoggerContext ctx = underTest.getRootContext(); LogbackHelper.RollingPolicy policy = underTest.createRollingPolicy(ctx, props, "sonar"); Appender appender = policy.createAppender("SONAR_FILE"); assertThat(appender).isNotInstanceOf(RollingFileAppender.class).isInstanceOf(FileAppender.class); } @Test public void createRollingPolicy_size() throws Exception { props.set("sonar.log.rollingPolicy", "size:1MB"); props.set("sonar.log.maxFiles", "20"); LoggerContext ctx = underTest.getRootContext(); LogbackHelper.RollingPolicy policy = underTest.createRollingPolicy(ctx, props, "sonar"); Appender appender = policy.createAppender("SONAR_FILE"); assertThat(appender).isInstanceOf(RollingFileAppender.class); // max 20 files of 1Mb RollingFileAppender fileAppender = (RollingFileAppender) appender; FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) fileAppender.getRollingPolicy(); assertThat(rollingPolicy.getMaxIndex()).isEqualTo(20); assertThat(rollingPolicy.getFileNamePattern()).endsWith("sonar.%i.log"); SizeBasedTriggeringPolicy triggeringPolicy = (SizeBasedTriggeringPolicy) fileAppender.getTriggeringPolicy(); FileSize maxFileSize = (FileSize) FieldUtils.readField(triggeringPolicy, "maxFileSize", true); assertThat(maxFileSize.getSize()).isEqualTo(1024L * 1024); } @Test public void createRollingPolicy_time() { props.set("sonar.log.rollingPolicy", "time:yyyy-MM"); props.set("sonar.log.maxFiles", "20"); LoggerContext ctx = underTest.getRootContext(); LogbackHelper.RollingPolicy policy = underTest.createRollingPolicy(ctx, props, "sonar"); RollingFileAppender appender = (RollingFileAppender) policy.createAppender("SONAR_FILE"); // max 5 monthly files TimeBasedRollingPolicy triggeringPolicy = (TimeBasedRollingPolicy) appender.getTriggeringPolicy(); assertThat(triggeringPolicy.getMaxHistory()).isEqualTo(20); assertThat(triggeringPolicy.getFileNamePattern()).endsWith("sonar.%d{yyyy-MM}.log"); } @Test public void createRollingPolicy_fail_if_unknown_policy() { props.set("sonar.log.rollingPolicy", "unknown:foo"); try { LoggerContext ctx = underTest.getRootContext(); underTest.createRollingPolicy(ctx, props, "sonar"); fail(); } catch (MessageException e) { assertThat(e).hasMessage("Unsupported value for property sonar.log.rollingPolicy: unknown:foo"); } } @Test public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_ROOT_LOGGER_NAME_of_LogBack() { LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build(); assertThatThrownBy(() -> underTest.apply(logLevelConfig, props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of LogLevelConfig#rootLoggerName must be \"ROOT\""); } @Test public void apply_fails_with_IAE_if_global_property_has_unsupported_level() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); props.set("sonar.log.level", "ERROR"); assertThatThrownBy(() -> underTest.apply(config, props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void apply_fails_with_IAE_if_process_property_has_unsupported_level() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); props.set("sonar.log.level.web", "ERROR"); assertThatThrownBy(() -> underTest.apply(config, props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void apply_sets_logger_to_INFO_if_no_property_is_set() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.INFO); } @Test public void apply_sets_logger_to_globlal_property_if_set() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); props.set("sonar.log.level", "TRACE"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_sets_logger_to_process_property_if_set() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); props.set("sonar.log.level.web", "DEBUG"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.DEBUG); } @Test public void apply_sets_logger_to_process_property_over_global_property_if_both_set() { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); props.set("sonar.log.level", "DEBUG"); props.set("sonar.log.level.web", "TRACE"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_sets_domain_property_over_process_and_global_property_if_all_set() { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); props.set("sonar.log.level", "DEBUG"); props.set("sonar.log.level.web", "DEBUG"); props.set("sonar.log.level.web.es", "TRACE"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger("foo").getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_sets_domain_property_over_process_property_if_both_set() { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); props.set("sonar.log.level.web", "DEBUG"); props.set("sonar.log.level.web.es", "TRACE"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger("foo").getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_sets_domain_property_over_global_property_if_both_set() { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); props.set("sonar.log.level", "DEBUG"); props.set("sonar.log.level.web.es", "TRACE"); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger("foo").getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_fails_with_IAE_if_domain_property_has_unsupported_level() { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX).build(); props.set("sonar.log.level.web.jmx", "ERROR"); assertThatThrownBy(() -> underTest.apply(config, props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test @UseDataProvider("logbackLevels") public void apply_accepts_any_level_as_hardcoded_level(Level level) { LogLevelConfig config = newLogLevelConfig().immutableLevel("bar", level).build(); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger("bar").getLevel()).isEqualTo(level); } @Test public void changeRoot_sets_level_of_ROOT_and_all_loggers_with_a_config_but_the_hardcoded_one() { LogLevelConfig config = newLogLevelConfig() .rootLevelFor(ProcessId.WEB_SERVER) .levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX) .levelByDomain("bar", ProcessId.COMPUTE_ENGINE, LogDomain.ES) .immutableLevel("doh", Level.ERROR) .immutableLevel("pif", Level.TRACE) .build(); LoggerContext context = underTest.apply(config, props); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.INFO); assertThat(context.getLogger("foo").getLevel()).isEqualTo(Level.INFO); assertThat(context.getLogger("bar").getLevel()).isEqualTo(Level.INFO); assertThat(context.getLogger("doh").getLevel()).isEqualTo(Level.ERROR); assertThat(context.getLogger("pif").getLevel()).isEqualTo(Level.TRACE); underTest.changeRoot(config, Level.DEBUG); assertThat(context.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.DEBUG); assertThat(context.getLogger("foo").getLevel()).isEqualTo(Level.DEBUG); assertThat(context.getLogger("bar").getLevel()).isEqualTo(Level.DEBUG); assertThat(context.getLogger("doh").getLevel()).isEqualTo(Level.ERROR); assertThat(context.getLogger("pif").getLevel()).isEqualTo(Level.TRACE); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_not_set() { LoggerContext context = underTest.apply(newLogLevelConfig().offUnlessTrace("fii").build(), new Props(new Properties())); assertThat(context.getLogger("fii").getLevel()).isEqualTo(Level.OFF); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_INFO() { setLevelToOff(Level.INFO); } @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_DEBUG() { setLevelToOff(Level.DEBUG); } @Test public void apply_does_not_set_level_if_sonar_global_level_is_TRACE() { Properties properties = new Properties(); properties.setProperty("sonar.log.level", Level.TRACE.toString()); assertThat(underTest.getRootContext().getLogger("fii").getLevel()).isNull(); LoggerContext context = underTest.apply(newLogLevelConfig().offUnlessTrace("fii").build(), new Props(properties)); assertThat(context.getLogger("fii").getLevel()).isNull(); } @Test public void createEncoder_uses_pattern_by_default() { RootLoggerConfig config = newRootLoggerConfigBuilder() .setProcessId(ProcessId.WEB_SERVER) .build(); Encoder<ILoggingEvent> encoder = underTest.createEncoder(props, config, underTest.getRootContext()); assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class); } @Test public void createEncoder_uses_json_output() { props.set("sonar.log.jsonOutput", "true"); RootLoggerConfig config = newRootLoggerConfigBuilder() .setProcessId(ProcessId.WEB_SERVER) .build(); Encoder<ILoggingEvent> encoder = underTest.createEncoder(props, config, underTest.getRootContext()); assertThat(encoder).isInstanceOf(LayoutWrappingEncoder.class); Layout layout = ((LayoutWrappingEncoder) encoder).getLayout(); assertThat(layout).isInstanceOf(LogbackJsonLayout.class); assertThat(((LogbackJsonLayout) layout).getProcessKey()).isEqualTo("web"); } private LogLevelConfig.Builder newLogLevelConfig() { return LogLevelConfig.newBuilder(ROOT_LOGGER_NAME); } private void setLevelToOff(Level globalLogLevel) { Properties properties = new Properties(); properties.setProperty("sonar.log.level", globalLogLevel.toString()); LoggerContext context = underTest.apply(newLogLevelConfig().offUnlessTrace("fii").build(), new Props(properties)); assertThat(context.getLogger("fii").getLevel()).isEqualTo(Level.OFF); } @DataProvider public static Object[][] logbackLevels() { return new Object[][] { {Level.OFF}, {Level.ERROR}, {Level.WARN}, {Level.INFO}, {Level.DEBUG}, {Level.TRACE}, {Level.ALL} }; } @Test public void log_to_console_setting_missing() { assertThat(underTest.isAllLogsToConsoleEnabled(new Props(new Properties()))).isFalse(); } @Test public void log_to_console_setting_enabled() { Properties properties = new Properties(); properties.setProperty("sonar.log.console", "true"); assertThat(underTest.isAllLogsToConsoleEnabled(new Props(properties))).isTrue(); } @Test public void log_to_console_setting_disabled() { Properties properties = new Properties(); properties.setProperty("sonar.log.console", "false"); assertThat(underTest.isAllLogsToConsoleEnabled(new Props(properties))).isFalse(); } public static class MemoryAppender extends AppenderBase<ILoggingEvent> { private static final List<ILoggingEvent> LOGS = new ArrayList<>(); @Override protected void append(ILoggingEvent eventObject) { LOGS.add(eventObject); } public List<ILoggingEvent> getLogs() { return ImmutableList.copyOf(LOGS); } public void clear() { LOGS.clear(); } } }
22,488
38.179443
140
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackJsonLayoutTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.LoggingEvent; import com.google.gson.Gson; import java.time.Instant; import org.junit.Test; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.process.logging.LogbackJsonLayout.DATE_FORMATTER; public class LogbackJsonLayoutTest { private final LogbackJsonLayout underTest = new LogbackJsonLayout("web", ""); @Test public void test_simple_log() { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.process).isEqualTo("web"); assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))); assertThat(json.severity).isEqualTo("WARN"); assertThat(json.logger).isEqualTo("the.logger"); assertThat(json.message).isEqualTo("the message"); assertThat(json.stacktrace).isNull(); assertThat(json.fromMdc).isNull(); assertThat(json.nodename).isNull(); } @Test public void test_simple_log_with_hostname() { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]); LogbackJsonLayout underTestWithNodeName = new LogbackJsonLayout("web", "my-nodename"); String log = underTestWithNodeName.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.process).isEqualTo("web"); assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))); assertThat(json.severity).isEqualTo("WARN"); assertThat(json.logger).isEqualTo("the.logger"); assertThat(json.message).isEqualTo("the message"); assertThat(json.stacktrace).isNull(); assertThat(json.fromMdc).isNull(); assertThat(json.nodename).isEqualTo("my-nodename"); } @Test public void test_log_with_throwable_and_no_cause() { Throwable exception = new IllegalStateException("BOOM"); LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", exception, new Object[0]); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.process).isEqualTo("web"); assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))); assertThat(json.severity).isEqualTo("WARN"); assertThat(json.logger).isEqualTo("the.logger"); assertThat(json.message).isEqualTo("the message"); assertThat(json.stacktrace).hasSizeGreaterThan(5); assertThat(json.stacktrace[0]).isEqualTo("java.lang.IllegalStateException: BOOM"); assertThat(json.stacktrace[1]).startsWith("at ").contains("LogbackJsonLayoutTest.test_log_with_throwable"); assertThat(json.fromMdc).isNull(); } @Test public void test_log_with_throwable_and_cause() { Throwable rootCause = new IllegalArgumentException("Root cause"); Throwable exception = new IllegalStateException("BOOM", rootCause); LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", exception, new Object[0]); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.stacktrace).hasSizeGreaterThan(5); assertThat(json.stacktrace[0]).isEqualTo("java.lang.IllegalStateException: BOOM"); assertThat(json.stacktrace[1]).contains("at org.sonar.process.logging.LogbackJsonLayoutTest.test_log_with_throwable_and_cause"); assertThat(json.stacktrace) .contains("\tCaused by: ") .contains("\tjava.lang.IllegalArgumentException: Root cause"); } @Test public void test_log_with_suppressed_throwable() { Exception exception = new Exception("BOOM"); exception.addSuppressed(new IllegalStateException("foo")); LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", exception, new Object[0]); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.stacktrace).hasSizeGreaterThan(5); assertThat(json.stacktrace[0]).isEqualTo("java.lang.Exception: BOOM"); assertThat(json.stacktrace).contains("Suppressed: java.lang.IllegalStateException: foo"); } @Test public void test_log_with_message_arguments() { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the {}", null, new Object[] {"message"}); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.process).isEqualTo("web"); assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp()))); assertThat(json.severity).isEqualTo("WARN"); assertThat(json.logger).isEqualTo("the.logger"); assertThat(json.message).isEqualTo("the message"); assertThat(json.stacktrace).isNull(); assertThat(json.fromMdc).isNull(); } @Test public void test_log_with_MDC() { try { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]); MDC.put("fromMdc", "foo"); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.fromMdc).isEqualTo("foo"); } finally { MDC.clear(); } } private static class JsonLog { private String process; private String timestamp; private String severity; private String logger; private String message; private String fromMdc; private String[] stacktrace; private String nodename; } }
7,062
41.806061
169
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/PatternLayoutEncoderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; public class PatternLayoutEncoderTest { PatternLayoutEncoder underTest = new PatternLayoutEncoder(); @Before public void before() { underTest.start(); } @Test public void start_should_initialize_escaped_message_converter() { assertThat(underTest.getLayout()) .isInstanceOf(ch.qos.logback.classic.PatternLayout.class); assertThat(((ch.qos.logback.classic.PatternLayout) underTest.getLayout()).getDefaultConverterMap()) .contains( entry("m", EscapedMessageConverter.class.getName()), entry("msg", EscapedMessageConverter.class.getName()), entry("message", EscapedMessageConverter.class.getName())); } }
1,708
33.18
103
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/logging/TestILoggingEvent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.LoggerContextVO; import java.util.List; import java.util.Map; import org.slf4j.Marker; import org.slf4j.event.KeyValuePair; public class TestILoggingEvent implements ILoggingEvent { private String formattedMessage; public TestILoggingEvent(String formattedMessage) { this.formattedMessage = formattedMessage; } @Override public String getThreadName() { return null; } @Override public Level getLevel() { return null; } @Override public String getMessage() { return null; } @Override public Object[] getArgumentArray() { return null; } @Override public String getFormattedMessage() { return this.formattedMessage; } @Override public String getLoggerName() { return null; } @Override public LoggerContextVO getLoggerContextVO() { return null; } @Override public IThrowableProxy getThrowableProxy() { return null; } @Override public StackTraceElement[] getCallerData() { return new StackTraceElement[0]; } @Override public boolean hasCallerData() { return false; } @Override public Marker getMarker() { return null; } @Override public List<Marker> getMarkerList() { return null; } @Override public Map<String, String> getMDCPropertyMap() { return null; } @Override public Map<String, String> getMdc() { return null; } @Override public long getTimeStamp() { return 0; } @Override public int getNanoseconds() { return 0; } @Override public long getSequenceNumber() { return 0; } @Override public List<KeyValuePair> getKeyValuePairs() { return null; } @Override public void prepareForDeferredProcessing() { } }
2,765
20.44186
75
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/AllProcessesCommandsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.sharedmemoryfile; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; public class AllProcessesCommandsTest { private static final int PROCESS_NUMBER = 1; private static final byte HARD_STOP = (byte) 0xFF; private static final byte STOP = (byte) 0xD2; private static final byte RESTART = (byte) 0xAA; private static final byte UP = (byte) 0x01; private static final byte OPERATIONAL = (byte) 0x59; private static final byte EMPTY = (byte) 0x00; @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void fail_to_init_if_dir_does_not_exist() throws Exception { File dir = temp.newFolder(); FileUtils.deleteQuietly(dir); try { new AllProcessesCommands(dir); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Not a valid directory: " + dir.getAbsolutePath()); } } @Test public void write_and_read_up() throws IOException { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 0; assertThat(commands.isUp(PROCESS_NUMBER)).isFalse(); assertThat(readByte(commands, offset)).isEqualTo(EMPTY); commands.setUp(PROCESS_NUMBER); assertThat(commands.isUp(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(UP); } } @Test public void write_and_read_operational() throws IOException { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 4; assertThat(commands.isOperational(PROCESS_NUMBER)).isFalse(); assertThat(readByte(commands, offset)).isEqualTo(EMPTY); commands.setOperational(PROCESS_NUMBER); assertThat(commands.isOperational(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(OPERATIONAL); } } @Test public void write_and_read_ping() throws IOException { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 5; assertThat(readLong(commands, offset)).isZero(); long currentTime = System.currentTimeMillis(); commands.ping(PROCESS_NUMBER); assertThat(readLong(commands, offset)).isGreaterThanOrEqualTo(currentTime); } } @Test public void write_and_read_system_info_url() throws IOException { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 13; for (int i = 0; i < 500; i++) { assertThat(readByte(commands, offset + i)).isEqualTo(EMPTY); } commands.setSystemInfoUrl(PROCESS_NUMBER, "jmx:foo"); assertThat(readByte(commands, offset)).isNotEqualTo(EMPTY); assertThat(commands.getSystemInfoUrl(PROCESS_NUMBER)).isEqualTo("jmx:foo"); } } @Test public void ask_for_hard_stop() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 1; assertThat(readByte(commands, offset)).isNotEqualTo(HARD_STOP); assertThat(commands.askedForHardStop(PROCESS_NUMBER)).isFalse(); commands.askForHardStop(PROCESS_NUMBER); assertThat(commands.askedForHardStop(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(HARD_STOP); } } @Test public void ask_for_stop() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 2; assertThat(readByte(commands, offset)).isNotEqualTo(STOP); assertThat(commands.askedForStop(PROCESS_NUMBER)).isFalse(); commands.askForStop(PROCESS_NUMBER); assertThat(commands.askedForStop(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(STOP); } } @Test public void ask_for_restart() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 3; assertThat(readByte(commands, offset)).isNotEqualTo(RESTART); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isFalse(); commands.askForRestart(PROCESS_NUMBER); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(RESTART); } } @Test public void acknowledgeAskForRestart_has_no_effect_when_no_restart_asked() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 3; assertThat(readByte(commands, offset)).isNotEqualTo(RESTART); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isFalse(); commands.acknowledgeAskForRestart(PROCESS_NUMBER); assertThat(readByte(commands, offset)).isNotEqualTo(RESTART); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isFalse(); } } @Test public void acknowledgeAskForRestart_resets_askForRestart_has_no_effect_when_no_restart_asked() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int offset = 3; commands.askForRestart(PROCESS_NUMBER); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isTrue(); assertThat(readByte(commands, offset)).isEqualTo(RESTART); commands.acknowledgeAskForRestart(PROCESS_NUMBER); assertThat(readByte(commands, offset)).isNotEqualTo(RESTART); assertThat(commands.askedForRestart(PROCESS_NUMBER)).isFalse(); } } @Test public void getProcessCommands_fails_if_processNumber_is_less_than_0() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int processNumber = -2; assertThatThrownBy(() -> commands.createAfterClean(processNumber)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process number " + processNumber + " is not valid"); } } @Test public void getProcessCommands_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int processNumber = MAX_PROCESSES + 1; assertThatThrownBy(() -> commands.createAfterClean(processNumber)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process number " + processNumber + " is not valid"); } } @Test public void clean_cleans_sharedMemory_of_any_process_less_than_MAX_PROCESSES() throws IOException { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { for (int i = 0; i < MAX_PROCESSES; i++) { commands.create(i).setUp(); } commands.clean(); for (int i = 0; i < MAX_PROCESSES; i++) { assertThat(commands.create(i).isUp()).isFalse(); } } } private byte readByte(AllProcessesCommands commands, int offset) { return commands.mappedByteBuffer.get(commands.offset(PROCESS_NUMBER) + offset); } private long readLong(AllProcessesCommands commands, int offset) { return commands.mappedByteBuffer.getLong(offset + commands.offset(PROCESS_NUMBER)); } }
8,328
35.213043
116
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommandsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.sharedmemoryfile; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.assertj.core.api.ThrowableAssert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; public class DefaultProcessCommandsTest { private static final int PROCESS_NUMBER = 1; @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void fail_to_init_if_dir_does_not_exist() throws Exception { File dir = temp.newFolder(); FileUtils.deleteQuietly(dir); try { DefaultProcessCommands.main(dir, PROCESS_NUMBER); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Not a valid directory: " + dir.getAbsolutePath()); } } @Test public void main_clears_the_memory_space_of_the_specified_process_number() throws IOException { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { commands.setUp(); commands.setHttpUrl("bla"); commands.setOperational(); } try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { assertThat(commands.isUp()).isFalse(); assertThat(commands.getHttpUrl()).isEmpty(); assertThat(commands.isOperational()).isFalse(); } } @Test public void secondary_does_not_clear_the_memory_space_of_the_specified_process_number() throws IOException { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { commands.setUp(); commands.setHttpUrl("bla"); commands.setOperational(); } try (DefaultProcessCommands commands = DefaultProcessCommands.secondary(dir, PROCESS_NUMBER)) { assertThat(commands.isUp()).isTrue(); assertThat(commands.getHttpUrl()).isEqualTo("bla"); assertThat(commands.isOperational()).isTrue(); } } @Test public void child_process_update_the_mapped_memory() throws Exception { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { assertThat(commands.isUp()).isFalse(); commands.setUp(); assertThat(commands.isUp()).isTrue(); } } @Test public void reset_clears_only_the_memory_space_of_specified_process_number() throws IOException { File dir = temp.newFolder(); try (AllProcessesCommands commands = new AllProcessesCommands(dir)) { for (int i = 0; i < MAX_PROCESSES; i++) { commands.setOperational(i); commands.setUp(i); } int resetProcess = 3; DefaultProcessCommands.reset(dir, resetProcess); for (int i = 0; i < MAX_PROCESSES; i++) { assertThat(commands.isOperational(i)).isEqualTo(i != resetProcess); assertThat(commands.isUp(i)).isEqualTo(i != resetProcess); } } } @Test public void ask_for_stop() throws Exception { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { assertThat(commands.askedForHardStop()).isFalse(); commands.askForHardStop(); assertThat(commands.askedForHardStop()).isTrue(); } } @Test public void ask_for_restart() throws Exception { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { assertThat(commands.askedForRestart()).isFalse(); commands.askForRestart(); assertThat(commands.askedForRestart()).isTrue(); } } @Test public void acknowledgeAskForRestart_has_no_effect_when_no_restart_asked() throws Exception { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { assertThat(commands.askedForRestart()).isFalse(); commands.acknowledgeAskForRestart(); assertThat(commands.askedForRestart()).isFalse(); } } @Test public void acknowledgeAskForRestart_resets_askForRestart_has_no_effect_when_no_restart_asked() throws Exception { File dir = temp.newFolder(); try (DefaultProcessCommands commands = DefaultProcessCommands.main(dir, PROCESS_NUMBER)) { commands.askForRestart(); assertThat(commands.askedForRestart()).isTrue(); commands.acknowledgeAskForRestart(); assertThat(commands.askedForRestart()).isFalse(); } } @Test public void main_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; expectProcessNumberNoValidIAE(() -> { try ( DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber);) { } }, processNumber); } @Test public void main_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; expectProcessNumberNoValidIAE(() -> { try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { } }, processNumber); } @Test public void main_fails_if_processNumber_is_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES; expectProcessNumberNoValidIAE(() -> { try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { } }, processNumber); } @Test public void secondary_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.secondary(temp.newFolder(), processNumber), processNumber); } @Test public void secondary_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; expectProcessNumberNoValidIAE(() -> { try (DefaultProcessCommands secondary = DefaultProcessCommands.secondary(temp.newFolder(), processNumber)) { } }, processNumber); } @Test public void reset_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.reset(temp.newFolder(), processNumber), processNumber); } @Test public void reset_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.reset(temp.newFolder(), processNumber), processNumber); } private void expectProcessNumberNoValidIAE(ThrowableAssert.ThrowingCallable callback, int processNumber) { assertThatThrownBy(callback) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process number " + processNumber + " is not valid"); } }
7,886
31.8625
122
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/systeminfo/BaseSectionMBeanTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.lang.management.ManagementFactory; import javax.annotation.CheckForNull; import javax.management.InstanceNotFoundException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.Test; import org.sonar.process.jmx.FakeMBean; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import static org.assertj.core.api.Assertions.assertThat; public class BaseSectionMBeanTest { private static final String EXPECTED_NAME = "SonarQube:name=FakeName"; private final FakeBaseSectionMBean underTest = new FakeBaseSectionMBean(); @Test public void verify_mbean() throws Exception { assertThat(lookupMBean()).isNull(); underTest.start(); assertThat(lookupMBean()).isNotNull(); underTest.stop(); assertThat(lookupMBean()).isNull(); assertThat(underTest.name()).isEqualTo("FakeName"); assertThat(underTest.toProtobuf()).isNotNull(); } @CheckForNull private ObjectInstance lookupMBean() throws Exception { try { return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(EXPECTED_NAME)); } catch (InstanceNotFoundException e) { return null; } } private static class FakeBaseSectionMBean extends BaseSectionMBean implements FakeMBean { @Override protected String name() { return "FakeName"; } @Override public Section toProtobuf() { return Section.newBuilder().build(); } @Override public void foo() { // nothing to do } } }
2,423
29.3
105
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/systeminfo/JvmPropertiesSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.assertj.core.api.Assertions.assertThat; public class JvmPropertiesSectionTest { private JvmPropertiesSection underTest = new JvmPropertiesSection("Web JVM Properties"); @Test public void name_is_not_empty() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Web JVM Properties"); } @Test public void system_properties_are_returned_in_alphabetical_order() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); List<String> keys = section.getAttributesList() .stream() .map(ProtobufSystemInfo.Attribute::getKey) .toList(); assertThat(keys).contains("java.vm.vendor", "os.name"); List<String> sortedKeys = new ArrayList<>(keys); Collections.sort(sortedKeys); assertThat(sortedKeys).isEqualTo(keys); } }
1,852
33.314815
90
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/systeminfo/JvmStateSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.lang.management.MemoryMXBean; import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JvmStateSectionTest { private static final String PROCESS_NAME = "the process name"; @Test public void toSystemInfoSection() { JvmStateSection underTest = new JvmStateSection(PROCESS_NAME); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getName()).isEqualTo(PROCESS_NAME); assertThat(section.getAttributesCount()).isPositive(); assertThat(section.getAttributesList()).extracting("key") .contains( "Max Memory (MB)", "Free Memory (MB)", "Heap Max (MB)", "System Load Average", "Threads"); } @Test public void should_hide_attributes_without_values() { MemoryMXBean memoryBean = mock(MemoryMXBean.class, Mockito.RETURNS_DEEP_STUBS); when(memoryBean.getHeapMemoryUsage().getCommitted()).thenReturn(-1L); JvmStateSection underTest = new JvmStateSection(PROCESS_NAME); ProtobufSystemInfo.Section section = underTest.toProtobuf(memoryBean); assertThat(section.getAttributesList()) .extracting("key") .isNotEmpty() .doesNotContain("Heap Committed (MB)"); } }
2,285
35.285714
83
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/systeminfo/SystemInfoUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.util.Collection; import java.util.List; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class SystemInfoUtilsTest { @Test public void test_setAttribute_with_boolean_parameter() { Section.Builder builder = Section.newBuilder(); SystemInfoUtils.setAttribute(builder, "isNull", (Boolean)null); SystemInfoUtils.setAttribute(builder, "isTrue", true); SystemInfoUtils.setAttribute(builder, "isFalse", false); Section section = builder.build(); assertThat(SystemInfoUtils.attribute(section, "isNull")).isNull(); assertThat(SystemInfoUtils.attribute(section, "isTrue").getBooleanValue()).isTrue(); assertThat(SystemInfoUtils.attribute(section, "isFalse").getBooleanValue()).isFalse(); } @Test public void test_order() { Collection<Section> sections = asList( newSection("end2"), newSection("bar"), newSection("end1"), newSection("foo")); List<String> ordered = SystemInfoUtils.order(sections, "foo", "bar").stream() .map(Section::getName) .toList(); assertThat(ordered).isEqualTo(asList("foo", "bar", "end1", "end2")); } private static Section newSection(String name) { return Section.newBuilder().setName(name).build(); } }
2,270
35.047619
90
java
sonarqube
sonarqube-master/server/sonar-process/src/test/java/org/sonar/process/test/StandardProcess.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import org.sonar.process.Lifecycle.State; import org.sonar.process.Monitored; import org.sonar.process.ProcessEntryPoint; import static com.google.common.base.Preconditions.checkState; public class StandardProcess implements Monitored { private AtomicReference<State> state = new AtomicReference<>(State.INIT); private volatile boolean stopped = false; private volatile boolean hardStopped = false; private CountDownLatch stopLatch = new CountDownLatch(1); private final Thread daemon = new Thread() { @Override public void run() { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { interrupt(); } } }; /** * Blocks until started() */ @Override public void start() { state.compareAndSet(State.INIT, State.STARTING); daemon.start(); state.compareAndSet(State.STARTING, State.STARTED); } @Override public Status getStatus() { return state.get() == State.STARTED ? Status.OPERATIONAL : Status.DOWN; } @Override public void awaitStop() { try { stopLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Override public void stop() { checkState(state.compareAndSet(State.STARTED, State.STOPPING), "not started?!! what?"); daemon.interrupt(); stopped = true; state.compareAndSet(State.STOPPING, State.STOPPED); stopLatch.countDown(); } /** * Blocks until stopped */ @Override public void hardStop() { state.set(State.HARD_STOPPING); daemon.interrupt(); hardStopped = true; state.compareAndSet(State.HARD_STOPPING, State.STOPPED); stopLatch.countDown(); } public State getState() { return state.get(); } public boolean wasStopped() { return stopped; } public boolean wasHardStopped() { return hardStopped; } public static void main(String[] args) { ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args); entryPoint.launch(new StandardProcess()); System.exit(0); } }
3,044
26.432432
91
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/component/index/EntityDefinitionIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import java.util.Arrays; import java.util.Collection; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ProjectData; import org.sonar.db.entity.EntityDto; import org.sonar.db.es.EsQueueDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import org.sonar.server.es.Indexers; import org.sonar.server.es.IndexingResult; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_NAME; import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT; import static org.sonar.server.es.Indexers.EntityEvent.CREATION; import static org.sonar.server.es.Indexers.EntityEvent.DELETION; import static org.sonar.server.es.Indexers.EntityEvent.PERMISSION_CHANGE; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_TAGS_UPDATE; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER; public class EntityDefinitionIndexerIT { private System2 system2 = System2.INSTANCE; @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(system2); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private EntityDefinitionIndexer underTest = new EntityDefinitionIndexer(db.getDbClient(), es.client()); @Test public void test_getIndexTypes() { assertThat(underTest.getIndexTypes()).containsExactly(TYPE_COMPONENT); } @Test public void indexOnStartup_does_nothing_if_no_projects() { underTest.indexOnStartup(emptySet()); assertThatIndexHasSize(0); } @Test public void indexOnStartup_indexes_all_components() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project1, project2); } @Test public void indexOAll_indexes_all_components() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); underTest.indexAll(); assertThatIndexContainsOnly(project1, project2); } @Test public void map_fields() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project); ComponentDoc doc = es.getDocuments(TYPE_COMPONENT, ComponentDoc.class).get(0); assertThat(doc.getId()).isEqualTo(project.getUuid()); assertThat(doc.getKey()).isEqualTo(project.getKey()); assertThat(doc.getName()).isEqualTo(project.getName()); } @Test public void indexOnStartup_does_not_index_non_main_branches() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo")); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project); } @Test public void indexOnAnalysis_indexes_project() { ProjectData project = db.components().insertPrivateProject(); underTest.indexOnAnalysis(project.getMainBranchComponent().uuid()); assertThatIndexContainsOnly(project.getProjectDto()); } @Test public void indexOnAnalysis_indexes_new_components() { ProjectData projectData = db.components().insertPrivateProject(); ProjectDto project = projectData.getProjectDto(); underTest.indexOnAnalysis(projectData.getMainBranchComponent().uuid()); assertThatIndexContainsOnly(project); underTest.indexOnAnalysis(projectData.getMainBranchComponent().uuid()); assertThatIndexContainsOnly(project); } @Test public void indexOnAnalysis_does_not_index_non_main_branches() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo")); underTest.indexOnAnalysis(branch.getUuid()); assertThatIndexHasSize(0); } @Test public void do_not_update_index_on_project_tag_update() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); indexProject(project, PROJECT_TAGS_UPDATE); assertThatIndexHasSize(0); } @Test public void do_not_update_index_on_permission_change() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); indexProject(project, PERMISSION_CHANGE); assertThatIndexHasSize(0); } @Test public void update_index_on_project_creation() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); IndexingResult result = indexProject(project, CREATION); assertThatIndexContainsOnly(project); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); } @Test public void delete_project() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); indexProject(project, CREATION); assertThatIndexHasSize(1); db.getDbClient().purgeDao().deleteProject(db.getSession(), project.getUuid(), PROJECT, project.getName(), project.getKey()); indexProject(project, DELETION); assertThatIndexHasSize(0); } @Test public void indexOnAnalysis_updates_index_on_changes() { ProjectData project = db.components().insertPrivateProject(); ProjectDto projectDto = project.getProjectDto(); underTest.indexOnAnalysis(project.getMainBranchDto().getUuid()); assertThatEntityHasName(projectDto.getUuid(), projectDto.getName()); // modify projectDto.setName("NewName"); db.getDbClient().projectDao().update(dbSession, projectDto); db.commit(); // verify that index is updated underTest.indexOnAnalysis(project.getMainBranchDto().getUuid()); assertThatIndexContainsOnly(projectDto.getUuid()); assertThatEntityHasName(projectDto.getUuid(), "NewName"); } @Test public void errors_during_indexing_are_recovered() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); es.lockWrites(TYPE_COMPONENT); IndexingResult result = indexProject(project1, CREATION); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isOne(); // index is still read-only, fail to recover result = recover(); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isOne(); assertThat(es.countDocuments(TYPE_COMPONENT)).isZero(); es.unlockWrites(TYPE_COMPONENT); result = recover(); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isZero(); assertThatIndexContainsOnly(project1); } private IndexingResult indexProject(ProjectDto project, Indexers.EntityEvent cause) { DbSession dbSession = db.getSession(); Collection<EsQueueDto> items = underTest.prepareForRecoveryOnEntityEvent(dbSession, singletonList(project.getUuid()), cause); dbSession.commit(); return underTest.index(dbSession, items); } private IndexingResult recover() { Collection<EsQueueDto> items = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), System.currentTimeMillis() + 1_000L, 10); return underTest.index(db.getSession(), items); } private void assertThatIndexHasSize(int expectedSize) { assertThat(es.countDocuments(TYPE_COMPONENT)).isEqualTo(expectedSize); } private void assertThatIndexContainsOnly(EntityDto... expectedEntities) { assertThat(es.getIds(TYPE_COMPONENT)).containsExactlyInAnyOrder( Arrays.stream(expectedEntities).map(EntityDto::getUuid).toArray(String[]::new)); } private void assertThatIndexContainsOnly(String uuid) { assertThat(es.getIds(TYPE_COMPONENT)).containsExactlyInAnyOrder(uuid); } private void assertThatEntityHasName(String uuid, String expectedName) { SearchHit[] hits = es.client() .search(EsClient.prepareSearch(TYPE_COMPONENT.getMainType()) .source(new SearchSourceBuilder() .query(matchQuery(SORTABLE_ANALYZER.subField(FIELD_NAME), expectedName)))) .getHits() .getHits(); assertThat(hits) .extracting(SearchHit::getId) .contains(uuid); } }
9,711
34.316364
141
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/es/BulkIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.db.DbTester; import org.sonar.server.es.BulkIndexer.Size; import org.sonar.server.es.newindex.FakeIndexDefinition; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.es.newindex.FakeIndexDefinition.EXCPECTED_TYPE_FAKE; import static org.sonar.server.es.newindex.FakeIndexDefinition.INDEX; import static org.sonar.server.es.newindex.FakeIndexDefinition.TYPE_FAKE; public class BulkIndexerIT { private final TestSystem2 testSystem2 = new TestSystem2().setNow(1_000L); @Rule public EsTester es = EsTester.createCustom(new FakeIndexDefinition().setReplicas(1)); @Rule public DbTester dbTester = DbTester.create(testSystem2); @Rule public LogTester logTester = new LogTester(); @Test public void index_nothing() { BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR); indexer.start(); indexer.stop(); assertThat(count()).isZero(); } @Test public void index_documents() { BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR); indexer.start(); indexer.add(newIndexRequest(42)); indexer.add(newIndexRequest(78)); // request is not sent yet assertThat(count()).isZero(); // send remaining requests indexer.stop(); assertThat(count()).isEqualTo(2); } @Test public void large_indexing() { // index has one replica assertThat(replicas()).isOne(); BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.LARGE); indexer.start(); // replicas are temporarily disabled assertThat(replicas()).isZero(); for (int i = 0; i < 10; i++) { indexer.add(newIndexRequest(i)); } IndexingResult result = indexer.stop(); assertThat(result.isSuccess()).isTrue(); assertThat(result.getSuccess()).isEqualTo(10); assertThat(result.getFailures()).isZero(); assertThat(result.getTotal()).isEqualTo(10); assertThat(count()).isEqualTo(10); // replicas are re-enabled assertThat(replicas()).isOne(); } @Test public void bulk_delete() { int max = 500; int removeFrom = 200; FakeDoc[] docs = new FakeDoc[max]; for (int i = 0; i < max; i++) { docs[i] = FakeIndexDefinition.newDoc(i); } es.putDocuments(TYPE_FAKE, docs); assertThat(count()).isEqualTo(max); SearchRequest req = EsClient.prepareSearch(TYPE_FAKE) .source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery(FakeIndexDefinition.INT_FIELD).gte(removeFrom))); BulkIndexer.delete(es.client(), TYPE_FAKE, req); assertThat(count()).isEqualTo(removeFrom); } @Test public void listener_is_called_on_successful_requests() { FakeListener listener = new FakeListener(); BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.addDeletion(TYPE_FAKE, "foo"); indexer.stop(); assertThat(listener.calledDocIds) .containsExactlyInAnyOrder(newDocId(EXCPECTED_TYPE_FAKE, "foo")); assertThat(listener.calledResult.getSuccess()).isOne(); assertThat(listener.calledResult.getTotal()).isOne(); } @Test public void listener_is_called_even_if_deleting_a_doc_that_does_not_exist() { FakeListener listener = new FakeListener(); BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.add(newIndexRequestWithDocId("foo")); indexer.add(newIndexRequestWithDocId("bar")); indexer.stop(); assertThat(listener.calledDocIds) .containsExactlyInAnyOrder(newDocId(EXCPECTED_TYPE_FAKE, "foo"), newDocId(EXCPECTED_TYPE_FAKE, "bar")); assertThat(listener.calledResult.getSuccess()).isEqualTo(2); assertThat(listener.calledResult.getTotal()).isEqualTo(2); } @Test public void listener_is_not_called_with_errors() { FakeListener listener = new FakeListener(); BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.add(newIndexRequestWithDocId("foo")); indexer.add(new IndexRequest("index_does_not_exist").id("bar").source(emptyMap())); indexer.stop(); assertThat(listener.calledDocIds).containsExactly(newDocId(EXCPECTED_TYPE_FAKE, "foo")); assertThat(listener.calledResult.getSuccess()).isOne(); assertThat(listener.calledResult.getTotal()).isEqualTo(2); } @Test public void log_requests_when_TRACE_level_is_enabled() { logTester.setLevel(LoggerLevel.TRACE); BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR, new FakeListener()); indexer.start(); indexer.add(newIndexRequestWithDocId("foo")); indexer.addDeletion(TYPE_FAKE, "foo"); indexer.add(newIndexRequestWithDocId("bar")); indexer.stop(); assertThat(logTester.logs(Level.TRACE) .stream() .filter(log -> log.contains("Bulk[2 index requests on fakes/_doc, 1 delete requests on fakes/_doc]")) .count()).isNotZero(); } private static class FakeListener implements IndexingListener { private final List<DocId> calledDocIds = new ArrayList<>(); private IndexingResult calledResult; @Override public void onSuccess(List<DocId> docIds) { calledDocIds.addAll(docIds); } @Override public void onFinish(IndexingResult result) { calledResult = result; } } private long count() { return es.countDocuments(IndexType.main(Index.simple("fakes"), "fake")); } private int replicas() { try { GetSettingsResponse settingsResp = es.client().nativeClient().indices() .getSettings(new GetSettingsRequest().indices(INDEX), RequestOptions.DEFAULT); return Integer.parseInt(settingsResp.getSetting(INDEX, IndexMetadata.SETTING_NUMBER_OF_REPLICAS)); } catch (IOException e) { throw new IllegalStateException("Could not get index settings", e); } } private IndexRequest newIndexRequest(int intField) { return new IndexRequest(INDEX) .source(Map.of(FakeIndexDefinition.INT_FIELD, intField)); } private IndexRequest newIndexRequestWithDocId(String id) { return new IndexRequest(INDEX) .id(id) .source(Map.of(FakeIndexDefinition.INT_FIELD, 42)); } private static DocId newDocId(IndexType.IndexMainType mainType, String id) { return new DocId(TYPE_FAKE.getIndex().getName(), mainType.getType(), id); } }
8,115
34.286957
120
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/es/OneToManyResilientIndexingListenerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; import org.sonar.server.component.index.ComponentIndexDefinition; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; public class OneToManyResilientIndexingListenerIT { @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(); @Test public void ES_QUEUE_rows_are_deleted_when_all_docs_are_successfully_indexed() { EsQueueDto item1 = insertInQueue(TYPE_ISSUE, "P1"); EsQueueDto item2 = insertInQueue(TYPE_ISSUE, "P2"); EsQueueDto outOfScopeItem = insertInQueue(ComponentIndexDefinition.TYPE_COMPONENT, "P1"); db.commit(); // does not contain outOfScopeItem IndexingListener underTest = newListener(asList(item1, item2)); DocId issue1 = newDocId(TYPE_ISSUE, "I1"); DocId issue2 = newDocId(TYPE_ISSUE, "I2"); underTest.onSuccess(asList(issue1, issue2)); assertThatEsTableContainsOnly(item1, item2, outOfScopeItem); // onFinish deletes all items IndexingResult result = new IndexingResult(); result.incrementSuccess().incrementRequests(); result.incrementSuccess().incrementRequests(); underTest.onFinish(result); assertThatEsTableContainsOnly(outOfScopeItem); } @Test public void ES_QUEUE_rows_are_not_deleted_on_partial_error() { EsQueueDto item1 = insertInQueue(TYPE_ISSUE, "P1"); EsQueueDto item2 = insertInQueue(TYPE_ISSUE, "P2"); EsQueueDto outOfScopeItem = insertInQueue(ComponentIndexDefinition.TYPE_COMPONENT, "P1"); db.commit(); // does not contain outOfScopeItem IndexingListener underTest = newListener(asList(item1, item2)); DocId issue1 = newDocId(TYPE_ISSUE, "I1"); DocId issue2 = newDocId(TYPE_ISSUE, "I2"); underTest.onSuccess(asList(issue1, issue2)); assertThatEsTableContainsOnly(item1, item2, outOfScopeItem); // one failure among the 2 indexing requests of issues IndexingResult result = new IndexingResult(); result.incrementSuccess().incrementRequests(); result.incrementRequests(); underTest.onFinish(result); assertThatEsTableContainsOnly(item1, item2, outOfScopeItem); } private static DocId newDocId(IndexType.IndexRelationType indexType, String id) { IndexType.IndexMainType mainType = indexType.getMainType(); return new DocId(mainType.getIndex().getName(), mainType.getType(), id); } private IndexingListener newListener(Collection<EsQueueDto> items) { return new OneToManyResilientIndexingListener(db.getDbClient(), db.getSession(), items); } private EsQueueDto insertInQueue(IndexType indexType, String id) { EsQueueDto item = EsQueueDto.create(indexType.format(), id); db.getDbClient().esQueueDao().insert(db.getSession(), singletonList(item)); return item; } private void assertThatEsTableContainsOnly(EsQueueDto... expected) { try (DbSession otherSession = db.getDbClient().openSession(false)) { List<String> uuidsInDb = db.getDbClient().esQueueDao().selectForRecovery(otherSession, Long.MAX_VALUE, 10) .stream().map(EsQueueDto::getUuid).collect(toList()); String[] expectedUuids = Arrays.stream(expected).map(EsQueueDto::getUuid).toArray(String[]::new); assertThat(uuidsInDb).containsExactlyInAnyOrder(expectedUuids); } } }
4,544
37.846154
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/es/OneToOneResilientIndexingListenerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; public class OneToOneResilientIndexingListenerIT { @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(); @Test public void onSuccess_deletes_rows_from_ES_QUEUE_table() { EsQueueDto item1 = insertInQueue(TYPE_ISSUE, "foo"); EsQueueDto item2 = insertInQueue(TYPE_ISSUE, "bar"); EsQueueDto item3 = insertInQueue(TYPE_ISSUE, "baz"); db.commit(); IndexingListener underTest = newListener(asList(item1, item2, item3)); underTest.onSuccess(emptyList()); assertThatEsTableContainsOnly(item1, item2, item3); underTest.onSuccess(asList(toDocId(item1), toDocId(item3))); assertThatEsTableContainsOnly(item2); // onFinish does nothing underTest.onFinish(new IndexingResult()); assertThatEsTableContainsOnly(item2); } /** * ES_QUEUE can contain multiple times the same document, for instance * when an issue has been updated multiple times in a row without * being successfully indexed. * Elasticsearch response does not make difference between the different * occurrences (and nevertheless it would be useless). So all the * occurrences are marked as successfully indexed if a single request * passes. */ @Test public void onSuccess_deletes_all_the_rows_with_same_doc_id() { EsQueueDto item1 = insertInQueue(TYPE_ISSUE, "foo"); // same id as item1 EsQueueDto item2 = insertInQueue(TYPE_ISSUE, item1.getDocId()); EsQueueDto item3 = insertInQueue(TYPE_ISSUE, "bar"); db.commit(); IndexingListener underTest = newListener(asList(item1, item2, item3)); underTest.onSuccess(asList(toDocId(item1))); assertThatEsTableContainsOnly(item3); } private static DocId toDocId(EsQueueDto dto) { IndexType.SimpleIndexMainType mainType = IndexType.parseMainType(dto.getDocType()); return new DocId(mainType.getIndex(), mainType.getType(), dto.getDocId()); } private IndexingListener newListener(Collection<EsQueueDto> items) { return new OneToOneResilientIndexingListener(db.getDbClient(), db.getSession(), items); } private EsQueueDto insertInQueue(IndexType indexType, String id) { EsQueueDto item = EsQueueDto.create(indexType.format(), id); db.getDbClient().esQueueDao().insert(db.getSession(), singletonList(item)); return item; } private void assertThatEsTableContainsOnly(EsQueueDto... expected) { try (DbSession otherSession = db.getDbClient().openSession(false)) { List<String> uuidsInDb = db.getDbClient().esQueueDao().selectForRecovery(otherSession, Long.MAX_VALUE, 10) .stream().map(EsQueueDto::getUuid).collect(toList()); String[] expectedUuids = Arrays.stream(expected).map(EsQueueDto::getUuid).toArray(String[]::new); assertThat(uuidsInDb).containsExactlyInAnyOrder(expectedUuids); } } }
4,241
36.875
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/es/metadata/MetadataIndexIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.metadata; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Locale; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.server.es.EsTester; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.newindex.FakeIndexDefinition; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; @RunWith(DataProviderRunner.class) public class MetadataIndexIT { @Rule public EsTester es = EsTester.createCustom(new MetadataIndexDefinitionBridge(), new FakeIndexDefinition()); private final MetadataIndex underTest = new MetadataIndexImpl(es.client()); private final String indexName = randomAlphabetic(20).toLowerCase(Locale.ENGLISH); private final Index index = new Random().nextBoolean() ? Index.simple(indexName) : Index.withRelations(indexName); @Test @UseDataProvider("mainOrRelationType") public void type_should_be_not_initialized_by_default(IndexType indexType) { assertThat(underTest.getInitialized(indexType)).isFalse(); } @Test @UseDataProvider("mainOrRelationType") public void type_should_be_initialized_after_explicitly_set_to_initialized(IndexType indexType) { underTest.setInitialized(indexType, true); assertThat(underTest.getInitialized(indexType)).isTrue(); } @DataProvider public static Object[][] mainOrRelationType() { IndexMainType mainType = IndexType.main(Index.withRelations("examples"), "example"); return new Object[][] { {mainType}, {IndexType.relation(mainType, "doo")} }; } @Test public void hash_should_be_empty_by_default() { assertThat(underTest.getHash(index)).isEmpty(); } @Test public void hash_should_be_able_to_be_automatically_set() { String hash = randomAlphanumeric(20); underTest.setHash(index, hash); assertThat(underTest.getHash(index)).hasValue(hash); } @Test public void database_metadata_are_empty_if_absent_from_index() { assertThat(underTest.getDbVendor()).isNotPresent(); } @Test public void database_metadata_are_present_from_index() { underTest.setDbMetadata("postgres"); assertThat(underTest.getDbVendor()).hasValue("postgres"); } }
3,440
34.84375
116
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/favorite/FavoriteUpdaterIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.favorite; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.property.PropertyQuery; import org.sonar.db.user.UserDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FavoriteUpdaterIT { @Rule public DbTester db = DbTester.create(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private FavoriteUpdater underTest = new FavoriteUpdater(dbClient); @Test public void put_favorite() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(); assertNoFavorite(project, user); underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true); assertFavorite(project, user); } @Test public void do_nothing_when_no_user() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); underTest.add(dbSession, project, null, null,true); assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setEntityUuid(project.getUuid()) .build(), dbSession)).isEmpty(); } @Test public void do_not_add_favorite_when_already_100_favorite_projects() { UserDto user = db.users().insertUser(); IntStream.rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject().getProjectDto(), user.getUuid(), user.getName())); assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .build(), dbSession)).hasSize(100); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); underTest.add(dbSession, project, user.getUuid(), user.getLogin(), false); assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .build(), dbSession)).hasSize(100); } @Test public void do_not_add_favorite_when_already_100_favorite_portfolios() { UserDto user = db.users().insertUser(); IntStream.rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject().getProjectDto(), user.getUuid(), user.getLogin())); assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .build(), dbSession)).hasSize(100); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); underTest.add(dbSession, project, user.getUuid(), user.getLogin(), false); assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .build(), dbSession)).hasSize(100); } @Test public void fail_when_more_than_100_projects_favorites() { UserDto user = db.users().insertUser(); IntStream.rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject().getProjectDto(), user.getUuid(), user.getLogin())); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); assertThatThrownBy(() -> underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("You cannot have more than 100 favorites on components with qualifier 'TRK'"); } @Test public void fail_when_adding_existing_favorite() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(); underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true); assertFavorite(project, user); assertThatThrownBy(() -> underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true)) .isInstanceOf(IllegalArgumentException.class) .hasMessage(String.format("Component '%s' (uuid: %s) is already a favorite", project.getKey(), project.getUuid())); } private void assertFavorite(EntityDto entity, UserDto user) { assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .setEntityUuid(entity.getUuid()) .build(), dbSession)).hasSize(1); } private void assertNoFavorite(EntityDto entity, UserDto user) { assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setUserUuid(user.getUuid()) .setEntityUuid(entity.getUuid()) .build(), dbSession)).isEmpty(); } }
5,504
38.604317
155
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/issue/index/IssueIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import org.assertj.core.api.Assertions; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.resources.Qualifiers; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.es.EsQueueDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueTesting; import org.sonar.db.project.ProjectDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.IndexType; import org.sonar.server.es.Indexers; import org.sonar.server.es.Indexers.EntityEvent; import org.sonar.server.es.IndexingResult; import org.sonar.server.es.StartupIndexer; import org.sonar.server.permission.index.AuthorizationScope; import org.sonar.server.permission.index.IndexPermissions; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.SQCategory; import org.sonar.server.security.SecurityStandards.VulnerabilityProbability; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.server.es.Indexers.BranchEvent.DELETION; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_KEY_UPDATE; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_TAGS_UPDATE; import static org.sonar.server.issue.IssueDocTesting.newDoc; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_POROUS_DEFENSES; public class IssueIndexerIT { @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(); @Rule public LogTester logTester = new LogTester(); private final IssueIndexer underTest = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null); @Test public void getIndexTypes_shouldReturnTypeIssue() { assertThat(underTest.getIndexTypes()).containsExactly(TYPE_ISSUE); } @Test public void getAuthorizationScope_shouldBeProject() { AuthorizationScope scope = underTest.getAuthorizationScope(); assertThat(scope.getIndexType().getIndex()).isEqualTo(IssueIndexDefinition.DESCRIPTOR); assertThat(scope.getIndexType().getType()).isEqualTo(TYPE_AUTHORIZATION); Predicate<IndexPermissions> projectPredicate = scope.getEntityPredicate(); IndexPermissions project = new IndexPermissions("P1", Qualifiers.PROJECT); IndexPermissions file = new IndexPermissions("F1", Qualifiers.FILE); assertThat(projectPredicate.test(project)).isTrue(); assertThat(projectPredicate.test(file)).isFalse(); } @Test public void indexAllIssues_shouldIndexAllIssues() { IssueDto issue1 = db.issues().insert(); IssueDto issue2 = db.issues().insert(); underTest.indexAllIssues(); assertThatIndexHasOnly(issue1, issue2); } @Test public void indexAllIssues_shouldIndexAllIssueFields() { RuleDto rule = db.rules().insert(); ProjectData projectData = db.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo")); ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1")); IssueDto issue = db.issues().insert(rule, project, file); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getId()).isEqualTo(issue.getKey()); assertThat(doc.assigneeUuid()).isEqualTo(issue.getAssigneeUuid()); assertThat(doc.authorLogin()).isEqualTo(issue.getAuthorLogin()); assertThat(doc.componentUuid()).isEqualTo(file.uuid()); assertThat(doc.projectUuid()).isEqualTo(projectData.projectUuid()); assertThat(doc.branchUuid()).isEqualTo(project.uuid()); assertThat(doc.isMainBranch()).isTrue(); assertThat(doc.closeDate()).isEqualTo(issue.getIssueCloseDate()); assertThat(doc.creationDate()).isEqualToIgnoringMillis(issue.getIssueCreationDate()); assertThat(doc.directoryPath()).isEqualTo(dir.path()); assertThat(doc.filePath()).isEqualTo(file.path()); assertThat(doc.scope()).isEqualTo(IssueScope.MAIN); assertThat(doc.language()).isEqualTo(issue.getLanguage()); assertThat(doc.line()).isEqualTo(issue.getLine()); // functional date assertThat(doc.updateDate()).isEqualToIgnoringMillis(new Date(issue.getIssueUpdateTime())); assertThat(doc.getCwe()).containsExactlyInAnyOrder(SecurityStandards.UNKNOWN_STANDARD); assertThat(doc.getOwaspTop10()).isEmpty(); assertThat(doc.getSansTop25()).isEmpty(); assertThat(doc.getSonarSourceSecurityCategory()).isEqualTo(SQCategory.OTHERS); assertThat(doc.getVulnerabilityProbability()).isEqualTo(VulnerabilityProbability.LOW); } @Test public void indexAllIssues_shouldIndexSecurityStandards() { RuleDto rule = db.rules().insert(r -> r.setSecurityStandards(new HashSet<>(Arrays.asList("cwe:123", "owaspTop10:a3", "cwe:863", "owaspAsvs-4.0:2.1.1")))); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo")); ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1")); db.issues().insert(rule, project, file); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getCwe()).containsExactlyInAnyOrder("123", "863"); assertThat(doc.getOwaspTop10()).containsExactlyInAnyOrder("a3"); assertThat(doc.getOwaspAsvs40()).containsExactlyInAnyOrder("2.1.1"); assertThat(doc.getSansTop25()).containsExactlyInAnyOrder(SANS_TOP_25_POROUS_DEFENSES); } @Test public void indexOnStartup_does_not_fail_on_errors_and_does_enable_recovery_mode() { es.lockWrites(TYPE_ISSUE); db.issues().insert(); Set<IndexType> uninitializedIndexTypes = emptySet(); assertThatThrownBy(() -> underTest.indexOnStartup(uninitializedIndexTypes)) .isInstanceOf(IllegalStateException.class) .hasMessage("SYNCHRONOUS StartupIndexer must implement indexOnStartup"); assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); es.unlockWrites(TYPE_ISSUE); } @Test public void indexOnAnalysis_indexes_the_issues_of_project() { RuleDto rule = db.rules().insert(); ComponentDto branchComponent = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(branchComponent)); IssueDto issue = db.issues().insert(rule, branchComponent, file); ComponentDto otherProject = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newFileDto(otherProject)); underTest.indexOnAnalysis(branchComponent.uuid()); assertThatIndexHasOnly(issue); } @Test public void indexOnAnalysis_does_not_delete_orphan_docs() { RuleDto rule = db.rules().insert(); ProjectData projectData = db.components().insertPrivateProject(); ComponentDto file = db.components().insertComponent(newFileDto(projectData.getMainBranchComponent())); IssueDto issue = db.issues().insert(rule, projectData.getMainBranchComponent(), file); // orphan in the project addIssueToIndex(projectData.projectUuid(), projectData.getMainBranchComponent().uuid(), "orphan"); underTest.indexOnAnalysis(projectData.getMainBranchComponent().uuid()); assertThat(es.getDocuments(TYPE_ISSUE)) .extracting(SearchHit::getId) .containsExactlyInAnyOrder(issue.getKey(), "orphan"); } /** * Indexing recovery is handled by Compute Engine, without using * the table es_queue */ @Test public void indexOnAnalysis_does_not_fail_on_errors_and_does_not_enable_recovery_mode() { es.lockWrites(TYPE_ISSUE); IssueDto issue = db.issues().insert(); String projectUuid = issue.getProjectUuid(); assertThatThrownBy(() -> underTest.indexOnAnalysis(projectUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unrecoverable indexation failures: 1 errors among 1 requests. Check Elasticsearch logs for further details."); assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); es.unlockWrites(TYPE_ISSUE); } @Test public void index_is_not_updated_when_updating_project_key() { // issue is inserted to verify that indexing of project is not triggered IssueDto issue = db.issues().insert(); IndexingResult result = indexProject(issue.getProjectUuid(), PROJECT_KEY_UPDATE); assertThat(result.getTotal()).isZero(); assertThatIndexHasSize(0); } @Test public void index_is_not_updated_when_updating_tags() { // issue is inserted to verify that indexing of project is not triggered IssueDto issue = db.issues().insert(); IndexingResult result = indexProject(issue.getProjectUuid(), PROJECT_TAGS_UPDATE); assertThat(result.getTotal()).isZero(); assertThatIndexHasSize(0); } @Test public void index_is_updated_when_deleting_branch() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch1 = db.components().insertProjectBranch(project); BranchDto branch2 = db.components().insertProjectBranch(project); addIssueToIndex(project.getUuid(), branch1.getUuid(), "I1"); addIssueToIndex(project.getUuid(), branch1.getUuid(), "I2"); addIssueToIndex(project.getUuid(), branch2.getUuid(), "I3"); assertThatIndexHasSize(3); IndexingResult result = indexBranch(branch1.getUuid(), DELETION); assertThat(result.getTotal()).isEqualTo(2); assertThat(result.getSuccess()).isEqualTo(2); assertThatIndexHasOnly("I3"); } @Test public void index_is_updated_when_deleting_project() { BranchDto branch = db.components().insertPrivateProject().getMainBranchDto(); addIssueToIndex(branch.getProjectUuid(), branch.getUuid(), "I1"); assertThatIndexHasSize(1); IndexingResult result = indexProject(branch.getProjectUuid(), EntityEvent.DELETION); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); assertThatIndexHasSize(0); } @Test public void errors_during_project_deletion_are_recovered() { addIssueToIndex("P1", "B1", "I1"); addIssueToIndex("P1", "B2", "I2"); assertThatIndexHasSize(2); es.lockWrites(TYPE_ISSUE); IndexingResult result = indexProject("P1", EntityEvent.DELETION); assertThat(result.getTotal()).isEqualTo(2); assertThat(result.getFailures()).isEqualTo(2); // index is still read-only, fail to recover result = recover(); assertThat(result.getTotal()).isEqualTo(2); assertThat(result.getFailures()).isEqualTo(2); assertThatIndexHasSize(2); es.unlockWrites(TYPE_ISSUE); result = recover(); assertThat(result.getTotal()).isEqualTo(2); assertThat(result.getFailures()).isZero(); assertThatIndexHasSize(0); } @Test public void commitAndIndexIssues_commits_db_transaction_and_adds_issues_to_index() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); // insert issues in db without committing IssueDto issue1 = IssueTesting.newIssue(rule, project, file); IssueDto issue2 = IssueTesting.newIssue(rule, project, file); db.getDbClient().issueDao().insert(db.getSession(), issue1, issue2); underTest.commitAndIndexIssues(db.getSession(), asList(issue1, issue2)); // issues are persisted and indexed assertThatIndexHasOnly(issue1, issue2); assertThatDbHasOnly(issue1, issue2); assertThatEsQueueTableHasSize(0); } @Test public void commitAndIndexIssues_removes_issue_from_index_if_it_does_not_exist_in_db() { IssueDto issue1 = new IssueDto().setKee("I1").setProjectUuid("B1"); addIssueToIndex("B1", issue1.getProjectUuid(), issue1.getKey()); IssueDto issue2 = db.issues().insert(); underTest.commitAndIndexIssues(db.getSession(), asList(issue1, issue2)); // issue1 is removed from index, issue2 is persisted and indexed assertThatIndexHasOnly(issue2); assertThatDbHasOnly(issue2); assertThatEsQueueTableHasSize(0); } @Test public void indexing_errors_during_commitAndIndexIssues_are_recovered() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); // insert issues in db without committing IssueDto issue1 = IssueTesting.newIssue(rule, project, file); IssueDto issue2 = IssueTesting.newIssue(rule, project, file); db.getDbClient().issueDao().insert(db.getSession(), issue1, issue2); // index is read-only es.lockWrites(TYPE_ISSUE); underTest.commitAndIndexIssues(db.getSession(), asList(issue1, issue2)); // issues are persisted but not indexed assertThatIndexHasSize(0); assertThatDbHasOnly(issue1, issue2); assertThatEsQueueTableHasSize(2); // re-enable write on index es.unlockWrites(TYPE_ISSUE); // emulate the recovery daemon IndexingResult result = recover(); assertThatEsQueueTableHasSize(0); assertThatIndexHasOnly(issue1, issue2); assertThat(result.isSuccess()).isTrue(); assertThat(result.getTotal()).isEqualTo(2L); } @Test public void recovery_does_not_fail_if_unsupported_docIdType() { EsQueueDto item = EsQueueDto.create(TYPE_ISSUE.format(), "I1", "unknown", "P1"); db.getDbClient().esQueueDao().insert(db.getSession(), item); db.commit(); recover(); assertThat(logTester.logs(Level.ERROR)) .filteredOn(l -> l.contains("Unsupported es_queue.doc_id_type for issues. Manual fix is required: ")) .hasSize(1); assertThatEsQueueTableHasSize(1); } @Test public void indexing_recovers_multiple_errors_on_the_same_issue() { es.lockWrites(TYPE_ISSUE); IssueDto issue = db.issues().insert(); // three changes on the same issue underTest.commitAndIndexIssues(db.getSession(), singletonList(issue)); underTest.commitAndIndexIssues(db.getSession(), singletonList(issue)); underTest.commitAndIndexIssues(db.getSession(), singletonList(issue)); assertThatIndexHasSize(0); // three attempts of indexing are stored in es_queue recovery table assertThatEsQueueTableHasSize(3); es.unlockWrites(TYPE_ISSUE); recover(); assertThatIndexHasOnly(issue); assertThatEsQueueTableHasSize(0); } @Test public void indexing_recovers_multiple_errors_on_the_same_project() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); db.issues().insert(rule, project, file); db.issues().insert(rule, project, file); es.lockWrites(TYPE_ISSUE); IndexingResult result = indexBranch(project.uuid(), DELETION); assertThat(result.getTotal()).isEqualTo(2L); assertThat(result.getFailures()).isEqualTo(2L); // index is still read-only, fail to recover result = recover(); assertThat(result.getTotal()).isEqualTo(2L); assertThat(result.getFailures()).isEqualTo(2L); assertThatIndexHasSize(0); es.unlockWrites(TYPE_ISSUE); result = recover(); assertThat(result.getTotal()).isEqualTo(2L); assertThat(result.getFailures()).isZero(); assertThatIndexHasSize(2); assertThatEsQueueTableHasSize(0); } private IndexingResult indexBranch(String branchUuid, Indexers.BranchEvent cause) { Collection<EsQueueDto> items = underTest.prepareForRecoveryOnBranchEvent(db.getSession(), singletonList(branchUuid), cause); db.commit(); return underTest.index(db.getSession(), items); } private IndexingResult indexProject(String projectUuid, EntityEvent cause) { Collection<EsQueueDto> items = underTest.prepareForRecoveryOnEntityEvent(db.getSession(), singletonList(projectUuid), cause); db.commit(); return underTest.index(db.getSession(), items); } @Test public void deleteByKeys_shouldDeleteDocsByKeys() { addIssueToIndex("P1", "B1", "Issue1"); addIssueToIndex("P1", "B1", "Issue2"); addIssueToIndex("P1", "B1", "Issue3"); addIssueToIndex("P2", "B2", "Issue4"); assertThatIndexHasOnly("Issue1", "Issue2", "Issue3", "Issue4"); underTest.deleteByKeys("P1", asList("Issue1", "Issue2")); assertThatIndexHasOnly("Issue3", "Issue4"); } @Test public void deleteByKeys_shouldNotRecoverFromErrors() { addIssueToIndex("P1", "B1","Issue1"); es.lockWrites(TYPE_ISSUE); List<String> issues = List.of("Issue1"); assertThatThrownBy(() -> underTest.deleteByKeys("P1", issues)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unrecoverable indexation failures: 1 errors among 1 requests. Check Elasticsearch logs for further details."); assertThatIndexHasOnly("Issue1"); assertThatEsQueueTableHasSize(0); es.unlockWrites(TYPE_ISSUE); } @Test public void deleteByKeys_whenEmptyList_shouldDoNothing() { addIssueToIndex("P1", "B1", "Issue1"); addIssueToIndex("P1", "B1", "Issue2"); addIssueToIndex("P1", "B1", "Issue3"); underTest.deleteByKeys("B1", emptyList()); assertThatIndexHasOnly("Issue1", "Issue2", "Issue3"); } /** * This is a technical constraint, to ensure, that the indexers can be called in any order, during startup. */ @Test public void parent_child_relationship_does_not_require_ordering_of_index_requests() { IssueDoc issueDoc = new IssueDoc(); issueDoc.setKey("key"); issueDoc.setProjectUuid("parent-does-not-exist"); new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null) .index(singletonList(issueDoc).iterator()); assertThat(es.countDocuments(TYPE_ISSUE)).isOne(); } @Test public void index_issue_in_non_main_branch() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo")); BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), branch.uuid()).orElseThrow(); ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(branch, "src/main/java/foo")); ComponentDto file = db.components().insertComponent(newFileDto(branch, dir, "F1")); IssueDto issue = db.issues().insert(rule, branch, file); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getId()).isEqualTo(issue.getKey()); assertThat(doc.componentUuid()).isEqualTo(file.uuid()); assertThat(doc.projectUuid()).isEqualTo(branchDto.getProjectUuid()); assertThat(doc.branchUuid()).isEqualTo(branch.uuid()); assertThat(doc.isMainBranch()).isFalse(); assertThat(doc.scope()).isEqualTo(IssueScope.MAIN); } @Test public void issue_on_test_file_has_test_scope() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo")); ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1").setQualifier("UTS")); IssueDto issue = db.issues().insert(rule, project, file); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getId()).isEqualTo(issue.getKey()); assertThat(doc.componentUuid()).isEqualTo(file.uuid()); assertThat(doc.scope()).isEqualTo(IssueScope.TEST); } @Test public void issue_on_directory_has_main_code_scope() { RuleDto rule = db.rules().insert(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo")); IssueDto issue = db.issues().insert(rule, project, dir); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getId()).isEqualTo(issue.getKey()); assertThat(doc.componentUuid()).isEqualTo(dir.uuid()); assertThat(doc.scope()).isEqualTo(IssueScope.MAIN); } @Test public void issue_on_project_has_main_code_scope() { RuleDto rule = db.rules().insert(); ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent(); IssueDto issue = db.issues().insert(rule, mainBranchComponent, mainBranchComponent); underTest.indexAllIssues(); IssueDoc doc = es.getDocuments(TYPE_ISSUE, IssueDoc.class).get(0); assertThat(doc.getId()).isEqualTo(issue.getKey()); assertThat(doc.componentUuid()).isEqualTo(mainBranchComponent.uuid()); assertThat(doc.scope()).isEqualTo(IssueScope.MAIN); } @Test public void getType() { Assertions.assertThat(underTest.getType()).isEqualTo(StartupIndexer.Type.ASYNCHRONOUS); } @Test public void indexOnAnalysis_whenChangedComponents_shouldReindexOnlyChangedComponents() { RuleDto rule = db.rules().insert(); ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto changedComponent1 = db.components().insertComponent(newFileDto(mainBranchComponent)); ComponentDto unchangedComponent = db.components().insertComponent(newFileDto(mainBranchComponent)); ComponentDto ChangedComponent2 = db.components().insertComponent(newFileDto(mainBranchComponent)); IssueDto changedIssue1 = db.issues().insert(rule, mainBranchComponent, changedComponent1); IssueDto changedIssue2 = db.issues().insert(rule, mainBranchComponent, changedComponent1); IssueDto changedIssue3 = db.issues().insert(rule, mainBranchComponent, ChangedComponent2); db.issues().insert(rule, mainBranchComponent, unchangedComponent); db.issues().insert(rule, mainBranchComponent, unchangedComponent); underTest.indexOnAnalysis(mainBranchComponent.uuid(), Set.of(unchangedComponent.uuid())); assertThatIndexHasOnly(changedIssue1, changedIssue2, changedIssue3); } @Test public void indexOnAnalysis_whenEmptyUnchangedComponents_shouldReindexEverything() { RuleDto rule = db.rules().insert(); ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto changedComponent = db.components().insertComponent(newFileDto(mainBranchComponent)); IssueDto changedIssue1 = db.issues().insert(rule, mainBranchComponent, changedComponent); IssueDto changedIssue2 = db.issues().insert(rule, mainBranchComponent, changedComponent); underTest.indexOnAnalysis(mainBranchComponent.uuid(), Set.of()); assertThatIndexHasOnly(changedIssue1, changedIssue2); } @Test public void indexOnAnalysis_whenChangedComponentWithoutIssue_shouldReindexNothing() { db.rules().insert(); ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newFileDto(mainBranchComponent)); underTest.indexOnAnalysis(mainBranchComponent.uuid(), Set.of()); assertThat(es.getDocuments(TYPE_ISSUE)).isEmpty(); } private void addIssueToIndex(String projectUuid, String branchUuid, String issueKey) { es.putDocuments(TYPE_ISSUE, newDoc().setKey(issueKey).setProjectUuid(projectUuid).setBranchUuid(branchUuid)); } private void assertThatIndexHasSize(long expectedSize) { assertThat(es.countDocuments(TYPE_ISSUE)).isEqualTo(expectedSize); } private void assertThatIndexHasOnly(IssueDto... expectedIssues) { assertThat(es.getDocuments(TYPE_ISSUE)) .extracting(SearchHit::getId) .containsExactlyInAnyOrder(Arrays.stream(expectedIssues).map(IssueDto::getKey).toArray(String[]::new)); } private void assertThatIndexHasOnly(String... expectedKeys) { List<IssueDoc> issues = es.getDocuments(TYPE_ISSUE, IssueDoc.class); assertThat(issues).extracting(IssueDoc::key).containsOnly(expectedKeys); } private void assertThatEsQueueTableHasSize(int expectedSize) { assertThat(db.countRowsOfTable("es_queue")).isEqualTo(expectedSize); } private void assertThatDbHasOnly(IssueDto... expectedIssues) { try (DbSession otherSession = db.getDbClient().openSession(false)) { List<String> keys = Arrays.stream(expectedIssues).map(IssueDto::getKey).toList(); assertThat(db.getDbClient().issueDao().selectByKeys(otherSession, keys)).hasSize(expectedIssues.length); } } private IndexingResult recover() { Collection<EsQueueDto> items = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), System.currentTimeMillis() + 1_000L, 10); return underTest.index(db.getSession(), items); } }
26,916
40.410769
158
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/issue/index/IssueIteratorFactoryIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import com.google.common.collect.Maps; import java.util.Date; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.issue.IssueDto; import org.sonar.db.rule.RuleDto; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.issue.IssueTesting.newCodeReferenceIssue; public class IssueIteratorFactoryIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Test public void iterator_over_one_issue() { RuleDto rule = dbTester.rules().insert(); ProjectData projectData = dbTester.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); ComponentDto file = dbTester.components().insertComponent(newFileDto(project) .setPath("src/main/java/Action.java")); IssueDto expected = dbTester.issues().insert(rule, project, file, t -> t.setResolution("FIXED") .setStatus("RESOLVED") .setSeverity("BLOCKER") .setManualSeverity(false) .setAssigneeUuid("uuid-of-guy1") .setAuthorLogin("guy2") .setChecksum("FFFFF") .setGap(2D) .setEffort(10L) .setMessage(null) .setLine(444) .setRuleUuid(rule.getUuid()) .setTags(List.of("tag1", "tag2", "tag3")) .setCreatedAt(1400000000000L) .setUpdatedAt(1400000000000L) .setIssueCreationDate(new Date(1115848800000L)) .setIssueUpdateDate(new Date(1356994800000L)) .setIssueCloseDate(null) .setType(2) .setCodeVariants(List.of("variant1", "variant2"))); Map<String, IssueDoc> issuesByKey = issuesByKey(); assertThat(issuesByKey).hasSize(1); IssueDoc issue = issuesByKey.get(expected.getKey()); assertThat(issue.key()).isEqualTo(expected.getKey()); assertThat(issue.resolution()).isEqualTo("FIXED"); assertThat(issue.status()).isEqualTo("RESOLVED"); assertThat(issue.severity()).isEqualTo("BLOCKER"); assertThat(issue.assigneeUuid()).isEqualTo("uuid-of-guy1"); assertThat(issue.authorLogin()).isEqualTo("guy2"); assertThat(issue.line()).isEqualTo(444); assertThat(issue.ruleUuid()).isEqualTo(rule.getUuid()); assertThat(issue.componentUuid()).isEqualTo(file.uuid()); assertThat(issue.projectUuid()).isEqualTo(projectData.projectUuid()); assertThat(issue.directoryPath()).isEqualTo("src/main/java"); assertThat(issue.filePath()).isEqualTo("src/main/java/Action.java"); assertThat(issue.getTags()).containsOnly("tag1", "tag2", "tag3"); assertThat(issue.effort().toMinutes()).isPositive(); assertThat(issue.type().getDbConstant()).isEqualTo(2); assertThat(issue.getCodeVariants()).containsOnly("variant1", "variant2"); } @Test public void iterator_over_issues() { RuleDto rule = dbTester.rules().insert(); ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = dbTester.components().insertComponent(newDirectory(project, "src/main/java")); ComponentDto file = dbTester.components().insertComponent(newFileDto(directory, directory) .setPath("src/main/java/Action.java")); IssueDto fileIssue = dbTester.issues().insert(rule, project, file, t -> t .setAssigneeUuid("uuid-of-guy1") .setAuthorLogin("guy2") .setEffort(10L) .setType(1)); IssueDto moduleIssue = dbTester.issues().insert(rule, project, file, t -> t .setAssigneeUuid("uuid-of-guy2") .setAuthorLogin("guy2") .setRuleUuid(rule.getUuid())); IssueDto dirIssue = dbTester.issues().insert(rule, project, directory); IssueDto projectIssue = dbTester.issues().insert(rule, project, project); dbTester.issues().insertNewCodeReferenceIssue(newCodeReferenceIssue(fileIssue)); Map<String, IssueDoc> issuesByKey = issuesByKey(); assertThat(issuesByKey) .hasSize(4) .containsOnlyKeys(fileIssue.getKey(), moduleIssue.getKey(), dirIssue.getKey(), projectIssue.getKey()); assertThat(issuesByKey.get(fileIssue.getKey()).isNewCodeReference()).isTrue(); } @Test public void iterator_over_issue_from_project() { RuleDto rule = dbTester.rules().insert(); ComponentDto project1 = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir = dbTester.components().insertComponent(newDirectory(project1, "path")); ComponentDto file1 = dbTester.components().insertComponent(newFileDto(project1, dir)); String[] project1IssueKeys = Stream.of(project1, dir, file1) .map(project1Component -> dbTester.issues().insert(rule, project1, project1Component).getKey()) .toArray(String[]::new); ComponentDto project2 = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir2 = dbTester.components().insertComponent(newDirectory(project2, "path")); ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project2, dir2)); String[] project2IssueKeys = Stream.of(project2, dir2, file2) .map(project2Component -> dbTester.issues().insert(rule, project2, project2Component).getKey()) .toArray(String[]::new); assertThat(issuesByKey(factory -> factory.createForBranch(project1.uuid()))) .containsOnlyKeys(project1IssueKeys); assertThat(issuesByKey(factory -> factory.createForBranch(project2.uuid()))) .containsOnlyKeys(project2IssueKeys); assertThat(issuesByKey(factory -> factory.createForBranch("does not exist"))) .isEmpty(); } @Test public void extract_directory_path() { RuleDto rule = dbTester.rules().insert(); ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto fileInRootDir = dbTester.components().insertComponent(newFileDto(project).setPath("pom.xml")); ComponentDto fileInSubDir = dbTester.components().insertComponent(newFileDto(project).setPath("src/main/java/Action.java")); IssueDto projectIssue = dbTester.issues().insert(rule, project, project); IssueDto fileInSubDirIssue = dbTester.issues().insert(rule, project, fileInSubDir); IssueDto fileInRootDirIssue = dbTester.issues().insert(rule, project, fileInRootDir); Map<String, IssueDoc> issuesByKey = issuesByKey(); assertThat(issuesByKey).hasSize(3); assertThat(issuesByKey.get(fileInSubDirIssue.getKey()).directoryPath()).isEqualTo("src/main/java"); assertThat(issuesByKey.get(fileInRootDirIssue.getKey()).directoryPath()).isEqualTo("/"); assertThat(issuesByKey.get(projectIssue.getKey()).directoryPath()).isNull(); } @Test public void extract_file_path() { RuleDto rule = dbTester.rules().insert(); ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto fileInRootDir = dbTester.components().insertComponent(newFileDto(project).setPath("pom.xml")); ComponentDto fileInSubDir = dbTester.components().insertComponent(newFileDto(project).setPath("src/main/java/Action.java")); IssueDto projectIssue = dbTester.issues().insert(rule, project, project); IssueDto fileInSubDirIssue = dbTester.issues().insert(rule, project, fileInSubDir); IssueDto fileInRootDirIssue = dbTester.issues().insert(rule, project, fileInRootDir); Map<String, IssueDoc> issuesByKey = issuesByKey(); assertThat(issuesByKey).hasSize(3); assertThat(issuesByKey.get(fileInSubDirIssue.getKey()).filePath()).isEqualTo("src/main/java/Action.java"); assertThat(issuesByKey.get(fileInRootDirIssue.getKey()).filePath()).isEqualTo("pom.xml"); assertThat(issuesByKey.get(projectIssue.getKey()).filePath()).isNull(); } private Map<String, IssueDoc> issuesByKey() { return issuesByKey(IssueIteratorFactory::createForAll); } private Map<String, IssueDoc> issuesByKey(Function<IssueIteratorFactory, IssueIterator> function) { try (IssueIterator it = function.apply(new IssueIteratorFactory(dbTester.getDbClient()))) { return Maps.uniqueIndex(it, IssueDoc::key); } } }
9,304
45.525
128
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/issue/notification/NewIssuesNotificationIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Date; import java.util.Optional; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.Duration; import org.sonar.api.utils.Durations; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier; import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.ASSIGNEE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.COMPONENT; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.EFFORT; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE_TYPE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.TAG; public class NewIssuesNotificationIT { @Rule public DbTester db = DbTester.create(); private DetailsSupplier detailsSupplier = mock(DetailsSupplier.class); private NewIssuesNotification underTest = new NewIssuesNotification(new Durations(), detailsSupplier); @Test public void set_project_without_branch() { underTest.setProject("project-key", "project-long-name", null, null); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_NAME)).isEqualTo("project-long-name"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_KEY)).isEqualTo("project-key"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_BRANCH)).isNull(); } @Test public void set_project_with_branch() { underTest.setProject("project-key", "project-long-name", "feature", null); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_NAME)).isEqualTo("project-long-name"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_KEY)).isEqualTo("project-key"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_BRANCH)).isEqualTo("feature"); } @Test public void set_project_with_pull_request() { underTest.setProject("project-key", "project-long-name", null, "pr-123"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_NAME)).isEqualTo("project-long-name"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_KEY)).isEqualTo("project-key"); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PULL_REQUEST)).isEqualTo("pr-123"); } @Test public void set_project_version() { String version = randomAlphanumeric(5); underTest.setProjectVersion(version); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_VERSION)).isEqualTo(version); } @Test public void set_project_version_supports_null() { underTest.setProjectVersion(null); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_VERSION)).isNull(); } @Test public void getProjectKey_returns_null_if_setProject_has_no_been_called() { assertThat(underTest.getProjectKey()).isNull(); } @Test public void getProjectKey_returns_projectKey_if_setProject_has_been_called() { String projectKey = randomAlphabetic(5); String projectName = randomAlphabetic(6); String branchName = randomAlphabetic(7); String pullRequest = randomAlphabetic(8); underTest.setProject(projectKey, projectName, branchName, pullRequest); assertThat(underTest.getProjectKey()).isEqualTo(projectKey); } @Test public void getProjectKey_returns_value_of_field_projectKey() { String projectKey = randomAlphabetic(5); underTest.setFieldValue("projectKey", projectKey); assertThat(underTest.getProjectKey()).isEqualTo(projectKey); } @Test public void set_date() { Date date = new Date(); underTest.setAnalysisDate(date); assertThat(underTest.getFieldValue(NewIssuesEmailTemplate.FIELD_PROJECT_DATE)).isEqualTo(DateUtils.formatDateTime(date)); } @Test public void set_statistics() { UserDto maynard = db.users().insertUser(u -> u.setLogin("maynard")); UserDto keenan = db.users().insertUser(u -> u.setLogin("keenan")); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = db.components().insertComponent(newDirectory(project, "path")); ComponentDto file = db.components().insertComponent(newFileDto(directory)); RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java")); RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure")); IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp"))); IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp"))); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(issue1.toDefaultIssue())); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(issue2.toDefaultIssue())); mockDetailsSupplierComponents(project, directory, file); mockDetailsSupplierRules(rule1, rule2); mockDetailsSupplierAssignees(maynard, keenan); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(RULE_TYPE + ".BUG.count")).isEqualTo("5"); assertThat(underTest.getFieldValue(RULE_TYPE + ".CODE_SMELL.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.label")).isEqualTo(maynard.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.count")).isEqualTo("5"); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.label")).isEqualTo(keenan.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(TAG + ".1.label")).isEqualTo("owasp"); assertThat(underTest.getFieldValue(TAG + ".1.count")).isEqualTo("8"); assertThat(underTest.getFieldValue(TAG + ".2.label")).isEqualTo("bug"); assertThat(underTest.getFieldValue(TAG + ".2.count")).isEqualTo("5"); assertThat(underTest.getFieldValue(COMPONENT + ".1.label")).isEqualTo(file.name()); assertThat(underTest.getFieldValue(COMPONENT + ".1.count")).isEqualTo("5"); assertThat(underTest.getFieldValue(COMPONENT + ".2.label")).isEqualTo(directory.name()); assertThat(underTest.getFieldValue(COMPONENT + ".2.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(RULE + ".1.label")).isEqualTo("Rule the World (Java)"); assertThat(underTest.getFieldValue(RULE + ".1.count")).isEqualTo("5"); assertThat(underTest.getFieldValue(RULE + ".2.label")).isEqualTo("Rule the Universe (Clojure)"); assertThat(underTest.getFieldValue(RULE + ".2.count")).isEqualTo("3"); assertThat(underTest.getDefaultMessage()).startsWith("8 new issues on " + project.longName()); } @Test public void set_statistics_when_no_issues_created_on_current_analysis() { UserDto maynard = db.users().insertUser(u -> u.setLogin("maynard")); UserDto keenan = db.users().insertUser(u -> u.setLogin("keenan")); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = db.components().insertComponent(newDirectory(project, "path")); ComponentDto file = db.components().insertComponent(newFileDto(directory)); RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java")); RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure")); IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp"))); IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp"))); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> false); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(issue1.toDefaultIssue())); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(issue2.toDefaultIssue())); mockDetailsSupplierComponents(project, directory, file); mockDetailsSupplierRules(rule1, rule2); mockDetailsSupplierAssignees(maynard, keenan); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(RULE_TYPE + ".BUG.count")).isEqualTo("0"); assertThat(underTest.getFieldValue(RULE_TYPE + ".CODE_SMELL.count")).isEqualTo("0"); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.label")).isNull(); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.count")).isNull(); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.label")).isNull(); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.count")).isNull(); assertThat(underTest.getFieldValue(TAG + ".1.label")).isNull(); assertThat(underTest.getFieldValue(TAG + ".1.count")).isNull(); assertThat(underTest.getFieldValue(TAG + ".2.label")).isNull(); assertThat(underTest.getFieldValue(TAG + ".2.count")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".1.label")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".1.count")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".2.label")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".2.count")).isNull(); assertThat(underTest.getFieldValue(RULE + ".1.label")).isNull(); assertThat(underTest.getFieldValue(RULE + ".1.count")).isNull(); assertThat(underTest.getFieldValue(RULE + ".2.label")).isNull(); assertThat(underTest.getFieldValue(RULE + ".2.count")).isNull(); assertThat(underTest.getDefaultMessage()).startsWith("0 new issues on " + project.longName()); } @Test public void set_statistics_when_some_issues_are_no_created_on_current_analysis() { UserDto maynard = db.users().insertUser(u -> u.setLogin("maynard")); UserDto keenan = db.users().insertUser(u -> u.setLogin("keenan")); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = db.components().insertComponent(newDirectory(project, "path")); ComponentDto file = db.components().insertComponent(newFileDto(directory)); RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java")); RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure")); IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp"))); IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp"))); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> i.key().equals(issue2.getKey())); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(issue1.toDefaultIssue())); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(issue2.toDefaultIssue())); mockDetailsSupplierComponents(project, directory, file); mockDetailsSupplierRules(rule1, rule2); mockDetailsSupplierAssignees(maynard, keenan); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(RULE_TYPE + ".BUG.count")).isEqualTo("0"); assertThat(underTest.getFieldValue(RULE_TYPE + ".CODE_SMELL.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.label")).isEqualTo(keenan.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.label")).isNull(); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.count")).isNull(); assertThat(underTest.getFieldValue(TAG + ".1.label")).isEqualTo("owasp"); assertThat(underTest.getFieldValue(TAG + ".1.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(TAG + ".2.label")).isNull(); assertThat(underTest.getFieldValue(TAG + ".2.count")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".1.label")).isEqualTo(directory.name()); assertThat(underTest.getFieldValue(COMPONENT + ".1.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(COMPONENT + ".2.label")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".2.count")).isNull(); assertThat(underTest.getFieldValue(RULE + ".1.label")).isEqualTo("Rule the Universe (Clojure)"); assertThat(underTest.getFieldValue(RULE + ".1.count")).isEqualTo("3"); assertThat(underTest.getFieldValue(RULE + ".2.label")).isNull(); assertThat(underTest.getFieldValue(RULE + ".2.count")).isNull(); assertThat(underTest.getDefaultMessage()).startsWith("3 new issues on " + project.longName()); } private void mockDetailsSupplierAssignees(UserDto... users) { for (UserDto user : users) { when(detailsSupplier.getUserNameByUuid(user.getUuid())).thenReturn(Optional.of(user.getName())); } } private void mockDetailsSupplierRules(RuleDto... rules) { for (RuleDto rule : rules) { when(detailsSupplier.getRuleDefinitionByRuleKey(rule.getKey())) .thenReturn(Optional.of(new RuleDefinition(rule.getName(), rule.getLanguage()))); } } private void mockDetailsSupplierComponents(ComponentDto... components) { for (ComponentDto component : components) { when(detailsSupplier.getComponentNameByUuid(component.uuid())).thenReturn(Optional.of(component.name())); } } @Test public void set_assignee() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); RuleDto rule = db.rules().insert(); UserDto user = db.users().insertUser(); IssueDto issue = db.issues().insert(rule, project, file, i -> i.setAssigneeUuid(user.getUuid())); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(issue.toDefaultIssue())); mockDetailsSupplierRules(rule); mockDetailsSupplierAssignees(user); mockDetailsSupplierComponents(project, file); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.label")).isEqualTo(user.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.count")).isEqualTo("5"); } @Test public void add_only_5_assignees_with_biggest_issue_counts() { UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); UserDto user3 = db.users().insertUser(); UserDto user4 = db.users().insertUser(); UserDto user5 = db.users().insertUser(); UserDto user6 = db.users().insertUser(); UserDto user7 = db.users().insertUser(); UserDto user8 = db.users().insertUser(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); RuleDto rule = db.rules().insert(); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true); IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user1.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 9).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user2.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 8).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user3.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 7).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user4.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 6).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user5.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user6.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 4).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user7.getUuid())).toDefaultIssue())); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user8.getUuid())).toDefaultIssue())); mockDetailsSupplierAssignees(user1, user2, user3, user4, user5, user6, user7, user8); mockDetailsSupplierComponents(project, file); mockDetailsSupplierRules(rule); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.label")).isEqualTo(user1.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".1.count")).isEqualTo("10"); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.label")).isEqualTo(user2.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".2.count")).isEqualTo("9"); assertThat(underTest.getFieldValue(ASSIGNEE + ".3.label")).isEqualTo(user3.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".3.count")).isEqualTo("8"); assertThat(underTest.getFieldValue(ASSIGNEE + ".4.label")).isEqualTo(user4.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".4.count")).isEqualTo("7"); assertThat(underTest.getFieldValue(ASSIGNEE + ".5.label")).isEqualTo(user5.getName()); assertThat(underTest.getFieldValue(ASSIGNEE + ".5.count")).isEqualTo("6"); assertThat(underTest.getFieldValue(ASSIGNEE + ".6.label")).isNull(); assertThat(underTest.getFieldValue(ASSIGNEE + ".6.count")).isNull(); } @Test public void add_only_5_components_with_biggest_issue_counts() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); RuleDto rule = db.rules().insert(); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true); ComponentDto file1 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule, project, file1).toDefaultIssue())); ComponentDto file2 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 9).forEach(i -> stats.add(db.issues().insert(rule, project, file2).toDefaultIssue())); ComponentDto file3 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 8).forEach(i -> stats.add(db.issues().insert(rule, project, file3).toDefaultIssue())); ComponentDto file4 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 7).forEach(i -> stats.add(db.issues().insert(rule, project, file4).toDefaultIssue())); ComponentDto file5 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 6).forEach(i -> stats.add(db.issues().insert(rule, project, file5).toDefaultIssue())); ComponentDto file6 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(db.issues().insert(rule, project, file6).toDefaultIssue())); ComponentDto file7 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 4).forEach(i -> stats.add(db.issues().insert(rule, project, file7).toDefaultIssue())); ComponentDto file8 = db.components().insertComponent(newFileDto(project)); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(db.issues().insert(rule, project, file8).toDefaultIssue())); mockDetailsSupplierComponents(project, file1, file2, file3, file4, file5, file6, file7, file8); mockDetailsSupplierRules(rule); underTest.setStatistics(project.longName(), stats); assertThat(underTest.getFieldValue(COMPONENT + ".1.label")).isEqualTo(file1.name()); assertThat(underTest.getFieldValue(COMPONENT + ".1.count")).isEqualTo("10"); assertThat(underTest.getFieldValue(COMPONENT + ".2.label")).isEqualTo(file2.name()); assertThat(underTest.getFieldValue(COMPONENT + ".2.count")).isEqualTo("9"); assertThat(underTest.getFieldValue(COMPONENT + ".3.label")).isEqualTo(file3.name()); assertThat(underTest.getFieldValue(COMPONENT + ".3.count")).isEqualTo("8"); assertThat(underTest.getFieldValue(COMPONENT + ".4.label")).isEqualTo(file4.name()); assertThat(underTest.getFieldValue(COMPONENT + ".4.count")).isEqualTo("7"); assertThat(underTest.getFieldValue(COMPONENT + ".5.label")).isEqualTo(file5.name()); assertThat(underTest.getFieldValue(COMPONENT + ".5.count")).isEqualTo("6"); assertThat(underTest.getFieldValue(COMPONENT + ".6.label")).isNull(); assertThat(underTest.getFieldValue(COMPONENT + ".6.count")).isNull(); } @Test public void add_only_5_rules_with_biggest_issue_counts() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true); RuleDto rule1 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule1, project, file).toDefaultIssue())); RuleDto rule2 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 9).forEach(i -> stats.add(db.issues().insert(rule2, project, file).toDefaultIssue())); RuleDto rule3 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 8).forEach(i -> stats.add(db.issues().insert(rule3, project, file).toDefaultIssue())); RuleDto rule4 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 7).forEach(i -> stats.add(db.issues().insert(rule4, project, file).toDefaultIssue())); RuleDto rule5 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 6).forEach(i -> stats.add(db.issues().insert(rule5, project, file).toDefaultIssue())); RuleDto rule6 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 5).forEach(i -> stats.add(db.issues().insert(rule6, project, file).toDefaultIssue())); RuleDto rule7 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 4).forEach(i -> stats.add(db.issues().insert(rule7, project, file).toDefaultIssue())); RuleDto rule8 = db.rules().insert(r -> r.setLanguage("Java")); IntStream.rangeClosed(1, 3).forEach(i -> stats.add(db.issues().insert(rule8, project, file).toDefaultIssue())); mockDetailsSupplierComponents(project, file); mockDetailsSupplierRules(rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8); underTest.setStatistics(project.longName(), stats); String javaSuffix = " (Java)"; assertThat(underTest.getFieldValue(RULE + ".1.label")).isEqualTo(rule1.getName() + javaSuffix); assertThat(underTest.getFieldValue(RULE + ".1.count")).isEqualTo("10"); assertThat(underTest.getFieldValue(RULE + ".2.label")).isEqualTo(rule2.getName() + javaSuffix); assertThat(underTest.getFieldValue(RULE + ".2.count")).isEqualTo("9"); assertThat(underTest.getFieldValue(RULE + ".3.label")).isEqualTo(rule3.getName() + javaSuffix); assertThat(underTest.getFieldValue(RULE + ".3.count")).isEqualTo("8"); assertThat(underTest.getFieldValue(RULE + ".4.label")).isEqualTo(rule4.getName() + javaSuffix); assertThat(underTest.getFieldValue(RULE + ".4.count")).isEqualTo("7"); assertThat(underTest.getFieldValue(RULE + ".5.label")).isEqualTo(rule5.getName() + javaSuffix); assertThat(underTest.getFieldValue(RULE + ".5.count")).isEqualTo("6"); assertThat(underTest.getFieldValue(RULE + ".6.label")).isNull(); assertThat(underTest.getFieldValue(RULE + ".6.count")).isNull(); } @Test public void set_debt() { underTest.setDebt(Duration.create(55)); assertThat(underTest.getFieldValue(EFFORT + ".count")).isEqualTo("55min"); } @Test public void RuleDefinition_implements_equals_base_on_name_and_language() { String name = randomAlphabetic(5); String language = randomAlphabetic(6); RuleDefinition underTest = new RuleDefinition(name, language); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new RuleDefinition(name, language)) .isNotEqualTo(new RuleDefinition(language, name)) .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name)) .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7))) .isNotEqualTo(new RuleDefinition(language, null)) .isNotNull() .isNotEqualTo(new Object()); } @Test public void RuleDefinition_implements_hashcode_base_on_name_and_language() { String name = randomAlphabetic(5); String language = randomAlphabetic(6); RuleDefinition underTest = new RuleDefinition(name, language); assertThat(underTest) .hasSameHashCodeAs(underTest) .hasSameHashCodeAs(new RuleDefinition(name, language)); assertThat(underTest.hashCode()) .isNotEqualTo(new RuleDefinition(language, name).hashCode()) .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name).hashCode()) .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7)).hashCode()) .isNotEqualTo(new RuleDefinition(language, null).hashCode()) .isNotEqualTo(new Object().hashCode()); } }
27,539
57.595745
164
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/measure/index/ProjectMeasuresIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.index; import java.util.Arrays; import java.util.Collection; import java.util.function.Consumer; import java.util.function.Predicate; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.es.EsQueueDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.Indexers; import org.sonar.server.es.IndexingResult; import org.sonar.server.permission.index.AuthorizationScope; import org.sonar.server.permission.index.IndexPermissions; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.termsQuery; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.server.es.EsClient.prepareSearch; import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE; import static org.sonar.server.es.Indexers.EntityEvent.CREATION; import static org.sonar.server.es.Indexers.EntityEvent.DELETION; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_KEY_UPDATE; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_TAGS_UPDATE; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_QUALIFIER; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_TAGS; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_UUID; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES; import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; public class ProjectMeasuresIndexerIT { private final System2 system2 = System2.INSTANCE; @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(system2); private final ProjectMeasuresIndexer underTest = new ProjectMeasuresIndexer(db.getDbClient(), es.client()); @Test public void getAuthorizationScope_shouldReturnTrueForProjectAndApp() { AuthorizationScope scope = underTest.getAuthorizationScope(); assertThat(scope.getIndexType().getIndex()).isEqualTo(ProjectMeasuresIndexDefinition.DESCRIPTOR); assertThat(scope.getIndexType().getType()).isEqualTo(TYPE_AUTHORIZATION); Predicate<IndexPermissions> projectPredicate = scope.getEntityPredicate(); IndexPermissions project = new IndexPermissions("P1", Qualifiers.PROJECT); IndexPermissions app = new IndexPermissions("P1", Qualifiers.APP); IndexPermissions file = new IndexPermissions("F1", Qualifiers.FILE); assertThat(projectPredicate.test(project)).isTrue(); assertThat(projectPredicate.test(app)).isTrue(); assertThat(projectPredicate.test(file)).isFalse(); } @Test public void indexOnStartup_whenNoEntities_shouldNotIndexAnything() { underTest.indexOnStartup(emptySet()); assertThat(es.countDocuments(TYPE_PROJECT_MEASURES)).isZero(); } @Test public void indexOnStartup_shouldIndexAllProjects() { SnapshotDto project1 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); SnapshotDto project2 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); SnapshotDto project3 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project1, project2, project3); assertThatQualifierIs("TRK", project1, project2, project3); } @Test public void indexAll_indexes_all_projects() { SnapshotDto snapshot1 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); SnapshotDto snapshot2 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); SnapshotDto snapshot3 = db.components().insertProjectAndSnapshot(newPrivateProjectDto()); underTest.indexAll(); assertThatIndexContainsOnly(snapshot1, snapshot2, snapshot3); assertThatQualifierIs("TRK", snapshot1, snapshot2, snapshot3); } /** * Provisioned projects don't have analysis yet */ @Test public void indexOnStartup_indexes_provisioned_projects() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project); } @Test public void indexOnStartup_ignores_non_main_branches() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.components().insertProjectBranch(project, b -> b.setKey("feature/foo")); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project); } @Test public void indexOnStartup_indexes_all_applications() { ProjectDto application1 = db.components().insertPrivateApplication().getProjectDto(); ProjectDto application2 = db.components().insertPrivateApplication().getProjectDto(); ProjectDto application3 = db.components().insertPrivateApplication().getProjectDto(); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(application1, application2, application3); assertThatQualifierIs("APP", application1, application2, application3); } @Test public void indexOnStartup_indexes_projects_and_applications() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject().getProjectDto(); ProjectDto application1 = db.components().insertPrivateApplication().getProjectDto(); ProjectDto application2 = db.components().insertPrivateApplication().getProjectDto(); ProjectDto application3 = db.components().insertPrivateApplication().getProjectDto(); underTest.indexOnStartup(emptySet()); assertThatIndexContainsOnly(project1, project2, project3, application1, application2, application3); assertThatQualifierIs("TRK", project1, project2, project3); assertThatQualifierIs("APP", application1, application2, application3); } @Test public void indexOnAnalysis_indexes_provisioned_project() { ProjectData project1 = db.components().insertPrivateProject(); ProjectData project2 = db.components().insertPrivateProject(); underTest.indexOnAnalysis(project1.getMainBranchComponent().uuid()); assertThatIndexContainsOnly(project1.getProjectDto()); } @Test public void indexOnAnalysis_whenPassingANonMainBranch_ShouldNotIndexProject() { ProjectData project1 = db.components().insertPrivateProject(); ProjectData project2 = db.components().insertPrivateProject(); BranchDto branchDto = db.components().insertProjectBranch(project1.getProjectDto()); underTest.indexOnAnalysis(branchDto.getUuid()); assertThatIndexContainsOnly(new ProjectDto[]{}); } @Test public void indexOnAnalysis_indexes_provisioned_application() { ProjectData app1 = db.components().insertPrivateApplication(); ProjectData app2 = db.components().insertPrivateApplication(); underTest.indexOnAnalysis(app1.getMainBranchComponent().uuid()); assertThatIndexContainsOnly(app1.getProjectDto()); } @Test public void update_index_when_project_key_is_updated() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); IndexingResult result = indexProject(project, PROJECT_KEY_UPDATE); assertThatIndexContainsOnly(project); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); } @Test public void update_index_when_project_is_created() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); IndexingResult result = indexProject(project, CREATION); assertThatIndexContainsOnly(project); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); } @Test public void update_index_when_project_tags_are_updated() { ProjectDto project = db.components().insertPrivateProject(defaults(), p -> p.setTagsString("foo")).getProjectDto(); indexProject(project, CREATION); assertThatProjectHasTag(project, "foo"); project.setTagsString("bar"); db.getDbClient().projectDao().updateTags(db.getSession(), project); IndexingResult result = indexProject(project, PROJECT_TAGS_UPDATE); assertThatProjectHasTag(project, "bar"); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); } @Test public void delete_doc_from_index_when_project_is_deleted() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); indexProject(project, CREATION); assertThatIndexContainsOnly(project); db.getDbClient().purgeDao().deleteProject(db.getSession(), project.getUuid(), Qualifiers.PROJECT, project.getName(), project.getKey()); IndexingResult result = indexProject(project, DELETION); assertThat(es.countDocuments(TYPE_PROJECT_MEASURES)).isZero(); assertThat(result.getTotal()).isOne(); assertThat(result.getSuccess()).isOne(); } @Test public void do_nothing_if_no_projects_and_apps_to_index() { // this project should not be indexed db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertPrivateApplication().getMainBranchComponent(); underTest.index(db.getSession(), emptyList()); assertThat(es.countDocuments(TYPE_PROJECT_MEASURES)).isZero(); } @Test public void errors_during_indexing_are_recovered() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); es.lockWrites(TYPE_PROJECT_MEASURES); IndexingResult result = indexProject(project, CREATION); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isOne(); // index is still read-only, fail to recover result = recover(); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isOne(); assertThat(es.countDocuments(TYPE_PROJECT_MEASURES)).isZero(); assertThatEsQueueTableHasSize(1); es.unlockWrites(TYPE_PROJECT_MEASURES); result = recover(); assertThat(result.getTotal()).isOne(); assertThat(result.getFailures()).isZero(); assertThatEsQueueTableHasSize(0); assertThatIndexContainsOnly(project); } @Test public void non_main_branches_are_not_indexed_during_analysis() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo")); underTest.indexOnAnalysis(branch.uuid()); assertThat(es.countDocuments(TYPE_PROJECT_MEASURES)).isZero(); } private IndexingResult indexProject(ProjectDto project, Indexers.EntityEvent cause) { DbSession dbSession = db.getSession(); Collection<EsQueueDto> items = underTest.prepareForRecoveryOnEntityEvent(dbSession, singletonList(project.getUuid()), cause); dbSession.commit(); return underTest.index(dbSession, items); } private void assertThatProjectHasTag(ProjectDto project, String expectedTag) { SearchRequest request = prepareSearch(TYPE_PROJECT_MEASURES.getMainType()) .source(new SearchSourceBuilder() .query(boolQuery() .filter(termQuery(FIELD_INDEX_TYPE, TYPE_PROJECT_MEASURES.getName())) .filter(termQuery(FIELD_TAGS, expectedTag)))); assertThat(es.client().search(request).getHits().getHits()) .extracting(SearchHit::getId) .contains(project.getUuid()); } private void assertThatEsQueueTableHasSize(int expectedSize) { assertThat(db.countRowsOfTable("es_queue")).isEqualTo(expectedSize); } private void assertThatIndexContainsOnly(SnapshotDto... expectedSnapshots) { assertThat(es.getIds(TYPE_PROJECT_MEASURES)).containsExactlyInAnyOrder( Arrays.stream(expectedSnapshots).map(this::getProjectUuidFromSnapshot).toArray(String[]::new)); } private String getProjectUuidFromSnapshot(SnapshotDto s) { ProjectDto projectDto = db.getDbClient().projectDao().selectByBranchUuid(db.getSession(), s.getRootComponentUuid()).orElseThrow(); return projectDto.getUuid(); } private void assertThatIndexContainsOnly(ProjectDto... expectedProjects) { assertThat(es.getIds(TYPE_PROJECT_MEASURES)).containsExactlyInAnyOrder( Arrays.stream(expectedProjects).map(ProjectDto::getUuid).toArray(String[]::new)); } private void assertThatQualifierIs(String qualifier, ProjectDto... expectedProjects) { String[] expectedComponentUuids = Arrays.stream(expectedProjects).map(ProjectDto::getUuid).toArray(String[]::new); assertThatQualifierIs(qualifier, expectedComponentUuids); } private void assertThatQualifierIs(String qualifier, SnapshotDto... expectedSnapshots) { String[] expectedComponentUuids = Arrays.stream(expectedSnapshots) .map(this::getProjectUuidFromSnapshot).toArray(String[]::new); assertThatQualifierIs(qualifier, expectedComponentUuids); } private void assertThatQualifierIs(String qualifier, String... componentsUuid) { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder() .query(boolQuery() .filter(termQuery(FIELD_INDEX_TYPE, TYPE_PROJECT_MEASURES.getName())) .filter(termQuery(FIELD_QUALIFIER, qualifier)) .filter(termsQuery(FIELD_UUID, componentsUuid))); SearchRequest request = prepareSearch(TYPE_PROJECT_MEASURES.getMainType()) .source(searchSourceBuilder); assertThat(es.client().search(request).getHits().getHits()) .extracting(SearchHit::getId) .containsExactlyInAnyOrder(componentsUuid); } private IndexingResult recover() { Collection<EsQueueDto> items = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), System.currentTimeMillis() + 1_000L, 10); return underTest.index(db.getSession(), items); } private static <T> Consumer<T> defaults() { return t -> { // do nothing }; } }
15,449
39.981432
141
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/metric/MetricFinderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.Metric; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.metric.MetricTesting.newMetricDto; public class MetricFinderIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final MetricFinder underTest = new MetricFinder(db.getDbClient()); @Test public void findAll_enabled() { db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); db.commit(); assertThat(underTest.findAll()).hasSize(2); } @Test public void findAll_by_keys() { db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("ncloc")); db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("foo")); db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setKey("coverage")); db.commit(); assertThat(underTest.findAll(Arrays.asList("ncloc", "foo"))).extracting(Metric::getKey).containsExactlyInAnyOrder("ncloc", "foo") .doesNotContain("coverage"); } @Test public void findById() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.commit(); assertThat(underTest.findByUuid(firstMetric.getUuid())).extracting(Metric::getKey).isEqualTo(firstMetric.getKey()); } @Test public void findById_filters_out_disabled() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); db.commit(); assertThat(underTest.findByUuid(secondMetric.getUuid())).isNull(); } @Test public void findById_doesnt_find_anything() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.commit(); assertThat(underTest.findByUuid("non existing")).isNull(); } @Test public void findByKey() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.commit(); assertThat(underTest.findByKey(secondMetric.getKey())).extracting(Metric::getKey).isEqualTo(secondMetric.getKey()); } @Test public void findByKey_filters_out_disabled() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto().setEnabled(false)); db.commit(); assertThat(underTest.findByKey(secondMetric.getKey())).isNull(); } @Test public void findByKey_doesnt_find_anything() { MetricDto firstMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); MetricDto secondMetric = db.getDbClient().metricDao().insert(db.getSession(), newMetricDto()); db.commit(); assertThat(underTest.findByKey("doesnt exist")).isNull(); } }
4,406
36.991379
133
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/platform/StartupMetadataProviderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.junit.Rule; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.System2; import org.sonar.api.utils.Version; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.utils.DateUtils.formatDateTime; public class StartupMetadataProviderIT { private static final long A_DATE = 1_500_000_000_000L; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final StartupMetadataProvider underTest = new StartupMetadataProvider(); private final System2 system = mock(System2.class); private final NodeInformation nodeInformation = mock(NodeInformation.class); @Test public void generate_SERVER_STARTIME_but_do_not_persist_it_if_server_is_startup_leader() { when(system.now()).thenReturn(A_DATE); SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.SERVER, SonarEdition.COMMUNITY); when(nodeInformation.isStartupLeader()).thenReturn(true); StartupMetadata metadata = underTest.provide(system, runtime, nodeInformation, dbTester.getDbClient()); assertThat(metadata.getStartedAt()).isEqualTo(A_DATE); assertNotPersistedProperty(CoreProperties.SERVER_STARTTIME); } @Test public void load_from_database_if_server_is_startup_follower() { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.SERVER, SonarEdition.COMMUNITY); when(nodeInformation.isStartupLeader()).thenReturn(false); testLoadingFromDatabase(runtime, false); } @Test public void load_from_database_if_compute_engine_of_startup_leader_server() { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.COMPUTE_ENGINE, SonarEdition.COMMUNITY); testLoadingFromDatabase(runtime, true); } @Test public void load_from_database_if_compute_engine_of_startup_follower_server() { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.COMPUTE_ENGINE, SonarEdition.COMMUNITY); testLoadingFromDatabase(runtime, false); } @Test public void fail_to_load_from_database_if_properties_are_not_persisted() { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.COMPUTE_ENGINE, SonarEdition.COMMUNITY); when(nodeInformation.isStartupLeader()).thenReturn(false); assertThatThrownBy(() -> underTest.provide(system, runtime, nodeInformation, dbTester.getDbClient())) .isInstanceOf(IllegalStateException.class) .hasMessage("Property sonar.core.startTime is missing in database"); } private void testLoadingFromDatabase(SonarRuntime runtime, boolean isStartupLeader) { dbTester.properties().insertProperty(new PropertyDto().setKey(CoreProperties.SERVER_STARTTIME).setValue(formatDateTime(A_DATE)), null, null,null, null); when(nodeInformation.isStartupLeader()).thenReturn(isStartupLeader); StartupMetadata metadata = underTest.provide(system, runtime, nodeInformation, dbTester.getDbClient()); assertThat(metadata.getStartedAt()).isEqualTo(A_DATE); // still in database assertPersistedProperty(CoreProperties.SERVER_STARTTIME, formatDateTime(A_DATE)); verifyNoInteractions(system); } private void assertPersistedProperty(String propertyKey, String expectedValue) { PropertyDto prop = dbTester.getDbClient().propertiesDao().selectGlobalProperty(dbTester.getSession(), propertyKey); assertThat(prop.getValue()).isEqualTo(expectedValue); } private void assertNotPersistedProperty(String propertyKey) { PropertyDto prop = dbTester.getDbClient().propertiesDao().selectGlobalProperty(dbTester.getSession(), propertyKey); assertThat(prop).isNull(); } }
5,053
41.470588
133
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/platform/monitoring/DbSectionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; public class DbSectionIT { @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); @Test public void db_info() { DbSection underTest = new DbSection(dbTester.getDbClient()); ProtobufSystemInfo.Section section = underTest.toProtobuf(); SystemInfoTesting.assertThatAttributeIs(section, "Database", "H2"); assertThat(attribute(section, "Database Version").getStringValue()).startsWith("2."); SystemInfoTesting.assertThatAttributeIs(section, "Username", "SONAR"); assertThat(attribute(section, "Driver Version").getStringValue()).startsWith("2."); SystemInfoTesting.assertThatAttributeIs(section, "Default transaction isolation", "TRANSACTION_READ_COMMITTED"); } @Test public void db_info_unknown_transaction_isolation() throws SQLException { DbClient dbClient = prepareClientWithUnknownTransactionLevel(); DbSection underTest = new DbSection(dbClient); ProtobufSystemInfo.Section section = underTest.toProtobuf(); SystemInfoTesting.assertThatAttributeIs(section, "Default transaction isolation", "Unknown transaction level: 42"); } private static DbClient prepareClientWithUnknownTransactionLevel() throws SQLException { DbClient dbClient = mock(DbClient.class); DbSession dbSession = mock(DbSession.class); Connection connection = mock(Connection.class); DatabaseMetaData metadata = mock(DatabaseMetaData.class); when(dbClient.openSession(false)).thenReturn(dbSession); when(dbSession.getConnection()).thenReturn(connection); when(connection.getMetaData()).thenReturn(metadata); when(metadata.getDefaultTransactionIsolation()).thenReturn(42); return dbClient; } }
3,116
40.013158
119
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/qualitygate/QualityGateFinderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateFinderIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbSession dbSession = db.getSession(); private final QualityGateFinder underTest = new QualityGateFinder(db.getDbClient()); @Test public void return_default_quality_gate_for_project() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto dbQualityGate = db.qualityGates().createDefaultQualityGate(qg -> qg.setName("Sonar way")); QualityGateFinder.QualityGateData result = underTest.getEffectiveQualityGate(dbSession, project); assertThat(result.getUuid()).isEqualTo(dbQualityGate.getUuid()); assertThat(result.isDefault()).isTrue(); } @Test public void return_project_quality_gate_over_default() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.qualityGates().createDefaultQualityGate(qg -> qg.setName("Sonar way")); QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.qualityGates().associateProjectToQualityGate(project, dbQualityGate); QualityGateFinder.QualityGateData result = underTest.getEffectiveQualityGate(dbSession, project); assertThat(result.getUuid()).isEqualTo(dbQualityGate.getUuid()); assertThat(result.isDefault()).isFalse(); } @Test public void fail_when_default_qgate_defined_does_not_exist() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto dbQualityGate = db.qualityGates().createDefaultQualityGate(qg -> qg.setName("Sonar way")); db.getDbClient().qualityGateDao().delete(dbQualityGate, dbSession); db.commit(); assertThatThrownBy(() -> underTest.getEffectiveQualityGate(dbSession, project)) .isInstanceOf(IllegalStateException.class) .hasMessage("Default quality gate is missing"); } @Test public void fail_when_project_qgate_defined_does_not_exist() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.qualityGates().setDefaultQualityGate(dbQualityGate); db.qualityGates().associateProjectToQualityGate(project, dbQualityGate); db.getDbClient().qualityGateDao().delete(dbQualityGate, dbSession); assertThatThrownBy(() -> underTest.getEffectiveQualityGate(dbSession, project)) .isInstanceOf(IllegalStateException.class) .hasMessage("Default quality gate is missing"); } @Test public void fail_when_qgate_property_does_not_exist() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.getDbClient().qualityGateDao().delete(dbQualityGate, dbSession); assertThatThrownBy(() -> underTest.getEffectiveQualityGate(dbSession, project)) .isInstanceOf(IllegalStateException.class) .hasMessage("Default quality gate is missing"); } @Test public void fail_when_default_quality_gate_does_not_exists() { QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.qualityGates().setDefaultQualityGate(dbQualityGate); db.getDbClient().qualityGateDao().delete(dbQualityGate, dbSession); assertThatThrownBy(() -> underTest.getDefault(dbSession)) .isInstanceOf(IllegalStateException.class) .hasMessage("Default quality gate is missing"); } }
4,802
41.131579
109
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 java.util.Collection; import java.util.Collections; import java.util.List; import org.assertj.core.groups.Tuple; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.es.EsTester; import org.sonar.server.qualityprofile.ActiveRuleChange; import static java.util.Arrays.stream; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_ACTIVE_RULE; public class ActiveRuleIndexerIT { private System2 system2 = System2.INSTANCE; @Rule public DbTester db = DbTester.create(system2); @Rule public EsTester es = EsTester.create(); private ActiveRuleIndexer underTest = new ActiveRuleIndexer(db.getDbClient(), es.client()); private RuleDto rule1; private RuleDto rule2; private QProfileDto profile1; private QProfileDto profile2; @Before public void before() { rule1 = db.rules().insert(); rule2 = db.rules().insert(); profile1 = db.qualityProfiles().insert(); profile2 = db.qualityProfiles().insert(); } @Test public void getIndexTypes() { assertThat(underTest.getIndexTypes()).containsExactly(TYPE_ACTIVE_RULE); } @Test public void indexOnStartup_does_nothing_if_no_data() { underTest.indexOnStartup(emptySet()); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isZero(); } @Test public void indexOnStartup_indexes_all_data() { ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile1, rule1); underTest.indexOnStartup(emptySet()); List<ActiveRuleDoc> docs = es.getDocuments(TYPE_ACTIVE_RULE, ActiveRuleDoc.class); assertThat(docs).hasSize(1); verify(docs.get(0), profile1, activeRule); assertThatEsQueueTableIsEmpty(); } @Test public void indexAll_indexes_all_data() { ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile1, rule1); underTest.indexAll(); List<ActiveRuleDoc> docs = es.getDocuments(TYPE_ACTIVE_RULE, ActiveRuleDoc.class); assertThat(docs).hasSize(1); verify(docs.get(0), profile1, activeRule); assertThatEsQueueTableIsEmpty(); } @Test public void test_commitAndIndex() { ActiveRuleDto ar1 = db.qualityProfiles().activateRule(profile1, rule1); ActiveRuleDto ar2 = db.qualityProfiles().activateRule(profile2, rule1); db.qualityProfiles().activateRule(profile2, rule2); commitAndIndex(rule1, ar1, ar2); verifyOnlyIndexed(ar1, ar2); assertThatEsQueueTableIsEmpty(); } @Test public void commitAndIndex_empty_list() { db.qualityProfiles().activateRule(profile1, rule1); underTest.commitAndIndex(db.getSession(), Collections.emptyList()); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isZero(); assertThatEsQueueTableIsEmpty(); } @Test public void commitAndIndex_keeps_elements_to_recover_in_ES_QUEUE_on_errors() { ActiveRuleDto ar = db.qualityProfiles().activateRule(profile1, rule1); es.lockWrites(TYPE_ACTIVE_RULE); commitAndIndex(rule1, ar); EsQueueDto expectedItem = EsQueueDto.create(TYPE_ACTIVE_RULE.format(), "ar_" + ar.getUuid(), "activeRuleUuid", ar.getRuleUuid()); assertThatEsQueueContainsExactly(expectedItem); es.unlockWrites(TYPE_ACTIVE_RULE); } @Test public void commitAndIndex_deletes_the_documents_that_dont_exist_in_database() { ActiveRuleDto ar = db.qualityProfiles().activateRule(profile1, rule1); indexAll(); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isOne(); db.getDbClient().activeRuleDao().delete(db.getSession(), ar.getKey()); commitAndIndex(rule1, ar); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isZero(); assertThatEsQueueTableIsEmpty(); } @Test public void index_fails_and_deletes_doc_if_docIdType_is_unsupported() { EsQueueDto item = EsQueueDto.create(TYPE_ACTIVE_RULE.format(), "the_id", "unsupported", "the_routing"); db.getDbClient().esQueueDao().insert(db.getSession(), item); underTest.index(db.getSession(), singletonList(item)); assertThatEsQueueTableIsEmpty(); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isZero(); } @Test public void commitDeletionOfProfiles() { ActiveRuleDto ar1 = db.qualityProfiles().activateRule(profile1, rule1); db.qualityProfiles().activateRule(profile2, rule1); db.qualityProfiles().activateRule(profile2, rule2); indexAll(); db.getDbClient().qualityProfileDao().deleteRulesProfilesByUuids(db.getSession(), singletonList(profile2.getRulesProfileUuid())); underTest.commitDeletionOfProfiles(db.getSession(), singletonList(profile2)); verifyOnlyIndexed(ar1); } @Test public void commitDeletionOfProfiles_does_nothing_if_profiles_are_not_indexed() { db.qualityProfiles().activateRule(profile1, rule1); indexAll(); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isOne(); underTest.commitDeletionOfProfiles(db.getSession(), singletonList(profile2)); assertThat(es.countDocuments(TYPE_ACTIVE_RULE)).isOne(); } private void assertThatEsQueueTableIsEmpty() { assertThat(db.countRowsOfTable(db.getSession(), "es_queue")).isZero(); } private void assertThatEsQueueContainsExactly(EsQueueDto expected) { Collection<EsQueueDto> items = db.getDbClient().esQueueDao().selectForRecovery(db.getSession(), system2.now() + 1_000, 10); assertThat(items) .extracting(EsQueueDto::getDocId, EsQueueDto::getDocIdType, EsQueueDto::getDocRouting) .containsExactlyInAnyOrder(Tuple.tuple(expected.getDocId(), expected.getDocIdType(), expected.getDocRouting())); } private void commitAndIndex(RuleDto rule, ActiveRuleDto... ar) { underTest.commitAndIndex(db.getSession(), stream(ar) .map(a -> new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, a, rule)) .toList()); } private void verifyOnlyIndexed(ActiveRuleDto... expected) { List<String> docs = es.getIds(TYPE_ACTIVE_RULE); assertThat(docs).hasSize(expected.length); for (ActiveRuleDto activeRuleDto : expected) { assertThat(docs).contains("ar_" + activeRuleDto.getUuid()); } } private void verify(ActiveRuleDoc doc1, QProfileDto profile, ActiveRuleDto activeRule) { assertThat(doc1) .matches(doc -> doc.getId().equals("ar_" + activeRule.getUuid())) .matches(doc -> doc.getRuleProfileUuid().equals(profile.getRulesProfileUuid())) .matches(doc -> doc.getSeverity().equals(activeRule.getSeverityString())); } private void indexAll() { underTest.indexOnStartup(emptySet()); } }
7,736
33.851351
133
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.Set; import org.junit.Before; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleQuery; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; import static java.util.Collections.emptySet; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DefaultRuleFinderIT { @org.junit.Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final DbClient dbClient = dbTester.getDbClient(); private final DbSession session = dbTester.getSession(); private final RuleDto rule1 = new RuleDto() .setName("Check Header") .setConfigKey("Checker/Treewalker/HeaderCheck") .setRuleKey("com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck") .setRepositoryKey("checkstyle") .setSeverity(4) .setScope(Scope.MAIN) .setStatus(RuleStatus.READY); private final RuleDto rule2 = new RuleDto() .setName("Disabled checked") .setConfigKey("Checker/Treewalker/DisabledCheck") .setRuleKey("DisabledCheck") .setRepositoryKey("checkstyle") .setSeverity(4) .setScope(Scope.MAIN) .setStatus(RuleStatus.REMOVED); private final RuleDto rule3 = new RuleDto() .setName("Check Annotation") .setConfigKey("Checker/Treewalker/AnnotationUseStyleCheck") .setRuleKey("com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationUseStyleCheck") .setRepositoryKey("checkstyle") .setSeverity(4) .setScope(Scope.MAIN) .setStatus(RuleStatus.READY); private final RuleDto rule4 = new RuleDto() .setName("Call Super First") .setConfigKey("rulesets/android.xml/CallSuperFirst") .setRuleKey("CallSuperFirst") .setRepositoryKey("pmd") .setSeverity(2) .setScope(Scope.MAIN) .setStatus(RuleStatus.READY); private final DefaultRuleFinder underTest = new DefaultRuleFinder(dbClient, mock(RuleDescriptionFormatter.class)); @Before public void setup() { dbTester.rules().insert(rule1); dbTester.rules().insert(rule2); dbTester.rules().insert(rule3); dbTester.rules().insert(rule4); session.commit(); } @Test public void should_success_finder_wrap() { // should_find_by_key Rule rule = underTest.findByKey("checkstyle", "com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck"); assertThat(rule).isNotNull(); assertThat(rule.getKey()).isEqualTo(("com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck")); assertThat(rule.isEnabled()).isTrue(); // find_should_return_null_if_no_results assertThat(underTest.findByKey("checkstyle", "unknown")).isNull(); assertThat(underTest.find(RuleQuery.create().withRepositoryKey("checkstyle").withConfigKey("unknown"))).isNull(); // find_repository_rules assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey("checkstyle"))).hasSize(2); // find_all_enabled assertThat(underTest.findAll(RuleQuery.create())).extracting(Rule::ruleKey).containsOnly(rule1.getKey(), rule3.getKey(), rule4.getKey()); // find_all assertThat(underTest.findAll()).extracting(RuleDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule()); // do_not_find_disabled_rules assertThat(underTest.findByKey("checkstyle", "DisabledCheck")).isNull(); // do_not_find_unknown_rules assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey("unknown_repository"))).isEmpty(); assertThat(underTest.findDtoByKey(RuleKey.of("pmd", "CallSuperFirst")).get().getUuid()).isEqualTo(rule4.getUuid()); assertThat(underTest.findDtoByUuid(rule4.getUuid())).isPresent(); } @Test public void should_fail_find() { assertThat(underTest.findDtoByKey(RuleKey.of("pmd", "unknown"))).isEmpty(); assertThat(underTest.findDtoByUuid("unknown")).isEmpty(); } @Test public void find_all_not_include_removed_rule() { // rule 3 is REMOVED assertThat(underTest.findAll(RuleQuery.create())).extracting(Rule::ruleKey).containsOnly(rule1.getKey(), rule3.getKey(), rule4.getKey()); assertThat(underTest.findAll()).extracting(RuleDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule()); } @Test public void findByKey_populates_system_tags_but_not_tags() { RuleDto ruleDto = dbTester.rules() .insert(t -> t.setSystemTags(Set.of(randomAlphanumeric(5), randomAlphanumeric(6))).setTags(emptySet())); dbTester.rules().insertRule(); Rule rule = underTest.findByKey(ruleDto.getKey()); assertThat(rule.getSystemTags()) .containsOnlyElementsOf(ruleDto.getSystemTags()); assertThat(rule.getTags()).isEmpty(); rule = underTest.findByKey(ruleDto.getRepositoryKey(), ruleDto.getRuleKey()); assertThat(rule.getSystemTags()) .containsOnlyElementsOf(ruleDto.getSystemTags()); assertThat(rule.getTags()).isEmpty(); } }
6,074
37.694268
150
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexDefinitionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.ImmutableMap; import java.io.IOException; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.lucene.search.TotalHits; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.indices.AnalyzeRequest; import org.elasticsearch.client.indices.AnalyzeResponse; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import org.sonar.server.es.Index; import org.sonar.server.es.IndexDefinition; import org.sonar.server.es.IndexType; import org.sonar.server.es.newindex.NewIndex; import static org.assertj.core.api.Assertions.assertThat; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.ENGLISH_HTML_ANALYZER; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_HTML_DESCRIPTION; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_KEY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_REPOSITORY; import static org.sonar.server.rule.index.RuleIndexDefinition.FIELD_RULE_UUID; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; public class RuleIndexDefinitionIT { private MapSettings settings = new MapSettings(); private RuleIndexDefinition underTest = new RuleIndexDefinition(settings.asConfig()); @Rule public EsTester tester = EsTester.create(); @Test public void test_definition_of_index() { IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext(); underTest.define(context); assertThat(context.getIndices()).hasSize(1); NewIndex<?> ruleIndex = context.getIndices().get("rules"); assertThat(ruleIndex.getMainType()) .isEqualTo(IndexType.main(Index.withRelations("rules"), "rule")); assertThat(ruleIndex.getRelationsStream()) .extracting(IndexType.IndexRelationType::getName) .containsOnly("activeRule"); // no cluster by default assertThat(ruleIndex.getSetting("index.number_of_shards")).isEqualTo("2"); assertThat(ruleIndex.getSetting("index.number_of_replicas")).isEqualTo("0"); } @Test public void enable_replica_if_clustering_is_enabled() { settings.setProperty(CLUSTER_ENABLED.getKey(), true); IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext(); underTest.define(context); NewIndex ruleIndex = context.getIndices().get("rules"); assertThat(ruleIndex.getSetting("index.number_of_replicas")).isEqualTo("1"); } @Test public void support_long_html_description() { String longText = StringUtils.repeat("The quick brown fox jumps over the lazy dog ", 700); List<AnalyzeResponse.AnalyzeToken> tokens = analyzeIndexedTokens(longText); assertThat(tokens).extracting(AnalyzeResponse.AnalyzeToken::getTerm).containsOnly( "quick", "brown", "fox", "jump", "over", "lazi", "dog"); // the following method fails if PUT fails tester.putDocuments(TYPE_RULE, new RuleDoc(ImmutableMap.of( FIELD_RULE_UUID, "123", FIELD_RULE_HTML_DESCRIPTION, longText, FIELD_RULE_REPOSITORY, "java", FIELD_RULE_KEY, "java:S001"))); assertThat(tester.countDocuments(TYPE_RULE)).isOne(); assertThat(tester.client().search(EsClient.prepareSearch(TYPE_RULE) .source(new SearchSourceBuilder() .query(matchQuery(ENGLISH_HTML_ANALYZER.subField(FIELD_RULE_HTML_DESCRIPTION), "brown fox jumps lazy")))) .getHits().getTotalHits()).isEqualTo(new TotalHits(1, TotalHits.Relation.EQUAL_TO)); } @Test public void remove_html_characters_of_html_description() { String text = "<p>html <i>line</i></p>"; List<AnalyzeResponse.AnalyzeToken> tokens = analyzeIndexedTokens(text); assertThat(tokens).extracting("term").containsOnly("html", "line"); } @Test public void sanitize_html_description_as_it_is_english() { String text = "this is a small list of words"; // "this", "is", "a" and "of" are not indexed. // Plural "words" is converted to singular "word" List<AnalyzeResponse.AnalyzeToken> tokens = analyzeIndexedTokens(text); assertThat(tokens).extracting("term").containsOnly("small", "list", "word"); } private List<AnalyzeResponse.AnalyzeToken> analyzeIndexedTokens(String text) { try { return tester.nativeClient().indices() .analyze(AnalyzeRequest.withField(TYPE_RULE.getIndex().getName(), ENGLISH_HTML_ANALYZER.subField(FIELD_RULE_HTML_DESCRIPTION), text), RequestOptions.DEFAULT) .getTokens(); } catch (IOException e) { throw new IllegalStateException("Could not analyze indexed tokens for text: " + text); } } }
5,838
42.251852
165
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.ImmutableList; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.Facets; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.security.SecurityStandards; import static com.google.common.collect.ImmutableSet.of; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static java.util.stream.IntStream.rangeClosed; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.junit.Assert.fail; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.rules.RuleType.VULNERABILITY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.setCreatedAt; import static org.sonar.db.rule.RuleTesting.setIsExternal; import static org.sonar.db.rule.RuleTesting.setIsTemplate; import static org.sonar.db.rule.RuleTesting.setLanguage; import static org.sonar.db.rule.RuleTesting.setName; import static org.sonar.db.rule.RuleTesting.setRepositoryKey; import static org.sonar.db.rule.RuleTesting.setRuleKey; import static org.sonar.db.rule.RuleTesting.setSecurityStandards; import static org.sonar.db.rule.RuleTesting.setSeverity; import static org.sonar.db.rule.RuleTesting.setStatus; import static org.sonar.db.rule.RuleTesting.setSystemTags; import static org.sonar.db.rule.RuleTesting.setTags; import static org.sonar.db.rule.RuleTesting.setTemplateId; import static org.sonar.db.rule.RuleTesting.setType; import static org.sonar.db.rule.RuleTesting.setUpdatedAt; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.OVERRIDES; import static org.sonar.server.rule.index.RuleIndex.FACET_LANGUAGES; import static org.sonar.server.rule.index.RuleIndex.FACET_REPOSITORIES; import static org.sonar.server.rule.index.RuleIndex.FACET_TAGS; import static org.sonar.server.rule.index.RuleIndex.FACET_TYPES; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_ACTIVE_RULE; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_INSECURE_INTERACTION; import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_RISKY_RESOURCE; public class RuleIndexIT { private final System2 system2 = new AlwaysIncreasingSystem2(); @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(system2); private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); private final ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); private final RuleIndex underTest = new RuleIndex(es.client(), system2); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Test public void search_all_rules() { createRule(); createRule(); index(); SearchIdResult<String> results = underTest.search(new RuleQuery(), new SearchOptions()); assertThat(results.getTotal()).isEqualTo(2); assertThat(results.getUuids()).hasSize(2); } @Test public void search_by_key() { RuleDto js1 = createRule( setRepositoryKey("javascript"), setRuleKey("X001")); RuleDto cobol1 = createRule( setRepositoryKey("cobol"), setRuleKey("X001")); createRule( setRepositoryKey("php"), setRuleKey("S002")); index(); // key RuleQuery query = new RuleQuery().setQueryText("X001"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(js1.getUuid(), cobol1.getUuid()); // partial key does not match query = new RuleQuery().setQueryText("X00"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // repo:key -> nice-to-have ! query = new RuleQuery().setQueryText("javascript:X001"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(js1.getUuid()); } @Test public void search_by_case_insensitive_key() { RuleDto ruleDto = createRule( setRepositoryKey("javascript"), setRuleKey("X001")); index(); RuleQuery query = new RuleQuery().setQueryText("x001"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(ruleDto.getUuid()); } @Test public void filter_by_key() { createRule( setRepositoryKey("javascript"), setRuleKey("X001")); createRule( setRepositoryKey("cobol"), setRuleKey("X001")); createRule( setRepositoryKey("php"), setRuleKey("S002")); index(); // key RuleQuery query = new RuleQuery().setKey(RuleKey.of("javascript", "X001").toString()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(1); // partial key does not match query = new RuleQuery().setKey("X001"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); } @Test public void search_name_by_query() { createRule(setName("testing the partial match and matching of rule")); index(); // substring RuleQuery query = new RuleQuery().setQueryText("test"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(1); // substring query = new RuleQuery().setQueryText("partial match"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(1); // case-insensitive query = new RuleQuery().setQueryText("TESTING"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(1); // not found query = new RuleQuery().setQueryText("not present"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); } @Test public void search_name_with_protected_chars() { RuleDto rule = createRule(setName("ja#va&sc\"r:ipt")); index(); RuleQuery protectedCharsQuery = new RuleQuery().setQueryText(rule.getName()); List<String> results = underTest.search(protectedCharsQuery, new SearchOptions()).getUuids(); assertThat(results).containsOnly(rule.getUuid()); } @Test public void search_content_by_query() { // it's important to set all the fields being used by the search (name, desc, key, lang, ...), // otherwise the generated random values may raise false-positives RuleDto rule1 = insertJavaRule("My great rule CWE-123 which makes your code 1000 times better!", "123", "rule 123"); RuleDto rule2 = insertJavaRule("Another great and shiny rule CWE-124", "124", "rule 124"); RuleDto rule3 = insertJavaRule("Another great rule CWE-1000", "1000", "rule 1000"); RuleDto rule4 = insertJavaRule("<h1>HTML-Geeks</h1><p style=\"color:blue\">special formatting!</p><table><tr><td>inside</td><td>tables</td></tr></table>", "404", "rule 404"); RuleDto rule5 = insertJavaRule("internationalization missunderstandings alsdkjfnadklsjfnadkdfnsksdjfn", "405", "rule 405"); index(); // partial match at word boundary assertThat(underTest.search(new RuleQuery().setQueryText("CWE"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule1.getUuid(), rule2.getUuid(), rule3.getUuid()); // full match assertThat(underTest.search(new RuleQuery().setQueryText("CWE-123"), new SearchOptions()).getUuids()).containsExactly(rule1.getUuid()); // match somewhere else in the text assertThat(underTest.search(new RuleQuery().setQueryText("CWE-1000"), new SearchOptions()).getUuids()).containsExactly(rule3.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("CWE 1000"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule3.getUuid(), rule1.getUuid()); // several words assertThat(underTest.search(new RuleQuery().setQueryText("great rule"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule1.getUuid(), rule2.getUuid(), rule3.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("rule Another"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule2.getUuid(), rule3.getUuid()); // no matches assertThat(underTest.search(new RuleQuery().setQueryText("unexisting"), new SearchOptions()).getUuids()).isEmpty(); assertThat(underTest.search(new RuleQuery().setQueryText("great rule unexisting"), new SearchOptions()).getUuids()).isEmpty(); // stopwords assertThat(underTest.search(new RuleQuery().setQueryText("and"), new SearchOptions()).getUuids()).isEmpty(); assertThat(underTest.search(new RuleQuery().setQueryText("great and shiny"), new SearchOptions()).getUuids()).isEmpty(); // html assertThat(underTest.search(new RuleQuery().setQueryText("h1"), new SearchOptions()).getUuids()).isEmpty(); assertThat(underTest.search(new RuleQuery().setQueryText("style"), new SearchOptions()).getUuids()).isEmpty(); assertThat(underTest.search(new RuleQuery().setQueryText("special"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule4.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("geeks formatting inside tables"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule4.getUuid()); // long words assertThat(underTest.search(new RuleQuery().setQueryText("missunderstand"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule5.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("missunderstandings"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule5.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("alsdkjfnadklsjfnadkdfnsksdjfn"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule5.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("internationalization"), new SearchOptions()).getUuids()).containsExactlyInAnyOrder(rule5.getUuid()); assertThat(underTest.search(new RuleQuery().setQueryText("internationalizationBlaBla"), new SearchOptions()).getUuids()).isEmpty(); } private RuleDto insertJavaRule(String description, String ruleKey, String name) { RuleDto javaRule = newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), description)) .setLanguage("java") .setRuleKey(ruleKey) .setName(name); return db.rules().insert(javaRule); } @Test public void search_by_any_of_repositories() { RuleDto findbugs = createRule( setRepositoryKey("findbugs"), setRuleKey("S001")); RuleDto pmd = createRule( setRepositoryKey("pmd"), setRuleKey("S002")); index(); RuleQuery query = new RuleQuery().setRepositories(asList("checkstyle", "pmd")); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsExactly(pmd.getUuid()); // no results query = new RuleQuery().setRepositories(singletonList("checkstyle")); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // empty list => no filter query = new RuleQuery().setRepositories(emptyList()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(findbugs.getUuid(), pmd.getUuid()); } @Test public void filter_by_tags() { RuleDto rule1 = createRule(setSystemTags("tag1s"), setTags("tag1")); RuleDto rule2 = createRule(setSystemTags("tag2s"), setTags("tag2")); index(); assertThat(es.countDocuments(TYPE_RULE)).isEqualTo(2); // tag2s in filter RuleQuery query = new RuleQuery().setTags(of("tag2s")); verifySearch(query, rule2); // tag2 in filter query = new RuleQuery().setTags(of("tag2")); verifySearch(query, rule2); // empty list => no filter query = new RuleQuery().setTags(emptySet()); verifySearch(query, rule1, rule2); // null list => no filter query = new RuleQuery().setTags(null); verifySearch(query, rule1, rule2); } @Test public void tags_facet_supports_selected_value_with_regexp_special_characters() { createRule(r -> r.setTags(Set.of("misra++"))); index(); RuleQuery query = new RuleQuery() .setTags(singletonList("misra[")); SearchOptions options = new SearchOptions().addFacets(FACET_TAGS); // do not fail assertThat(underTest.search(query, options).getTotal()).isZero(); } @Test public void search_by_types() { createRule(setType(CODE_SMELL)); RuleDto vulnerability = createRule(setType(VULNERABILITY)); RuleDto bug1 = createRule(setType(BUG)); RuleDto bug2 = createRule(setType(BUG)); index(); // find all RuleQuery query = new RuleQuery(); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(4); // type3 in filter query = new RuleQuery().setTypes(of(VULNERABILITY)); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(vulnerability.getUuid()); query = new RuleQuery().setTypes(of(BUG)); assertThat(underTest.search(query, new SearchOptions()).getUuids()).containsOnly(bug1.getUuid(), bug2.getUuid()); // types in query => nothing query = new RuleQuery().setQueryText("code smell bug vulnerability"); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // null list => no filter query = new RuleQuery().setTypes(emptySet()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(4); // null list => no filter query = new RuleQuery().setTypes(null); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(4); } @Test public void search_by_is_template() { RuleDto ruleNoTemplate = createRule(setIsTemplate(false)); RuleDto ruleIsTemplate = createRule(setIsTemplate(true)); index(); // find all RuleQuery query = new RuleQuery(); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).hasSize(2); // Only template query = new RuleQuery().setIsTemplate(true); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ruleIsTemplate.getUuid()); // Only not template query = new RuleQuery().setIsTemplate(false); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ruleNoTemplate.getUuid()); // null => no filter query = new RuleQuery().setIsTemplate(null); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ruleIsTemplate.getUuid(), ruleNoTemplate.getUuid()); } @Test public void search_by_is_external() { RuleDto ruleIsNotExternal = createRule(setIsExternal(false)); RuleDto ruleIsExternal = createRule(setIsExternal(true)); index(); // Only external RuleQuery query = new RuleQuery().setIncludeExternal(true); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ruleIsExternal.getUuid(), ruleIsNotExternal.getUuid()); // Only not external query = new RuleQuery().setIncludeExternal(false); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ruleIsNotExternal.getUuid()); } @Test public void search_by_template_key() { RuleDto template = createRule(setIsTemplate(true)); RuleDto customRule = createRule(setTemplateId(template.getUuid())); index(); // find all RuleQuery query = new RuleQuery(); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).hasSize(2); // Only custom rule query = new RuleQuery().setTemplateKey(template.getKey().toString()); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(customRule.getUuid()); // null => no filter query = new RuleQuery().setTemplateKey(null); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); } @Test public void search_by_any_of_languages() { createRule(setLanguage("java")); RuleDto javascript = createRule(setLanguage("js")); index(); RuleQuery query = new RuleQuery().setLanguages(asList("cobol", "js")); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(javascript.getUuid()); // no results query = new RuleQuery().setLanguages(singletonList("cpp")); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // empty list => no filter query = new RuleQuery().setLanguages(emptyList()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); // null list => no filter query = new RuleQuery().setLanguages(null); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); } @Test public void search_by_security_cwe_return_vulnerabilities_and_hotspots_only() { RuleDto rule1 = createRule(setSecurityStandards(of("cwe:543", "cwe:123", "owaspTop10:a1")), r -> r.setType(VULNERABILITY)); RuleDto rule2 = createRule(setSecurityStandards(of("cwe:543", "owaspTop10:a1")), r -> r.setType(SECURITY_HOTSPOT)); createRule(setSecurityStandards(of("owaspTop10:a1")), r -> r.setType(CODE_SMELL)); index(); RuleQuery query = new RuleQuery().setCwe(of("543")); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("cwe")); assertThat(results.getUuids()).containsOnly(rule1.getUuid(), rule2.getUuid()); } @Test public void search_by_security_owaspTop10_2017_return_vulnerabilities_and_hotspots_only() { RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:543")), r -> r.setType(VULNERABILITY)); RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT)); createRule(setSecurityStandards(of("cwe:543")), r -> r.setType(CODE_SMELL)); index(); RuleQuery query = new RuleQuery().setOwaspTop10(of("a5", "a10")); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("owaspTop10")); assertThat(results.getUuids()).containsOnly(rule1.getUuid(), rule2.getUuid()); } @Test public void search_by_security_owaspTop10_2021_return_vulnerabilities_and_hotspots_only() { RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10-2021:a1", "owaspTop10-2021:a10", "cwe:543")), r -> r.setType(VULNERABILITY)); RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10-2021:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT)); createRule(setSecurityStandards(of("cwe:543")), r -> r.setType(CODE_SMELL)); index(); RuleQuery query = new RuleQuery().setOwaspTop10For2021(of("a5", "a10")); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("owaspTop10-2021")); assertThat(results.getUuids()).containsOnly(rule1.getUuid(), rule2.getUuid()); } @Test public void search_by_security_sansTop25_return_vulnerabilities_and_hotspots_only() { RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:89")), r -> r.setType(VULNERABILITY)); RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:829")), r -> r.setType(SECURITY_HOTSPOT)); createRule(setSecurityStandards(of("cwe:306")), r -> r.setType(CODE_SMELL)); index(); RuleQuery query = new RuleQuery().setSansTop25(of(SANS_TOP_25_INSECURE_INTERACTION, SANS_TOP_25_RISKY_RESOURCE)); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("sansTop25")); assertThat(results.getUuids()).containsOnly(rule1.getUuid(), rule2.getUuid()); } @Test public void search_by_security_sonarsource_return_vulnerabilities_and_hotspots_only() { RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10-2021:a10", "cwe:89")), r -> r.setType(VULNERABILITY)); createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:829")), r -> r.setType(CODE_SMELL)); RuleDto rule3 = createRule(setSecurityStandards(of("cwe:601")), r -> r.setType(SECURITY_HOTSPOT)); index(); RuleQuery query = new RuleQuery().setSonarsourceSecurity(of("sql-injection", "open-redirect")); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("sonarsourceSecurity")); assertThat(results.getUuids()).containsOnly(rule1.getUuid(), rule3.getUuid()); } @Test public void search_by_security_sonarsource_return_complete_list_of_facets() { List<RuleDto> rules = new ArrayList<>(); //Creation of one rule for each standard security category defined (except other) for (Map.Entry<SecurityStandards.SQCategory, Set<String>> sqCategorySetEntry : SecurityStandards.CWES_BY_SQ_CATEGORY.entrySet()) { rules.add(createRule(setSecurityStandards(of("cwe:" + sqCategorySetEntry.getValue().iterator().next())), r -> r.setType(SECURITY_HOTSPOT))); } index(); RuleQuery query = new RuleQuery(); SearchIdResult<String> results = underTest.search(query, new SearchOptions().addFacets("sonarsourceSecurity")); assertThat(results.getFacets().get("sonarsourceSecurity")) .as("It should have as many facets returned as there are rules defined, and it is not truncated") .hasSize(rules.size()); } @Test public void compare_to_another_profile() { String xoo = "xoo"; QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(xoo)); QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setLanguage(xoo)); RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(xoo)); RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo)); RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo)); RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(xoo)); RuleDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo)); RuleDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo)); db.qualityProfiles().activateRule(profile, commonRule); db.qualityProfiles().activateRule(profile, profileRule1); db.qualityProfiles().activateRule(profile, profileRule2); db.qualityProfiles().activateRule(profile, profileRule3); db.qualityProfiles().activateRule(anotherProfile, commonRule); db.qualityProfiles().activateRule(anotherProfile, anotherProfileRule1); db.qualityProfiles().activateRule(anotherProfile, anotherProfileRule2); index(); verifySearch(newRuleQuery().setActivation(false).setQProfile(profile).setCompareToQProfile(anotherProfile), anotherProfileRule1, anotherProfileRule2); verifySearch(newRuleQuery().setActivation(true).setQProfile(profile).setCompareToQProfile(anotherProfile), commonRule); verifySearch(newRuleQuery().setActivation(true).setQProfile(profile).setCompareToQProfile(profile), commonRule, profileRule1, profileRule2, profileRule3); verifySearch(newRuleQuery().setActivation(false).setQProfile(profile).setCompareToQProfile(profile)); } @SafeVarargs private RuleDto createRule(Consumer<RuleDto>... consumers) { return db.rules().insert(consumers); } private RuleDto createJavaRule() { return createRule(r -> r.setLanguage("java")); } @Test public void search_by_any_of_severities() { createRule(setSeverity(BLOCKER)); RuleDto info = createRule(setSeverity(INFO)); index(); RuleQuery query = new RuleQuery().setSeverities(asList(INFO, MINOR)); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(info.getUuid()); // no results query = new RuleQuery().setSeverities(singletonList(MINOR)); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // empty list => no filter query = new RuleQuery().setSeverities(emptyList()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); // null list => no filter query = new RuleQuery().setSeverities(); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); } @Test public void search_by_any_of_statuses() { createRule(setStatus(RuleStatus.BETA)); RuleDto ready = createRule(setStatus(RuleStatus.READY)); index(); RuleQuery query = new RuleQuery().setStatuses(asList(RuleStatus.DEPRECATED, RuleStatus.READY)); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsOnly(ready.getUuid()); // no results query = new RuleQuery().setStatuses(singletonList(RuleStatus.DEPRECATED)); assertThat(underTest.search(query, new SearchOptions()).getUuids()).isEmpty(); // empty list => no filter query = new RuleQuery().setStatuses(emptyList()); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); // null list => no filter query = new RuleQuery().setStatuses(null); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(2); } @Test public void activation_parameter_is_ignored_if_profile_is_not_set() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); QProfileDto profile1 = createJavaProfile(); db.qualityProfiles().activateRule(profile1, rule1); index(); // all rules are returned verifySearch(newRuleQuery().setActivation(true), rule1, rule2); } @Test public void search_by_activation() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); RuleDto rule3 = createJavaRule(); QProfileDto profile1 = createJavaProfile(); QProfileDto profile2 = createJavaProfile(); db.qualityProfiles().activateRule(profile1, rule1); db.qualityProfiles().activateRule(profile2, rule1); db.qualityProfiles().activateRule(profile1, rule2); index(); // active rules verifySearch(newRuleQuery().setActivation(true).setQProfile(profile1), rule1, rule2); verifySearch(newRuleQuery().setActivation(true).setQProfile(profile2), rule1); // inactive rules verifySearch(newRuleQuery().setActivation(false).setQProfile(profile1), rule3); verifySearch(newRuleQuery().setActivation(false).setQProfile(profile2), rule2, rule3); } private void verifyEmptySearch(RuleQuery query) { verifySearch(query); } private void verifySearch(RuleQuery query, RuleDto... expectedRules) { SearchIdResult<String> result = underTest.search(query, new SearchOptions()); assertThat(result.getTotal()).isEqualTo(expectedRules.length); assertThat(result.getUuids()).hasSize(expectedRules.length); for (RuleDto expectedRule : expectedRules) { assertThat(result.getUuids()).contains(expectedRule.getUuid()); } } private void index() { ruleIndexer.indexOnStartup(Sets.newHashSet(TYPE_RULE)); activeRuleIndexer.indexOnStartup(Sets.newHashSet(TYPE_ACTIVE_RULE)); } private RuleQuery newRuleQuery() { return new RuleQuery(); } private QProfileDto createJavaProfile() { return db.qualityProfiles().insert(p -> p.setLanguage("java")); } @Test public void search_by_activation_and_inheritance() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); RuleDto rule3 = createJavaRule(); RuleDto rule4 = createJavaRule(); QProfileDto parent = createJavaProfile(); QProfileDto child = createJavaProfile(); db.qualityProfiles().activateRule(parent, rule1); db.qualityProfiles().activateRule(parent, rule2); db.qualityProfiles().activateRule(parent, rule3); db.qualityProfiles().activateRule(child, rule1, ar -> ar.setInheritance(INHERITED.name())); db.qualityProfiles().activateRule(child, rule2, ar -> ar.setInheritance(OVERRIDES.name())); db.qualityProfiles().activateRule(child, rule3, ar -> ar.setInheritance(INHERITED.name())); index(); // all rules verifySearch(newRuleQuery(), rule1, rule2, rule3, rule4); // inherited/overrides rules on parent verifyEmptySearch(newRuleQuery().setActivation(true).setQProfile(parent).setInheritance(of(INHERITED.name()))); verifyEmptySearch(newRuleQuery().setActivation(true).setQProfile(parent).setInheritance(of(OVERRIDES.name()))); // inherited/overrides rules on child verifySearch(newRuleQuery().setActivation(true).setQProfile(child).setInheritance(of(INHERITED.name())), rule1, rule3); verifySearch(newRuleQuery().setActivation(true).setQProfile(child).setInheritance(of(OVERRIDES.name())), rule2); // inherited AND overridden on parent verifyEmptySearch(newRuleQuery().setActivation(true).setQProfile(parent).setInheritance(of(INHERITED.name(), OVERRIDES.name()))); // inherited AND overridden on child verifySearch(newRuleQuery().setActivation(true).setQProfile(child).setInheritance(of(INHERITED.name(), OVERRIDES.name())), rule1, rule2, rule3); } @Test public void search_by_activation_and_severity() { RuleDto major = createRule(setSeverity(MAJOR)); RuleDto minor = createRule(setSeverity(MINOR)); createRule(setSeverity(INFO)); QProfileDto profile1 = createJavaProfile(); QProfileDto profile2 = createJavaProfile(); db.qualityProfiles().activateRule(profile1, major, ar -> ar.setSeverity(BLOCKER)); db.qualityProfiles().activateRule(profile2, major, ar -> ar.setSeverity(BLOCKER)); db.qualityProfiles().activateRule(profile1, minor, ar -> ar.setSeverity(CRITICAL)); index(); // count activation severities of all active rules RuleQuery query = newRuleQuery().setActivation(true).setQProfile(profile1); verifySearch(query, major, minor); verifyFacet(query, RuleIndex.FACET_ACTIVE_SEVERITIES, entry(BLOCKER, 1L), entry(CRITICAL, 1L)); // check stickyness of active severity facet query = newRuleQuery().setActivation(true).setQProfile(profile1).setActiveSeverities(singletonList(CRITICAL)); verifySearch(query, minor); verifyFacet(query, RuleIndex.FACET_ACTIVE_SEVERITIES, entry(BLOCKER, 1L), entry(CRITICAL, 1L)); } @Test public void facet_by_activation_severity_is_ignored_when_profile_is_not_specified() { RuleDto rule = createJavaRule(); QProfileDto profile = createJavaProfile(); db.qualityProfiles().activateRule(profile, rule); index(); RuleQuery query = newRuleQuery(); verifyNoFacet(query, RuleIndex.FACET_ACTIVE_SEVERITIES); } private void verifyFacet(RuleQuery query, String facet, Map.Entry<String, Long>... expectedBuckets) { SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(facet)); assertThat(result.getFacets().get(facet)) .containsOnly(expectedBuckets); } private void verifyNoFacet(RuleQuery query, String facet) { SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(facet)); assertThat(result.getFacets().get(facet)).isNull(); } @Test public void listTags_should_return_tags() { createRule(setSystemTags("sys1", "sys2"), setTags("tag1")); createRule(setSystemTags(), setTags("tag2")); index(); assertThat(underTest.listTags(null, 10)).containsOnly("tag1", "tag2", "sys1", "sys2"); } @Test public void fail_to_list_tags_when_size_greater_than_500() { assertThatThrownBy(() -> underTest.listTags(null, 501)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Page size must be lower than or equals to 500"); } @Test public void available_since() { RuleDto ruleOld = createRule(setCreatedAt(-2_000L)); RuleDto ruleOlder = createRule(setCreatedAt(-1_000L)); index(); // 0. find all rules; verifySearch(new RuleQuery(), ruleOld, ruleOlder); // 1. find all rules available since a date; RuleQuery availableSinceQuery = new RuleQuery().setAvailableSince(-1000L); verifySearch(availableSinceQuery, ruleOlder); // 2. find no new rules since tomorrow. RuleQuery availableSinceNowQuery = new RuleQuery().setAvailableSince(1000L); verifyEmptySearch(availableSinceNowQuery); } @Test public void global_facet_on_repositories_and_tags() { createRule(setRepositoryKey("php"), setSystemTags("sysTag"), setTags()); createRule(setRepositoryKey("php"), setSystemTags(), setTags("tag1")); createRule(setRepositoryKey("javascript"), setSystemTags(), setTags("tag1", "tag2")); index(); // should not have any facet! RuleQuery query = new RuleQuery(); SearchIdResult result1 = underTest.search(query, new SearchOptions()); assertThat(result1.getFacets().getAll()).isEmpty(); // should not have any facet on non matching query! SearchIdResult result2 = underTest.search(new RuleQuery().setQueryText("aeiou"), new SearchOptions().addFacets(singletonList("repositories"))); assertThat(result2.getFacets().getAll()).hasSize(1); assertThat(result2.getFacets().getAll().get("repositories")).isEmpty(); // Repositories Facet is preset SearchIdResult result3 = underTest.search(query, new SearchOptions().addFacets(asList("repositories", "tags"))); assertThat(result3.getFacets()).isNotNull(); // Verify the value of a given facet Map<String, Long> repoFacets = result3.getFacets().get("repositories"); assertThat(repoFacets).containsOnly(entry("php", 2L), entry("javascript", 1L)); // Check that tag facet has both Tags and SystemTags values Map<String, Long> tagFacets = result3.getFacets().get("tags"); assertThat(tagFacets).containsOnly(entry("tag1", 2L), entry("sysTag", 1L), entry("tag2", 1L)); // Check that there are no other facets assertThat(result3.getFacets().getAll()).hasSize(2); } private void setupStickyFacets() { createRule(setRepositoryKey("xoo"), setRuleKey("S001"), setLanguage("java"), setTags(), setSystemTags(), setType(BUG)); createRule(setRepositoryKey("xoo"), setRuleKey("S002"), setLanguage("java"), setTags(), setSystemTags(), setType(CODE_SMELL)); createRule(setRepositoryKey("xoo"), setRuleKey("S003"), setLanguage("java"), setTags(), setSystemTags("T1", "T2"), setType(CODE_SMELL)); createRule(setRepositoryKey("xoo"), setRuleKey("S011"), setLanguage("cobol"), setTags(), setSystemTags(), setType(CODE_SMELL)); createRule(setRepositoryKey("xoo"), setRuleKey("S012"), setLanguage("cobol"), setTags(), setSystemTags(), setType(BUG)); createRule(setRepositoryKey("foo"), setRuleKey("S013"), setLanguage("cobol"), setTags(), setSystemTags("T3", "T4"), setType(VULNERABILITY)); createRule(setRepositoryKey("foo"), setRuleKey("S111"), setLanguage("cpp"), setTags(), setSystemTags(), setType(BUG)); createRule(setRepositoryKey("foo"), setRuleKey("S112"), setLanguage("cpp"), setTags(), setSystemTags(), setType(CODE_SMELL)); createRule(setRepositoryKey("foo"), setRuleKey("S113"), setLanguage("cpp"), setTags(), setSystemTags("T2", "T3"), setType(CODE_SMELL)); index(); } @Test public void sticky_facets_base() { setupStickyFacets(); RuleQuery query = new RuleQuery(); assertThat(underTest.search(query, new SearchOptions()).getUuids()).hasSize(9); } /** * Facet with no filters at all */ @Test public void sticky_facets_no_filters() { setupStickyFacets(); RuleQuery query = new RuleQuery(); SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(asList(FACET_LANGUAGES, FACET_REPOSITORIES, FACET_TAGS, FACET_TYPES))); Map<String, LinkedHashMap<String, Long>> facets = result.getFacets().getAll(); assertThat(facets).hasSize(4); assertThat(facets.get(FACET_LANGUAGES)).containsOnlyKeys("cpp", "java", "cobol"); assertThat(facets.get(FACET_REPOSITORIES).keySet()).containsExactly("xoo", "foo"); assertThat(facets.get(FACET_TAGS)).containsOnlyKeys("T1", "T2", "T3", "T4"); assertThat(facets.get(FACET_TYPES)).containsOnlyKeys("BUG", "CODE_SMELL", "VULNERABILITY"); } /** * Facet with a language filter * -- lang facet should still have all language */ @Test public void sticky_facets_with_1_filter() { setupStickyFacets(); RuleQuery query = new RuleQuery().setLanguages(ImmutableList.of("cpp")); SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(asList(FACET_LANGUAGES, FACET_REPOSITORIES, FACET_TAGS))); assertThat(result.getUuids()).hasSize(3); assertThat(result.getFacets().getAll()).hasSize(3); assertThat(result.getFacets().get(FACET_LANGUAGES)).containsOnlyKeys("cpp", "java", "cobol"); assertThat(result.getFacets().get(FACET_REPOSITORIES)).containsOnlyKeys("foo"); assertThat(result.getFacets().get(FACET_TAGS)).containsOnlyKeys("T2", "T3"); } @Test public void languages_facet_should_return_top_100_items() { rangeClosed(1, 101).forEach(i -> db.rules().insert(r -> r.setLanguage("lang" + i))); index(); SearchIdResult<String> result = underTest.search(new RuleQuery(), new SearchOptions().addFacets(singletonList(FACET_LANGUAGES))); assertThat(result.getFacets().get(FACET_LANGUAGES)).hasSize(100); } @Test public void repositories_facet_should_return_top_100_items() { rangeClosed(1, 101).forEach(i -> db.rules().insert(r -> r.setRepositoryKey("repo" + i))); index(); SearchIdResult<String> result = underTest.search(new RuleQuery(), new SearchOptions().addFacets(singletonList(FACET_REPOSITORIES))); assertThat(result.getFacets().get(FACET_REPOSITORIES)).hasSize(100); } @Test public void tags_facet_should_find_tags() { createRule(setSystemTags(), setTags("bla")); index(); RuleQuery query = new RuleQuery(); SearchOptions options = new SearchOptions().addFacets(singletonList(FACET_TAGS)); SearchIdResult<String> result = underTest.search(query, options); assertThat(result.getFacets().get(FACET_TAGS)).contains(entry("bla", 1L)); } @Test public void tags_facet_should_return_top_100_items() { // default number of items returned in tag facet = 100 String[] tags = get101Tags(); createRule(setSystemTags(tags)); index(); RuleQuery query = new RuleQuery(); SearchOptions options = new SearchOptions().addFacets(singletonList(FACET_TAGS)); SearchIdResult<String> result = underTest.search(query, options); assertThat(result.getFacets().get(FACET_TAGS)).hasSize(100); assertThat(result.getFacets().get(FACET_TAGS)).contains(entry("tag0", 1L), entry("tag25", 1L), entry("tag99", 1L)); assertThat(result.getFacets().get(FACET_TAGS)).doesNotContain(entry("tagA", 1L)); } @Test public void tags_facet_should_include_matching_selected_items() { // default number of items returned in tag facet = 100 String[] tags = get101Tags(); createRule(setSystemTags(tags)); index(); RuleQuery query = new RuleQuery() .setTags(singletonList("tagA")); SearchOptions options = new SearchOptions().addFacets(singletonList(FACET_TAGS)); SearchIdResult<String> result = underTest.search(query, options); assertThat(result.getFacets().get(FACET_TAGS)).hasSize(101); assertThat(result.getFacets().get(FACET_TAGS).entrySet()).extracting(e -> entry(e.getKey(), e.getValue())).contains( // check that selected item is added, although there are 100 other items entry("tagA", 1L), entry("tag0", 1L), entry("tag25", 1L), entry("tag99", 1L)); } @Test public void tags_facet_should_be_available() { RuleQuery query = new RuleQuery(); SearchOptions options = new SearchOptions().addFacets(singletonList(FACET_TAGS)); SearchIdResult<String> result = underTest.search(query, options); assertThat(result.getFacets().get(FACET_TAGS)).isNotNull(); } /** * Facet with 2 filters * -- lang facet for tag T2 * -- tag facet for lang cpp * -- repository for cpp & T2 */ @Test public void sticky_facets_with_2_filters() { setupStickyFacets(); RuleQuery query = new RuleQuery() .setLanguages(ImmutableList.of("cpp")) .setTags(ImmutableList.of("T2")); SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(asList(FACET_LANGUAGES, FACET_REPOSITORIES, FACET_TAGS))); assertThat(result.getUuids()).hasSize(1); Facets facets = result.getFacets(); assertThat(facets.getAll()).hasSize(3); assertThat(facets.get(FACET_LANGUAGES)).containsOnlyKeys("cpp", "java"); assertThat(facets.get(FACET_REPOSITORIES)).containsOnlyKeys("foo"); assertThat(facets.get(FACET_TAGS)).containsOnlyKeys("T2", "T3"); } /** * Facet with 3 filters * -- lang facet for tag T2 * -- tag facet for lang cpp & java * -- repository for (cpp || java) & T2 * -- type */ @Test public void sticky_facets_with_3_filters() { setupStickyFacets(); RuleQuery query = new RuleQuery() .setLanguages(ImmutableList.of("cpp", "java")) .setTags(ImmutableList.of("T2")) .setTypes(asList(BUG, CODE_SMELL)); SearchIdResult<String> result = underTest.search(query, new SearchOptions().addFacets(asList(FACET_LANGUAGES, FACET_REPOSITORIES, FACET_TAGS, FACET_TYPES))); assertThat(result.getUuids()).hasSize(2); assertThat(result.getFacets().getAll()).hasSize(4); assertThat(result.getFacets().get(FACET_LANGUAGES)).containsOnlyKeys("cpp", "java"); assertThat(result.getFacets().get(FACET_REPOSITORIES)).containsOnlyKeys("foo", "xoo"); assertThat(result.getFacets().get(FACET_TAGS)).containsOnlyKeys("T1", "T2", "T3"); assertThat(result.getFacets().get(FACET_TYPES)).containsOnlyKeys("CODE_SMELL"); } @Test public void sort_by_name() { RuleDto abcd = createRule(setName("abcd")); RuleDto abc = createRule(setName("ABC")); RuleDto fgh = createRule(setName("FGH")); index(); // ascending RuleQuery query = new RuleQuery().setSortField(RuleIndexDefinition.FIELD_RULE_NAME); SearchIdResult<String> results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsExactly(abc.getUuid(), abcd.getUuid(), fgh.getUuid()); // descending query = new RuleQuery().setSortField(RuleIndexDefinition.FIELD_RULE_NAME).setAscendingSort(false); results = underTest.search(query, new SearchOptions()); assertThat(results.getUuids()).containsExactly(fgh.getUuid(), abcd.getUuid(), abc.getUuid()); } @Test public void default_sort_is_by_updated_at_desc() { long currentTimeMillis = System.currentTimeMillis(); RuleDto old = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 1000L)); RuleDto oldest = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 3000L)); RuleDto older = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 2000L)); index(); SearchIdResult<String> results = underTest.search(new RuleQuery(), new SearchOptions()); assertThat(results.getUuids()).containsExactly(oldest.getUuid(), older.getUuid(), old.getUuid()); } @Test public void fail_sort_by_language() { try { // Sorting on a field not tagged as sortable new RuleQuery().setSortField(RuleIndexDefinition.FIELD_RULE_LANGUAGE); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Field 'lang' is not sortable"); } } @Test public void paging() { createRule(); createRule(); createRule(); index(); // from 0 to 1 included SearchOptions options = new SearchOptions(); options.setOffset(0).setLimit(2); SearchIdResult<String> results = underTest.search(new RuleQuery(), options); assertThat(results.getTotal()).isEqualTo(3); assertThat(results.getUuids()).hasSize(2); // from 0 to 9 included options.setOffset(0).setLimit(10); results = underTest.search(new RuleQuery(), options); assertThat(results.getTotal()).isEqualTo(3); assertThat(results.getUuids()).hasSize(3); // from 2 to 11 included options.setOffset(2).setLimit(10); results = underTest.search(new RuleQuery(), options); assertThat(results.getTotal()).isEqualTo(3); assertThat(results.getUuids()).hasSize(1); } @Test public void search_all_keys_by_query() { createRule(setRepositoryKey("javascript"), setRuleKey("X001")); createRule(setRepositoryKey("cobol"), setRuleKey("X001")); createRule(setRepositoryKey("php"), setRuleKey("S002")); index(); // key assertThat(underTest.searchAll(new RuleQuery().setQueryText("X001"))).toIterable().hasSize(2); // partial key does not match assertThat(underTest.searchAll(new RuleQuery().setQueryText("X00"))).toIterable().isEmpty(); // repo:key -> nice-to-have ! assertThat(underTest.searchAll(new RuleQuery().setQueryText("javascript:X001"))).toIterable().hasSize(1); } @Test public void searchAll_keys_by_profile() { RuleDto rule1 = createRule(); RuleDto rule2 = createRule(); RuleDto rule3 = createRule(); QProfileDto profile1 = createJavaProfile(); QProfileDto profile2 = createJavaProfile(); db.qualityProfiles().activateRule(profile1, rule1); db.qualityProfiles().activateRule(profile2, rule1); db.qualityProfiles().activateRule(profile1, rule2); index(); // inactive rules on profile es.getDocuments(TYPE_RULE); es.getDocuments(TYPE_ACTIVE_RULE); assertThat(underTest.searchAll(new RuleQuery().setActivation(false).setQProfile(profile2))) .toIterable() .containsOnly(rule2.getUuid(), rule3.getUuid()); // active rules on profile assertThat(underTest.searchAll(new RuleQuery().setActivation(true).setQProfile(profile2))) .toIterable() .containsOnly(rule1.getUuid()); } private String[] get101Tags() { String[] tags = new String[101]; for (int i = 0; i < 100; i++) { tags[i] = "tag" + i; } tags[100] = "tagA"; return tags; } }
48,332
42.154464
179
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.event.Level; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; import org.sonar.server.es.EsTester; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.SQCategory; import static com.google.common.collect.Sets.newHashSet; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; import static org.sonar.server.security.SecurityStandards.CWES_BY_SQ_CATEGORY; import static org.sonar.server.security.SecurityStandards.SQ_CATEGORY_KEYS_ORDERING; @RunWith(DataProviderRunner.class) public class RuleIndexerIT { private static final String VALID_HOTSPOT_RULE_DESCRIPTION = "acme\n" + "<h2>Ask Yourself Whether</h2>\n" + "bar\n" + "<h2>Recommended Secure Coding Practices</h2>\n" + "foo"; private static final UuidFactoryFast uuidFactory = UuidFactoryFast.getInstance(); private static final RuleDescriptionSectionDto RULE_DESCRIPTION_SECTION_DTO = createDefaultRuleDescriptionSection(uuidFactory.create(), VALID_HOTSPOT_RULE_DESCRIPTION); private static final RuleDescriptionSectionDto RULE_DESCRIPTION_SECTION_DTO2 = RuleDescriptionSectionDto.builder() .uuid(uuidFactory.create()) .key("section2") .content("rule descriptions section 2") .build(); @Rule public EsTester es = EsTester.create(); @Rule public DbTester dbTester = DbTester.create(); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = dbTester.getDbClient(); private final RuleIndexer underTest = new RuleIndexer(es.client(), dbClient); private final DbSession dbSession = dbTester.getSession(); private final RuleDto rule = new RuleDto() .setUuid("rule-uuid") .setRuleKey("S001") .setRepositoryKey("xoo") .setConfigKey("S1") .setName("Null Pointer") .setDescriptionFormat(RuleDto.Format.HTML) .addRuleDescriptionSectionDto(RULE_DESCRIPTION_SECTION_DTO) .setLanguage("xoo") .setSeverity(Severity.BLOCKER) .setStatus(RuleStatus.READY) .setIsTemplate(true) .setSystemTags(newHashSet("cwe")) .setType(RuleType.BUG) .setScope(Scope.ALL) .setCreatedAt(1500000000000L) .setUpdatedAt(1600000000000L); @Test public void index_nothing() { underTest.index(dbSession, emptyList()); assertThat(es.countDocuments(TYPE_RULE)).isZero(); } @Test public void index() { dbClient.ruleDao().insert(dbSession, rule); underTest.commitAndIndex(dbSession, rule.getUuid()); assertThat(es.countDocuments(TYPE_RULE)).isOne(); } @Test public void removed_rule_is_not_removed_from_index() { // Create and Index rule dbClient.ruleDao().insert(dbSession, rule.setStatus(RuleStatus.READY)); dbSession.commit(); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(es.countDocuments(TYPE_RULE)).isOne(); // Remove rule dbTester.getDbClient().ruleDao().update(dbTester.getSession(), rule.setStatus(RuleStatus.READY).setUpdatedAt(2000000000000L)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(es.countDocuments(TYPE_RULE)).isOne(); } @Test public void index_long_rule_description() { RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), randomAlphanumeric(100000)); RuleDto rule = dbTester.rules().insert(newRule(ruleDescriptionSectionDto)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(es.countDocuments(TYPE_RULE)).isOne(); } @Test public void index_long_rule_with_several_sections() { RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO, RULE_DESCRIPTION_SECTION_DTO2)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); List<RuleDoc> ruleDocs = es.getDocuments(TYPE_RULE, RuleDoc.class); assertThat(ruleDocs).hasSize(1); assertThat(ruleDocs.iterator().next().htmlDescription()) .contains(RULE_DESCRIPTION_SECTION_DTO.getContent()) .contains(RULE_DESCRIPTION_SECTION_DTO2.getContent()) .hasSize(RULE_DESCRIPTION_SECTION_DTO.getContent().length() + " ".length() + RULE_DESCRIPTION_SECTION_DTO2.getContent().length()); } @Test public void index_long_rule_with_section_in_markdown() { RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO).setDescriptionFormat(RuleDto.Format.MARKDOWN)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); List<RuleDoc> ruleDocs = es.getDocuments(TYPE_RULE, RuleDoc.class); assertThat(ruleDocs).hasSize(1); assertThat(ruleDocs.iterator().next().htmlDescription()) .isEqualTo("acme<br/>&lt;h2&gt;Ask Yourself Whether&lt;/h2&gt;<br/>bar<br/>" + "&lt;h2&gt;Recommended Secure Coding Practices&lt;/h2&gt;<br/>foo"); } @Test @UseDataProvider("twoDifferentCategoriesButOTHERS") public void log_debug_if_hotspot_rule_maps_to_multiple_SQCategories(SQCategory sqCategory1, SQCategory sqCategory2) { logTester.setLevel(Level.DEBUG); Set<String> standards = Stream.of(sqCategory1, sqCategory2) .flatMap(t -> CWES_BY_SQ_CATEGORY.get(t).stream().map(e -> "cwe:" + e)) .collect(toSet()); SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(standards); RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO) .setType(RuleType.SECURITY_HOTSPOT) .setSecurityStandards(standards)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(logTester.logs(Level.DEBUG)) .contains(format( "Rule %s with CWEs '%s' maps to multiple SQ Security Categories: %s", rule.getKey(), String.join(", ", securityStandards.getCwe()), ImmutableSet.of(sqCategory1, sqCategory2).stream() .map(SQCategory::getKey) .sorted(SQ_CATEGORY_KEYS_ORDERING) .collect(joining(", ")))); } @DataProvider public static Object[][] twoDifferentCategoriesButOTHERS() { EnumSet<SQCategory> sqCategories = EnumSet.allOf(SQCategory.class); sqCategories.remove(SQCategory.OTHERS); // pick two random categories Random random = new Random(); SQCategory sqCategory1 = sqCategories.toArray(new SQCategory[0])[random.nextInt(sqCategories.size())]; sqCategories.remove(sqCategory1); SQCategory sqCategory2 = sqCategories.toArray(new SQCategory[0])[random.nextInt(sqCategories.size())]; return new Object[][]{ {sqCategory1, sqCategory2} }; } }
8,696
39.640187
170
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/setting/DatabaseSettingLoaderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; public class DatabaseSettingLoaderIT { private static final String A_KEY = "a_key"; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private DatabaseSettingLoader underTest = new DatabaseSettingLoader(dbTester.getDbClient()); @Test public void test_load() { insertPropertyIntoDb(A_KEY, "foo"); assertThat(underTest.load(A_KEY)).isEqualTo("foo"); assertThat(underTest.load("missing")).isNull(); } @Test public void null_value_in_db_is_considered_as_empty_string() { insertPropertyIntoDb(A_KEY, null); assertThat(underTest.load(A_KEY)).isEmpty(); } @Test public void test_empty_value_in_db() { insertPropertyIntoDb(A_KEY, ""); assertThat(underTest.load(A_KEY)).isEmpty(); } @Test public void test_loadAll_with_no_properties() { Map<String, String> map = underTest.loadAll(); assertThat(map).isEmpty(); } @Test public void test_loadAll() { insertPropertyIntoDb("foo", "1"); insertPropertyIntoDb("bar", "2"); Map<String, String> map = underTest.loadAll(); assertThat(map).containsOnly(entry("foo", "1"), entry("bar", "2")); } private void insertPropertyIntoDb(String key, String value) { dbTester.getDbClient().propertiesDao().saveProperty(new PropertyDto().setKey(key).setValue(value)); } }
2,485
28.951807
103
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/setting/ProjectConfigurationLoaderImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import static org.assertj.core.api.Assertions.assertThat; public class ProjectConfigurationLoaderImplIT { @Rule public DbTester db = DbTester.create(); private final static String GLOBAL_PROP_KEY = "GLOBAL_PROP_KEY"; private final static String GLOBAL_PROP_VALUE = "GLOBAL_PROP_VALUE"; private final static String MAIN_BRANCH_PROP_KEY = "MAIN_BRANCH_PROP_KEY"; private final static String MAIN_BRANCH_PROP_VALUE = "MAIN_BRANCH_PROP_VALUE"; private final static String BRANCH_PROP_KEY = "BRANCH_PROP_KEY"; private final static String BRANCH_PROP_VALUE = "BRANCH_PROP_VALUE"; private final static String MAIN_BRANCH_UUID = "MAIN_BRANCH_UUID"; private final static String BRANCH_UUID = "BRANCH_UUID"; private final MapSettings globalSettings = new MapSettings(); private ProjectConfigurationLoaderImpl underTest; @Before public void setUp() { underTest = new ProjectConfigurationLoaderImpl(globalSettings, db.getDbClient()); } @Test public void return_configuration_with_just_global_settings_when_no_component_settings() { globalSettings.setProperty(MAIN_BRANCH_PROP_KEY, MAIN_BRANCH_PROP_VALUE); BranchDto mainBranch = insertBranch(MAIN_BRANCH_UUID, MAIN_BRANCH_UUID, true); Configuration configuration = underTest.loadBranchConfiguration(db.getSession(), mainBranch); assertThat(configuration.get(MAIN_BRANCH_PROP_KEY)).contains(MAIN_BRANCH_PROP_VALUE); } @Test public void return_configuration_with_global_settings_and_component_settings() { String projectPropKey1 = "prop_key_1"; String projectPropValue1 = "prop_key_value_1"; String projectPropKey2 = "prop_key_2"; String projectPropValue2 = "prop_key_value_2"; globalSettings.setProperty(GLOBAL_PROP_KEY, GLOBAL_PROP_VALUE); db.properties().insertProperty(projectPropKey1, projectPropValue1, MAIN_BRANCH_UUID); db.properties().insertProperty(projectPropKey2, projectPropValue2, MAIN_BRANCH_UUID); BranchDto mainBranch = insertBranch(MAIN_BRANCH_UUID, MAIN_BRANCH_UUID, true); Configuration configuration = underTest.loadBranchConfiguration(db.getSession(), mainBranch); assertThat(configuration.get(GLOBAL_PROP_KEY)).contains(GLOBAL_PROP_VALUE); assertThat(configuration.get(projectPropKey1)).contains(projectPropValue1); assertThat(configuration.get(projectPropKey2)).contains(projectPropValue2); } @Test public void return_configuration_with_global_settings_main_branch_settings_and_branch_settings() { globalSettings.setProperty(GLOBAL_PROP_KEY, GLOBAL_PROP_VALUE); db.properties().insertProperty(MAIN_BRANCH_PROP_KEY, MAIN_BRANCH_PROP_VALUE, MAIN_BRANCH_UUID); db.properties().insertProperty(BRANCH_PROP_KEY, BRANCH_PROP_VALUE, BRANCH_UUID); BranchDto mainBranch = insertBranch(MAIN_BRANCH_UUID, MAIN_BRANCH_UUID, true); BranchDto branch = insertBranch(BRANCH_UUID, MAIN_BRANCH_UUID, false); Configuration configuration = underTest.loadBranchConfiguration(db.getSession(), branch); assertThat(configuration.get(GLOBAL_PROP_KEY)).contains(GLOBAL_PROP_VALUE); assertThat(configuration.get(MAIN_BRANCH_PROP_KEY)).contains(MAIN_BRANCH_PROP_VALUE); assertThat(configuration.get(BRANCH_PROP_KEY)).contains(BRANCH_PROP_VALUE); } public BranchDto insertBranch(String uuid, String projectUuid, boolean isMain){ BranchDto dto = new BranchDto(); dto.setProjectUuid(projectUuid); dto.setUuid(uuid); dto.setIsMain(isMain); dto.setBranchType(BranchType.BRANCH); dto.setKey("key_"+uuid); db.getDbClient().branchDao().insert(db.getSession(), dto); return dto; } }
4,766
41.945946
100
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/view/index/ViewIndexIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.List; import org.junit.Rule; import org.junit.Test; import org.sonar.server.es.EsTester; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.view.index.ViewIndexDefinition.TYPE_VIEW; public class ViewIndexIT { @Rule public EsTester es = EsTester.create(); private ViewIndex index = new ViewIndex(es.client()); @Test public void find_all_view_uuids() { ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjectBranchUuids(singletonList("P1")); ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjectBranchUuids(singletonList("P2")); es.putDocuments(TYPE_VIEW, view1); es.putDocuments(TYPE_VIEW, view2); List<String> result = newArrayList(index.findAllViewUuids()); assertThat(result).containsOnly(view1.uuid(), view2.uuid()); } @Test public void not_find_all_view_uuids() { List<String> result = newArrayList(index.findAllViewUuids()); assertThat(result).isEmpty(); } }
1,976
33.086207
94
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/view/index/ViewIndexerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 com.google.common.collect.Maps; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.server.es.EsTester; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.db.component.ComponentTesting.newProjectCopy; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonar.server.view.index.ViewIndexDefinition.TYPE_VIEW; public class ViewIndexerIT { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Rule public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final ViewIndexer underTest = new ViewIndexer(dbClient, es.client()); @Test public void getIndexTypes() { assertThat(underTest.getIndexTypes()).containsExactly(TYPE_VIEW); } @Test public void index_nothing() { underTest.indexOnStartup(emptySet()); assertThat(es.countDocuments(TYPE_VIEW)).isZero(); } @Test public void index_on_startup() { // simple view ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto view1 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view1, t -> t.setLast(true)); db.components().insertComponent(newProjectCopy(project1, view1)); // view with subview ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto view2 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view2, t -> t.setLast(true)); db.components().insertComponent(newProjectCopy(project2, view2)); ComponentDto subView = db.components().insertComponent(newSubPortfolio(view2)); db.components().insertComponent(newProjectCopy(project3, subView)); // view without project ComponentDto view3 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view3, t -> t.setLast(true)); underTest.indexOnStartup(emptySet()); List<ViewDoc> docs = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(docs).hasSize(4); Map<String, ViewDoc> viewsByUuid = Maps.uniqueIndex(docs, ViewDoc::uuid); assertThat(viewsByUuid.get(view1.uuid()).projectBranchUuids()).containsOnly(project1.uuid()); assertThat(viewsByUuid.get(view2.uuid()).projectBranchUuids()).containsOnly(project2.uuid(), project3.uuid()); assertThat(viewsByUuid.get(subView.uuid()).projectBranchUuids()).containsOnly(project3.uuid()); assertThat(viewsByUuid.get(view3.uuid()).projectBranchUuids()).isEmpty(); } @Test public void index_root_view() { // simple view ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto view1 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view1, t -> t.setLast(true)); db.components().insertComponent(newProjectCopy(project1, view1)); // view with subview ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto view2 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view2, t -> t.setLast(true)); db.components().insertComponent(newProjectCopy(project2, view2)); ComponentDto subView = db.components().insertComponent(newSubPortfolio(view2)); db.components().insertComponent(newProjectCopy(project3, subView)); // view without project ComponentDto view3 = db.components().insertPrivatePortfolio(); db.components().insertSnapshot(view3, t -> t.setLast(true)); underTest.index(view2.uuid()); List<ViewDoc> docs = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(docs).hasSize(2); Map<String, ViewDoc> viewsByUuid = Maps.uniqueIndex(docs, ViewDoc::uuid); assertThat(viewsByUuid.get(view2.uuid()).projectBranchUuids()).containsOnly(project2.uuid(), project3.uuid()); assertThat(viewsByUuid.get(subView.uuid()).projectBranchUuids()).containsOnly(project3.uuid()); } @Test public void index_view_doc() { underTest.index(new ViewDoc().setUuid("EFGH").setProjectBranchUuids(newArrayList("KLMN", "JKLM"))); List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(result).hasSize(1); ViewDoc view = result.get(0); assertThat(view.uuid()).isEqualTo("EFGH"); assertThat(view.projectBranchUuids()).containsOnly("KLMN", "JKLM"); } @Test public void index_application() { ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newProjectCopy("PC1", project, application)); underTest.index(application.uuid()); List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(result).hasSize(1); ViewDoc resultApp = result.get(0); assertThat(resultApp.uuid()).isEqualTo(application.uuid()); assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid()); } @Test public void index_application_on_startup() { ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newProjectCopy("PC1", project, application)); underTest.indexOnStartup(emptySet()); List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(result).hasSize(1); ViewDoc resultApp = result.get(0); assertThat(resultApp.uuid()).isEqualTo(application.uuid()); assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid()); } @Test public void index_application_with_indexAll() { ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newProjectCopy("PC1", project, application)); underTest.indexAll(); List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(result).hasSize(1); ViewDoc resultApp = result.get(0); assertThat(resultApp.uuid()).isEqualTo(application.uuid()); assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid()); } @Test public void index_application_branch() { ComponentDto application = db.components().insertPublicProject(c -> c.setQualifier(APP).setKey("app")).getMainBranchComponent(); ComponentDto applicationBranch1 = db.components().insertProjectBranch(application, a -> a.setKey("app-branch1")); ComponentDto applicationBranch2 = db.components().insertProjectBranch(application, a -> a.setKey("app-branch2")); ComponentDto project1 = db.components().insertPrivateProject(p -> p.setKey("prj1")).getMainBranchComponent(); ComponentDto project1Branch = db.components().insertProjectBranch(project1); ComponentDto project2 = db.components().insertPrivateProject(p -> p.setKey("prj2")).getMainBranchComponent(); ComponentDto project2Branch = db.components().insertProjectBranch(project2); ComponentDto project3 = db.components().insertPrivateProject(p -> p.setKey("prj3")).getMainBranchComponent(); ComponentDto project3Branch = db.components().insertProjectBranch(project3); db.components().insertComponent(newProjectCopy(project1Branch, applicationBranch1)); db.components().insertComponent(newProjectCopy(project2Branch, applicationBranch1)); // Technical project of applicationBranch2 should be ignored db.components().insertComponent(newProjectCopy(project3Branch, applicationBranch2)); underTest.index(applicationBranch1.uuid()); List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class); assertThat(result) .extracting(ViewDoc::uuid, ViewDoc::projectBranchUuids) .containsExactlyInAnyOrder( tuple(applicationBranch1.uuid(), asList(project1Branch.uuid(), project2Branch.uuid()))); } @Test public void delete_should_delete_the_view() { ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjectBranchUuids(Collections.singletonList("P1")); ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjectBranchUuids(asList("P2", "P3", "P4")); ViewDoc view3 = new ViewDoc().setUuid("UUID3").setProjectBranchUuids(asList("P2", "P3", "P4")); es.putDocuments(TYPE_VIEW, view1); es.putDocuments(TYPE_VIEW, view2); es.putDocuments(TYPE_VIEW, view3); assertThat(es.getDocumentFieldValues(TYPE_VIEW, ViewIndexDefinition.FIELD_UUID)) .containsOnly(view1.uuid(), view2.uuid(), view3.uuid()); underTest.delete(dbSession, asList(view1.uuid(), view2.uuid())); assertThat(es.getDocumentFieldValues(TYPE_VIEW, ViewIndexDefinition.FIELD_UUID)) .containsOnly(view3.uuid()); } }
10,655
44.538462
132
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/webhook/AsynchronousWebHooksImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.api.ce.posttask.PostProjectAnalysisTask.LogStatistics; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDbTester; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDbTester; import org.sonar.server.async.AsyncExecution; import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.sonar.db.DbTester.create; import static org.sonar.db.webhook.WebhookTesting.newGlobalWebhook; public class AsynchronousWebHooksImplIT { private final System2 system2 = mock(System2.class); @Rule public DbTester db = create(system2); private final WebhookDbTester webhookDbTester = db.webhooks(); private final ComponentDbTester componentDbTester = db.components(); private static final long NOW = 1_500_000_000_000L; private final TestWebhookCaller caller = new TestWebhookCaller(); private final WebhookDeliveryStorage deliveryStorage = mock(WebhookDeliveryStorage.class); private final WebhookPayload mock = mock(WebhookPayload.class); private final RecordingAsyncExecution asyncExecution = new RecordingAsyncExecution(); private final WebHooksImpl underTest = new WebHooksImpl(caller, deliveryStorage, asyncExecution, db.getDbClient()); @Test public void send_global_webhooks() { ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newGlobalWebhook().setName("First").setUrl("http://url1"), null, null); webhookDbTester.insert(newGlobalWebhook().setName("Second").setUrl("http://url2"), null, null); caller.enqueueSuccess(NOW, 200, 1_234); caller.enqueueFailure(NOW, new IOException("Fail to connect")); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(project.getUuid(), "1", "#1"), () -> mock, mock(LogStatistics.class)); assertThat(caller.countSent()).isZero(); verifyNoInteractions(deliveryStorage); asyncExecution.executeRecorded(); assertThat(caller.countSent()).isEqualTo(2); verify(deliveryStorage, times(2)).persist(any(WebhookDelivery.class)); verify(deliveryStorage).purge(project.getUuid()); } private static class RecordingAsyncExecution implements AsyncExecution { private final List<Runnable> runnableList = new ArrayList<>(); @Override public void addToQueue(Runnable r) { runnableList.add(requireNonNull(r)); } public void executeRecorded() { ArrayList<Runnable> runnables = new ArrayList<>(runnableList); runnableList.clear(); runnables.forEach(Runnable::run); } } }
3,863
38.030303
132
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/webhook/SynchronousWebHooksImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.io.IOException; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDbTester; import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDbTester; import org.sonar.server.async.AsyncExecution; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.slf4j.event.Level.DEBUG; import static org.sonar.db.DbTester.create; import static org.sonar.db.webhook.WebhookTesting.newGlobalWebhook; import static org.sonar.db.webhook.WebhookTesting.newWebhook; public class SynchronousWebHooksImplIT { private static final long NOW = 1_500_000_000_000L; @Rule public LogTester logTester = new LogTester(); @Rule public DbTester db = create(); private final DbClient dbClient = db.getDbClient(); private final WebhookDbTester webhookDbTester = db.webhooks(); private final ComponentDbTester componentDbTester = db.components(); private final TestWebhookCaller caller = new TestWebhookCaller(); private final WebhookDeliveryStorage deliveryStorage = mock(WebhookDeliveryStorage.class); private final WebhookPayload mock = mock(WebhookPayload.class); private final AsyncExecution synchronousAsyncExecution = Runnable::run; private final PostProjectAnalysisTask.LogStatistics taskStatistics = mock(PostProjectAnalysisTask.LogStatistics.class); private final WebHooksImpl underTest = new WebHooksImpl(caller, deliveryStorage, synchronousAsyncExecution, dbClient); @Before public void before() { logTester.setLevel(Level.DEBUG); } @Test public void isEnabled_returns_false_if_no_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); assertThat(underTest.isEnabled(projectDto)).isFalse(); } @Test public void isEnabled_returns_true_if_one_valid_global_webhook() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newWebhook(projectDto).setName("First").setUrl("http://url1"), projectDto.getKey(), projectDto.getName()); assertThat(underTest.isEnabled(projectDto)).isTrue(); } @Test public void isEnabled_returns_true_if_one_valid_project_webhook() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newWebhook(projectDto).setName("First").setUrl("http://url1"), projectDto.getKey(), projectDto.getName()); assertThat(underTest.isEnabled(projectDto)).isTrue(); } @Test public void do_nothing_if_no_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(projectDto.getUuid(), "1", "#1"), () -> mock); assertThat(caller.countSent()).isZero(); assertNoWebhookLogs(); verifyNoInteractions(deliveryStorage); } @Test public void populates_log_statistics_even_if_no_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(projectDto.getUuid(), "1", "#1"), () -> mock, taskStatistics); assertThat(caller.countSent()).isZero(); assertNoWebhookLogs(); verifyNoInteractions(deliveryStorage); verifyLogStatistics(0, 0); } @Test public void send_global_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newGlobalWebhook().setName("First").setUrl("http://url1"), null, null); webhookDbTester.insert(newGlobalWebhook().setName("Second").setUrl("http://url2"), null, null); caller.enqueueSuccess(NOW, 200, 1_234); caller.enqueueFailure(NOW, new IOException("Fail to connect")); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(projectDto.getUuid(), "1", "#1"), () -> mock, taskStatistics); assertThat(caller.countSent()).isEqualTo(2); assertThat(logTester.logs(DEBUG)).contains("Sent webhook 'First' | url=http://url1 | time=1234ms | status=200"); assertThat(logTester.logs(DEBUG)).contains("Failed to send webhook 'Second' | url=http://url2 | message=Fail to connect"); verify(deliveryStorage, times(2)).persist(any(WebhookDelivery.class)); verify(deliveryStorage).purge(projectDto.getUuid()); verifyLogStatistics(2, 0); } private void assertNoWebhookLogs() { assertThat(logTester.logs(DEBUG)) .noneMatch(s -> s.contains("Sent webhook")) .noneMatch(s -> s.contains("Failed to send webhook")); } @Test public void send_project_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newWebhook(projectDto).setName("First").setUrl("http://url1"), projectDto.getKey(), projectDto.getName()); caller.enqueueSuccess(NOW, 200, 1_234); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(projectDto.getUuid(), "1", "#1"), () -> mock, taskStatistics); assertThat(caller.countSent()).isOne(); assertThat(logTester.logs(DEBUG)).contains("Sent webhook 'First' | url=http://url1 | time=1234ms | status=200"); verify(deliveryStorage).persist(any(WebhookDelivery.class)); verify(deliveryStorage).purge(projectDto.getUuid()); verifyLogStatistics(0, 1); } @Test public void send_global_and_project_webhooks() { ProjectDto projectDto = componentDbTester.insertPrivateProject().getProjectDto(); webhookDbTester.insert(newWebhook(projectDto).setName("1First").setUrl("http://url1"), projectDto.getKey(), projectDto.getName()); webhookDbTester.insert(newWebhook(projectDto).setName("2Second").setUrl("http://url2"), projectDto.getKey(), projectDto.getName()); webhookDbTester.insert(newGlobalWebhook().setName("3Third").setUrl("http://url3"), null, null); webhookDbTester.insert(newGlobalWebhook().setName("4Fourth").setUrl("http://url4"), null, null); webhookDbTester.insert(newGlobalWebhook().setName("5Fifth").setUrl("http://url5"), null, null); caller.enqueueSuccess(NOW, 200, 1_234); caller.enqueueFailure(NOW, new IOException("Fail to connect 1")); caller.enqueueFailure(NOW, new IOException("Fail to connect 2")); caller.enqueueSuccess(NOW, 200, 5_678); caller.enqueueSuccess(NOW, 200, 9_256); underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(projectDto.getUuid(), "1", "#1"), () -> mock, taskStatistics); assertThat(caller.countSent()).isEqualTo(5); List<String> debugLogs = logTester.logs(DEBUG); assertThat(debugLogs) .contains("Sent webhook '1First' | url=http://url1 | time=1234ms | status=200") .contains("Failed to send webhook '2Second' | url=http://url2 | message=Fail to connect 1") .contains("Failed to send webhook '3Third' | url=http://url3 | message=Fail to connect 2") .contains("Sent webhook '4Fourth' | url=http://url4 | time=5678ms | status=200") .contains("Sent webhook '5Fifth' | url=http://url5 | time=9256ms | status=200"); verify(deliveryStorage, times(5)).persist(any(WebhookDelivery.class)); verify(deliveryStorage).purge(projectDto.getUuid()); verifyLogStatistics(3, 2); } private void verifyLogStatistics(int global, int project) { verify(taskStatistics).add("globalWebhooks", global); verify(taskStatistics).add("projectWebhooks", project); verifyNoMoreInteractions(taskStatistics); } }
8,773
44.226804
135
java
sonarqube
sonarqube-master/server/sonar-server-common/src/it/java/org/sonar/server/webhook/WebhookDeliveryStorageIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.io.IOException; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.webhook.WebhookDeliveryDto; import org.sonar.db.webhook.WebhookDeliveryTesting; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.webhook.WebhookDeliveryTesting.selectAllDeliveryUuids; public class WebhookDeliveryStorageIT { private static final String DELIVERY_UUID = "abcde1234"; private static final long NOW = 1_500_000_000_000L; private static final long TWO_MONTHS_AGO = NOW - 60L * 24 * 60 * 60 * 1000; private static final long TWO_WEEKS_AGO = NOW - 14L * 24 * 60 * 60 * 1000; private final System2 system = mock(System2.class); @Rule public final DbTester dbTester = DbTester.create(system); private DbClient dbClient = dbTester.getDbClient(); private DbSession dbSession = dbTester.getSession(); private UuidFactory uuidFactory = mock(UuidFactory.class); private WebhookDeliveryStorage underTest = new WebhookDeliveryStorage(dbClient, system, uuidFactory); @Test public void persist_generates_uuid_then_inserts_record() { when(uuidFactory.create()).thenReturn(DELIVERY_UUID); WebhookDelivery delivery = newBuilderTemplate().build(); underTest.persist(delivery); WebhookDeliveryDto dto = dbClient.webhookDeliveryDao().selectByUuid(dbSession, DELIVERY_UUID).get(); assertThat(dto.getUuid()).isEqualTo(DELIVERY_UUID); assertThat(dto.getWebhookUuid()).isEqualTo("WEBHOOK_UUID_1"); assertThat(dto.getProjectUuid()).isEqualTo(delivery.getWebhook().getProjectUuid()); assertThat(dto.getCeTaskUuid()).isEqualTo(delivery.getWebhook().getCeTaskUuid().get()); assertThat(dto.getName()).isEqualTo(delivery.getWebhook().getName()); assertThat(dto.getUrl()).isEqualTo(delivery.getWebhook().getUrl()); assertThat(dto.getCreatedAt()).isEqualTo(delivery.getAt()); assertThat(dto.getHttpStatus()).isEqualTo(delivery.getHttpStatus().get()); assertThat(dto.getDurationMs()).isEqualTo(delivery.getDurationInMs().get()); assertThat(dto.getPayload()).isEqualTo(delivery.getPayload().getJson()); assertThat(dto.getErrorStacktrace()).isNull(); } @Test public void persist_error_stacktrace() { when(uuidFactory.create()).thenReturn(DELIVERY_UUID); WebhookDelivery delivery = newBuilderTemplate() .setError(new IOException("fail to connect")) .build(); underTest.persist(delivery); WebhookDeliveryDto dto = dbClient.webhookDeliveryDao().selectByUuid(dbSession, DELIVERY_UUID).get(); assertThat(dto.getErrorStacktrace()).contains("java.io.IOException", "fail to connect"); } @Test public void purge_deletes_records_older_than_one_month_on_the_project() { when(system.now()).thenReturn(NOW); dbClient.webhookDeliveryDao().insert(dbSession, newDto("D1", "PROJECT_1", TWO_MONTHS_AGO)); dbClient.webhookDeliveryDao().insert(dbSession, newDto("D2", "PROJECT_1", TWO_WEEKS_AGO)); dbClient.webhookDeliveryDao().insert(dbSession, newDto("D3", "PROJECT_2", TWO_MONTHS_AGO)); dbSession.commit(); underTest.purge("PROJECT_1"); // do not purge another project PROJECT_2 assertThat(selectAllDeliveryUuids(dbTester, dbSession)).containsOnly("D2", "D3"); } @Test public void persist_effective_url_if_present() { when(uuidFactory.create()).thenReturn(DELIVERY_UUID); String effectiveUrl = randomAlphabetic(15); WebhookDelivery delivery = newBuilderTemplate() .setEffectiveUrl(effectiveUrl) .build(); underTest.persist(delivery); WebhookDeliveryDto dto = dbClient.webhookDeliveryDao().selectByUuid(dbSession, DELIVERY_UUID).get(); assertThat(dto.getUrl()).isEqualTo(effectiveUrl); } private static WebhookDelivery.Builder newBuilderTemplate() { return new WebhookDelivery.Builder() .setWebhook(new Webhook("WEBHOOK_UUID_1", "COMPONENT1", "TASK1", RandomStringUtils.randomAlphanumeric(40),"Jenkins", "http://jenkins", null)) .setPayload(new WebhookPayload("my-project", "{json}")) .setAt(1_000_000L) .setHttpStatus(200) .setDurationInMs(1_000); } private static WebhookDeliveryDto newDto(String uuid, String componentUuid, long at) { return WebhookDeliveryTesting.newDto() .setUuid(uuid) .setProjectUuid(componentUuid) .setCreatedAt(at); } }
5,574
40.296296
147
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/almsettings/MultipleAlmFeature.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.almsettings; import org.sonar.api.SonarRuntime; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.server.feature.SonarQubeFeature; import static org.sonar.api.SonarEdition.DATACENTER; import static org.sonar.api.SonarEdition.ENTERPRISE; @ServerSide @ComputeEngineSide public class MultipleAlmFeature implements SonarQubeFeature { private final SonarRuntime sonarRuntime; public MultipleAlmFeature(SonarRuntime sonarRuntime) { this.sonarRuntime = sonarRuntime; } @Override public String getName() { return "multiple-alm"; } @Override public boolean isAvailable() { return sonarRuntime.getEdition() == ENTERPRISE || sonarRuntime.getEdition() == DATACENTER; } }
1,616
30.705882
94
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/almsettings/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.almsettings; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecution.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; public interface AsyncExecution { /** * Add the specified {@link Runnable} in queue for asynchronous processing. * * This method returns instantly and {@code r} is executed in another thread. * * @throws NullPointerException if r is {@code null} */ void addToQueue(Runnable r); }
1,178
35.84375
79
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionExecutorService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; public interface AsyncExecutionExecutorService { void addToQueue(Runnable r); }
958
37.36
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionExecutorServiceImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.util.AbstractStoppableExecutorService; import static java.util.concurrent.TimeUnit.MINUTES; public class AsyncExecutionExecutorServiceImpl extends AbstractStoppableExecutorService<ThreadPoolExecutor> implements AsyncExecutionExecutorService, AsyncExecutionMonitoring { private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionExecutorServiceImpl.class); private static final int MAX_THREAD_COUNT = 10; private static final int UNLIMITED_QUEUE = Integer.MAX_VALUE; private static final long KEEP_ALIVE_TIME_IN_MINUTES = 5L; public AsyncExecutionExecutorServiceImpl() { super(createDelegate()); } private static ThreadPoolExecutor createDelegate() { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( MAX_THREAD_COUNT, MAX_THREAD_COUNT, KEEP_ALIVE_TIME_IN_MINUTES, MINUTES, new LinkedBlockingQueue<>(UNLIMITED_QUEUE), new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("SQ_async-%d") .setUncaughtExceptionHandler(((t, e) -> LOG.error("Thread " + t + " failed unexpectedly", e))) .build()); threadPoolExecutor.allowCoreThreadTimeOut(true); return threadPoolExecutor; } @Override public void addToQueue(Runnable r) { this.submit(r); } @Override public int getQueueSize() { return delegate.getQueue().size(); } @Override public int getWorkerCount() { return delegate.getPoolSize(); } @Override public int getLargestWorkerCount() { return delegate.getLargestPoolSize(); } }
2,663
33.153846
102
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Objects.requireNonNull; public class AsyncExecutionImpl implements AsyncExecution { private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionImpl.class); private final AsyncExecutionExecutorService executorService; public AsyncExecutionImpl(AsyncExecutionExecutorService executorService) { this.executorService = executorService; } @Override public void addToQueue(Runnable r) { requireNonNull(r); executorService.addToQueue(() -> { try { r.run(); } catch (Exception e) { LOG.error("Asynchronous task failed", e); } }); } }
1,564
32.297872
86
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionMBean.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; public interface AsyncExecutionMBean { String OBJECT_NAME = "SonarQube:name=AsyncExecution"; long getQueueSize(); long getWorkerCount(); long getLargestWorkerCount(); }
1,057
32.0625
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionMBeanImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; import org.sonar.api.Startable; import org.sonar.process.Jmx; public class AsyncExecutionMBeanImpl implements AsyncExecutionMBean, Startable { private final AsyncExecutionMonitoring asyncExecutionMonitoring; public AsyncExecutionMBeanImpl(AsyncExecutionMonitoring asyncExecutionMonitoring) { this.asyncExecutionMonitoring = asyncExecutionMonitoring; } @Override public void start() { Jmx.register(OBJECT_NAME, this); } @Override public void stop() { Jmx.unregister(OBJECT_NAME); } @Override public long getQueueSize() { return asyncExecutionMonitoring.getQueueSize(); } @Override public long getWorkerCount() { return asyncExecutionMonitoring.getWorkerCount(); } @Override public long getLargestWorkerCount() { return asyncExecutionMonitoring.getLargestWorkerCount(); } }
1,716
28.603448
85
java