diff options
author | Sébastien Lesaint <sebastien.lesaint@sonarsource.com> | 2017-02-15 18:18:27 +0100 |
---|---|---|
committer | Sébastien Lesaint <sebastien.lesaint@sonarsource.com> | 2017-02-17 13:31:49 +0100 |
commit | 9824b94f16109305b4847a611379029695823427 (patch) | |
tree | 85b339103ce4c56df78e3e26f21117da7fb04976 /sonar-db/src/main/java/org/sonar/db | |
parent | 0d3be9943570cf5bfb7fbb72fdfe5a6fcb2798c0 (diff) | |
download | sonarqube-9824b94f16109305b4847a611379029695823427.tar.gz sonarqube-9824b94f16109305b4847a611379029695823427.zip |
split sonar-db into server/sonar-db-core and server/sonar-db-dao
Diffstat (limited to 'sonar-db/src/main/java/org/sonar/db')
257 files changed, 0 insertions, 24001 deletions
diff --git a/sonar-db/src/main/java/org/sonar/db/BatchSession.java b/sonar-db/src/main/java/org/sonar/db/BatchSession.java deleted file mode 100644 index 1e9d37a8176..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/BatchSession.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.util.List; -import java.util.Map; -import org.apache.ibatis.executor.BatchResult; -import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator; -import org.apache.ibatis.executor.keygen.KeyGenerator; -import org.apache.ibatis.mapping.MappedStatement; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.apache.ibatis.session.SqlSession; - -public class BatchSession extends DbSession { - - public static final int MAX_BATCH_SIZE = 250; - - private final int batchSize; - private int count = 0; - - public BatchSession(SqlSession session) { - this(session, MAX_BATCH_SIZE); - } - - BatchSession(SqlSession session, int batchSize) { - super(session); - this.batchSize = batchSize; - } - - @Override - public void select(String statement, Object parameter, ResultHandler handler) { - reset(); - super.select(statement, parameter, handler); - } - - @Override - public void select(String statement, ResultHandler handler) { - reset(); - super.select(statement, handler); - } - - @Override - public <T> T selectOne(String statement) { - reset(); - return super.selectOne(statement); - } - - @Override - public <T> T selectOne(String statement, Object parameter) { - reset(); - return super.selectOne(statement, parameter); - } - - @Override - public <E> List<E> selectList(String statement) { - reset(); - return super.selectList(statement); - } - - @Override - public <E> List<E> selectList(String statement, Object parameter) { - reset(); - return super.selectList(statement, parameter); - } - - @Override - public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { - reset(); - return super.selectList(statement, parameter, rowBounds); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, String mapKey) { - reset(); - return super.selectMap(statement, mapKey); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { - reset(); - return super.selectMap(statement, parameter, mapKey); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { - reset(); - return super.selectMap(statement, parameter, mapKey, rowBounds); - } - - @Override - public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { - reset(); - super.select(statement, parameter, rowBounds, handler); - } - - @Override - public int insert(String statement) { - makeSureGeneratedKeysAreNotUsedInBatchInserts(statement); - increment(); - return super.insert(statement); - } - - @Override - public int insert(String statement, Object parameter) { - makeSureGeneratedKeysAreNotUsedInBatchInserts(statement); - increment(); - return super.insert(statement, parameter); - } - - private void makeSureGeneratedKeysAreNotUsedInBatchInserts(String statement) { - Configuration configuration = super.getConfiguration(); - if (null != configuration) { - MappedStatement mappedStatement = configuration.getMappedStatement(statement); - if (null != mappedStatement) { - KeyGenerator keyGenerator = mappedStatement.getKeyGenerator(); - if (keyGenerator instanceof Jdbc3KeyGenerator) { - throw new IllegalStateException("Batch inserts cannot use generated keys"); - } - } - } - } - - @Override - public int update(String statement) { - increment(); - return super.update(statement); - } - - @Override - public int update(String statement, Object parameter) { - increment(); - return super.update(statement, parameter); - } - - @Override - public int delete(String statement) { - increment(); - return super.delete(statement); - } - - @Override - public int delete(String statement, Object parameter) { - increment(); - return super.delete(statement, parameter); - } - - @Override - public void commit() { - super.commit(); - reset(); - } - - @Override - public void commit(boolean force) { - super.commit(force); - reset(); - } - - @Override - public void rollback() { - super.rollback(); - reset(); - } - - @Override - public void rollback(boolean force) { - super.rollback(force); - reset(); - } - - @Override - public List<BatchResult> flushStatements() { - List<BatchResult> batchResults = super.flushStatements(); - reset(); - return batchResults; - } - - @Override - public <T> T getMapper(Class<T> type) { - return getConfiguration().getMapper(type, this); - } - - private BatchSession increment() { - count += 1; - if (count >= batchSize) { - commit(); - } - return this; - } - - private void reset() { - count = 0; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/Dao.java b/sonar-db/src/main/java/org/sonar/db/Dao.java deleted file mode 100644 index 647d5b09989..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/Dao.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -/** - * All implementations must be declared in {@link DaoModule} - */ -public interface Dao { -} diff --git a/sonar-db/src/main/java/org/sonar/db/DaoModule.java b/sonar-db/src/main/java/org/sonar/db/DaoModule.java deleted file mode 100644 index b088950c1bd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DaoModule.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import org.sonar.core.platform.Module; -import org.sonar.db.ce.CeActivityDao; -import org.sonar.db.ce.CeQueueDao; -import org.sonar.db.ce.CeScannerContextDao; -import org.sonar.db.ce.CeTaskInputDao; -import org.sonar.db.component.ComponentDao; -import org.sonar.db.component.ComponentKeyUpdaterDao; -import org.sonar.db.component.ComponentLinkDao; -import org.sonar.db.component.ResourceDao; -import org.sonar.db.component.SnapshotDao; -import org.sonar.db.duplication.DuplicationDao; -import org.sonar.db.event.EventDao; -import org.sonar.db.issue.IssueChangeDao; -import org.sonar.db.issue.IssueDao; -import org.sonar.db.loadedtemplate.LoadedTemplateDao; -import org.sonar.db.measure.MeasureDao; -import org.sonar.db.measure.custom.CustomMeasureDao; -import org.sonar.db.metric.MetricDao; -import org.sonar.db.notification.NotificationQueueDao; -import org.sonar.db.organization.OrganizationDao; -import org.sonar.db.permission.AuthorizationDao; -import org.sonar.db.permission.GroupPermissionDao; -import org.sonar.db.permission.UserPermissionDao; -import org.sonar.db.permission.template.PermissionTemplateCharacteristicDao; -import org.sonar.db.permission.template.PermissionTemplateDao; -import org.sonar.db.property.InternalPropertiesDao; -import org.sonar.db.property.PropertiesDao; -import org.sonar.db.purge.PurgeDao; -import org.sonar.db.qualitygate.ProjectQgateAssociationDao; -import org.sonar.db.qualitygate.QualityGateConditionDao; -import org.sonar.db.qualitygate.QualityGateDao; -import org.sonar.db.qualityprofile.ActiveRuleDao; -import org.sonar.db.qualityprofile.QProfileChangeDao; -import org.sonar.db.qualityprofile.QualityProfileDao; -import org.sonar.db.rule.RuleDao; -import org.sonar.db.rule.RuleRepositoryDao; -import org.sonar.db.schemamigration.SchemaMigrationDao; -import org.sonar.db.source.FileSourceDao; -import org.sonar.db.user.AuthorDao; -import org.sonar.db.user.GroupDao; -import org.sonar.db.user.GroupMembershipDao; -import org.sonar.db.user.RoleDao; -import org.sonar.db.user.UserDao; -import org.sonar.db.user.UserGroupDao; -import org.sonar.db.user.UserTokenDao; -import org.sonar.db.webhook.WebhookDeliveryDao; - -public class DaoModule extends Module { - private static final List<Class<? extends Dao>> classes = ImmutableList.<Class<? extends Dao>>builder().add( - // ===================================================================== - // for readability and easier merge, keep list ordered alphabetically - // ===================================================================== - ActiveRuleDao.class, - AuthorDao.class, - AuthorizationDao.class, - CeActivityDao.class, - CeQueueDao.class, - CeScannerContextDao.class, - CeTaskInputDao.class, - ComponentDao.class, - ComponentKeyUpdaterDao.class, - ComponentLinkDao.class, - CustomMeasureDao.class, - DuplicationDao.class, - EventDao.class, - FileSourceDao.class, - GroupDao.class, - GroupMembershipDao.class, - GroupPermissionDao.class, - InternalPropertiesDao.class, - IssueChangeDao.class, - IssueDao.class, - LoadedTemplateDao.class, - MeasureDao.class, - MetricDao.class, - NotificationQueueDao.class, - OrganizationDao.class, - PermissionTemplateCharacteristicDao.class, - PermissionTemplateDao.class, - ProjectQgateAssociationDao.class, - PropertiesDao.class, - PurgeDao.class, - QProfileChangeDao.class, - QualityGateConditionDao.class, - QualityGateDao.class, - QualityProfileDao.class, - ResourceDao.class, - RoleDao.class, - RuleDao.class, - RuleRepositoryDao.class, - SnapshotDao.class, - SchemaMigrationDao.class, - UserDao.class, - UserGroupDao.class, - UserPermissionDao.class, - UserTokenDao.class, - WebhookDeliveryDao.class) - .build(); - - @Override - protected void configureModule() { - add(classes.toArray()); - } - - public static List<Class<? extends Dao>> classes() { - return classes; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/Database.java b/sonar-db/src/main/java/org/sonar/db/Database.java deleted file mode 100644 index c5f7862a83f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/Database.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import javax.sql.DataSource; -import org.picocontainer.Startable; -import org.sonar.db.dialect.Dialect; - -/** - * @since 2.12 - */ -public interface Database extends Startable { - /** - * Returns the configured datasource. Null as long as start() is not executed. - */ - DataSource getDataSource(); - - /** - * @return the dialect or null if start() has not been executed - */ - Dialect getDialect(); - - void enableSqlLogging(boolean enable); -} diff --git a/sonar-db/src/main/java/org/sonar/db/DatabaseChecker.java b/sonar-db/src/main/java/org/sonar/db/DatabaseChecker.java deleted file mode 100644 index 110fcae0daa..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DatabaseChecker.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Map; -import org.apache.commons.lang.StringUtils; -import org.picocontainer.Startable; -import org.sonar.api.utils.MessageException; -import org.sonar.api.utils.Version; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.dialect.H2; -import org.sonar.db.dialect.MsSql; -import org.sonar.db.dialect.MySql; -import org.sonar.db.dialect.Oracle; -import org.sonar.db.dialect.PostgreSql; - -/** - * Fail-fast checks of some database requirements - */ -public class DatabaseChecker implements Startable { - - private static final Map<String, Version> MINIMAL_SUPPORTED_DB_VERSIONS = ImmutableMap.of( - // MsSQL 2012 is 11.x - // MsSQL 2014 is 12.x - // https://support.microsoft.com/en-us/kb/321185 - MsSql.ID, Version.create(11, 0, 0), - MySql.ID, Version.create(5, 6, 0), - Oracle.ID, Version.create(11, 0, 0), - PostgreSql.ID, Version.create(8, 0, 0)); - - private final Database db; - - public DatabaseChecker(Database db) { - this.db = db; - } - - @Override - public void start() { - try { - checkMinDatabaseVersion(); - - // additional checks - if (H2.ID.equals(db.getDialect().getId())) { - Loggers.get(DatabaseChecker.class).warn("H2 database should be used for evaluation purpose only"); - } else if (Oracle.ID.equals(db.getDialect().getId())) { - checkOracleDriverVersion(); - } - } catch (SQLException e) { - Throwables.propagate(e); - } - } - - @Override - public void stop() { - // nothing to do - } - - private void checkMinDatabaseVersion() throws SQLException { - Version minDbVersion = MINIMAL_SUPPORTED_DB_VERSIONS.get(db.getDialect().getId()); - if (minDbVersion != null) { - try (Connection connection = db.getDataSource().getConnection()) { - int dbMajorVersion = connection.getMetaData().getDatabaseMajorVersion(); - int dbMinorVersion = connection.getMetaData().getDatabaseMinorVersion(); - Version dbVersion = Version.create(dbMajorVersion, dbMinorVersion, 0); - if (dbVersion.compareTo(minDbVersion) < 0) { - throw MessageException.of(String.format( - "Unsupported %s version: %s. Minimal supported version is %s.", db.getDialect().getId(), dbVersion, minDbVersion)); - } - } - } - } - - private void checkOracleDriverVersion() throws SQLException { - try (Connection connection = db.getDataSource().getConnection()) { - String driverVersion = connection.getMetaData().getDriverVersion(); - String[] parts = StringUtils.split(driverVersion, "."); - int intVersion = Integer.parseInt(parts[0]) * 100 + Integer.parseInt(parts[1]); - if (intVersion < 1102) { - throw MessageException.of(String.format( - "Unsupported Oracle driver version: %s. Minimal supported version is 11.2.", driverVersion)); - } - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/DatabaseUtils.java b/sonar-db/src/main/java/org/sonar/db/DatabaseUtils.java deleted file mode 100644 index 31f5abebb9f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DatabaseUtils.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; -import com.google.common.collect.Sets; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -import static com.google.common.collect.Lists.newArrayList; -import static java.lang.String.format; - -public class DatabaseUtils { - - public static final int PARTITION_SIZE_FOR_ORACLE = 1000; - - /** - * @see DatabaseMetaData#getTableTypes() - */ - private static final String[] TABLE_TYPE = {"TABLE"}; - - public static void closeQuietly(@Nullable Connection connection) { - if (connection != null) { - try { - connection.close(); - } catch (SQLException e) { - Loggers.get(DatabaseUtils.class).warn("Fail to close connection", e); - // ignore - } - } - } - - public static void closeQuietly(@Nullable Statement stmt) { - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - Loggers.get(DatabaseUtils.class).warn("Fail to close statement", e); - // ignore - } - } - } - - public static void closeQuietly(@Nullable ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - Loggers.get(DatabaseUtils.class).warn("Fail to close result set", e); - // ignore - } - } - } - - /** - * Returns an escaped value in parameter, with the desired wildcards. Suitable to be used in a like sql query<br /> - * Escapes the "/", "%" and "_" characters.<br/> - * - * You <strong>must</strong> add "ESCAPE '/'" after your like query. It defines '/' as the escape character. - */ - public static String buildLikeValue(String value, WildcardPosition wildcardPosition) { - String escapedValue = escapePercentAndUnderscore(value); - String wildcard = "%"; - switch (wildcardPosition) { - case BEFORE: - escapedValue = wildcard + escapedValue; - break; - case AFTER: - escapedValue += wildcard; - break; - case BEFORE_AND_AFTER: - escapedValue = wildcard + escapedValue + wildcard; - break; - default: - throw new UnsupportedOperationException("Unhandled WildcardPosition: " + wildcardPosition); - } - - return escapedValue; - } - - /** - * Replace escape percent and underscore by adding a slash just before - */ - private static String escapePercentAndUnderscore(String value) { - return value - .replaceAll("/", "//") - .replaceAll("%", "/%") - .replaceAll("_", "/_"); - } - - /** - * Partition by 1000 elements a list of input and execute a function on each part. - * - * The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)' - * and with MsSQL when there's more than 2000 parameters in a query - */ - public static <OUTPUT, INPUT extends Comparable<INPUT>> List<OUTPUT> executeLargeInputs(Collection<INPUT> input, Function<List<INPUT>, List<OUTPUT>> function) { - return executeLargeInputs(input, function, size -> size == 0 ? Collections.emptyList() : new ArrayList<>(size)); - } - - public static <OUTPUT, INPUT extends Comparable<INPUT>> Set<OUTPUT> executeLargeInputsIntoSet(Collection<INPUT> input, Function<List<INPUT>, Set<OUTPUT>> function) { - return executeLargeInputs(input, function, size -> size == 0 ? Collections.emptySet() : new HashSet<>(size)); - } - - private static <OUTPUT, INPUT extends Comparable<INPUT>, RESULT extends Collection<OUTPUT>> RESULT executeLargeInputs(Collection<INPUT> input, - Function<List<INPUT>, RESULT> function, java.util.function.Function<Integer, RESULT> outputInitializer) { - if (input.isEmpty()) { - return outputInitializer.apply(0); - } - RESULT results = outputInitializer.apply(input.size()); - for (List<INPUT> partition : toUniqueAndSortedPartitions(input)) { - RESULT subResults = function.apply(partition); - if (subResults != null) { - results.addAll(subResults); - } - } - return results; - } - - /** - * Partition by 1000 elements a list of input and execute a consumer on each part. - * - * The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)' - * and with MsSQL when there's more than 2000 parameters in a query - */ - public static <INPUT extends Comparable<INPUT>> void executeLargeUpdates(Collection<INPUT> inputs, Consumer<List<INPUT>> consumer) { - Iterable<List<INPUT>> partitions = toUniqueAndSortedPartitions(inputs); - for (List<INPUT> partition : partitions) { - consumer.accept(partition); - } - } - - /** - * Partition by 1000 elements a list of input and execute a consumer on each part. - * - * The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)' - * and with MsSQL when there's more than 2000 parameters in a query - * - * @param sqlCaller a {@link Function} which calls the SQL update/delete and returns the number of updated/deleted rows. - * - * @return the total number of updated/deleted rows (computed as the sum of the values returned by {@code sqlCaller}). - */ - public static <INPUT extends Comparable<INPUT>> int executeLargeUpdates(Collection<INPUT> inputs, Function<List<INPUT>, Integer> sqlCaller) { - Iterable<List<INPUT>> partitions = toUniqueAndSortedPartitions(inputs); - Integer res = 0; - for (List<INPUT> partition : partitions) { - res += sqlCaller.apply(partition); - } - return res; - } - - /** - * Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted before creating the partition. - */ - private static <INPUT extends Comparable<INPUT>> Iterable<List<INPUT>> toUniqueAndSortedPartitions(Collection<INPUT> inputs) { - return Iterables.partition(toUniqueAndSortedList(inputs), PARTITION_SIZE_FOR_ORACLE); - } - - /** - * Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted so that there is little - * variations of SQL requests over time as possible with a IN clause and/or a group of OR clauses. Such requests can - * then be more easily optimized by the SGDB engine. - */ - public static <INPUT extends Comparable<INPUT>> List<INPUT> toUniqueAndSortedList(Iterable<INPUT> inputs) { - if (inputs instanceof Set) { - // inputs are unique but order is not enforced - return Ordering.natural().immutableSortedCopy(inputs); - } - // inputs are not unique and order is not guaranteed - return Ordering.natural().immutableSortedCopy(Sets.newHashSet(inputs)); - } - - /** - * Partition by 1000 elements a list of input and execute a function on each part. - * The function has not output (ex: delete operation) - * - * The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)' - * and with MsSQL when there's more than 2000 parameters in a query - */ - public static <INPUT> void executeLargeInputsWithoutOutput(Collection<INPUT> input, Function<List<INPUT>, Void> function) { - if (input.isEmpty()) { - return; - } - - List<List<INPUT>> partitions = Lists.partition(newArrayList(input), PARTITION_SIZE_FOR_ORACLE); - for (List<INPUT> partition : partitions) { - function.apply(partition); - } - } - - public static String repeatCondition(String sql, int count, String separator) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < count; i++) { - sb.append(sql); - if (i < count - 1) { - sb.append(" ").append(separator).append(" "); - } - } - return sb.toString(); - } - - /** - * Logback does not log exceptions associated to {@link java.sql.SQLException#getNextException()}. - * See http://jira.qos.ch/browse/LOGBACK-775 - */ - public static void log(Logger logger, SQLException e) { - SQLException next = e.getNextException(); - while (next != null) { - logger.error("SQL error: {}. Message: {}", next.getSQLState(), next.getMessage()); - next = next.getNextException(); - } - } - - @CheckForNull - public static Long getLong(ResultSet rs, String columnName) throws SQLException { - long l = rs.getLong(columnName); - return rs.wasNull() ? null : l; - } - - @CheckForNull - public static Double getDouble(ResultSet rs, String columnName) throws SQLException { - double d = rs.getDouble(columnName); - return rs.wasNull() ? null : d; - } - - @CheckForNull - public static Integer getInt(ResultSet rs, String columnName) throws SQLException { - int i = rs.getInt(columnName); - return rs.wasNull() ? null : i; - } - - @CheckForNull - public static String getString(ResultSet rs, String columnName) throws SQLException { - String s = rs.getString(columnName); - return rs.wasNull() ? null : s; - } - - @CheckForNull - public static Long getLong(ResultSet rs, int columnIndex) throws SQLException { - long l = rs.getLong(columnIndex); - return rs.wasNull() ? null : l; - } - - @CheckForNull - public static Double getDouble(ResultSet rs, int columnIndex) throws SQLException { - double d = rs.getDouble(columnIndex); - return rs.wasNull() ? null : d; - } - - @CheckForNull - public static Integer getInt(ResultSet rs, int columnIndex) throws SQLException { - int i = rs.getInt(columnIndex); - return rs.wasNull() ? null : i; - } - - @CheckForNull - public static String getString(ResultSet rs, int columnIndex) throws SQLException { - String s = rs.getString(columnIndex); - return rs.wasNull() ? null : s; - } - - @CheckForNull - public static Date getDate(ResultSet rs, int columnIndex) throws SQLException { - Timestamp t = rs.getTimestamp(columnIndex); - return rs.wasNull() ? null : new Date(t.getTime()); - } - - /** - * @param table case-insensitive name of table - * @return true if a table exists with this name, otherwise false - * @throws SQLException - */ - public static boolean tableExists(String table, Connection connection) { - // table type is used to speed-up Oracle by removing introspection of system tables and aliases. - try (ResultSet rs = connection.getMetaData().getTables(null, null, null, TABLE_TYPE)) { - while (rs.next()) { - String name = rs.getString("TABLE_NAME"); - if (table.equalsIgnoreCase(name)) { - return true; - } - } - return false; - } catch (SQLException e) { - throw wrapSqlException(e, "Can not check that table %s exists", table); - } - } - - public static IllegalStateException wrapSqlException(SQLException e, String message, Object... messageArgs) { - return new IllegalStateException(format(message, messageArgs), e); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/DbClient.java b/sonar-db/src/main/java/org/sonar/db/DbClient.java deleted file mode 100644 index 24dc5dfea8b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DbClient.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.util.IdentityHashMap; -import java.util.Map; -import javax.annotation.Nullable; -import org.sonar.db.ce.CeActivityDao; -import org.sonar.db.ce.CeQueueDao; -import org.sonar.db.ce.CeScannerContextDao; -import org.sonar.db.ce.CeTaskInputDao; -import org.sonar.db.component.ComponentDao; -import org.sonar.db.component.ComponentKeyUpdaterDao; -import org.sonar.db.component.ComponentLinkDao; -import org.sonar.db.component.ResourceDao; -import org.sonar.db.component.SnapshotDao; -import org.sonar.db.duplication.DuplicationDao; -import org.sonar.db.event.EventDao; -import org.sonar.db.issue.IssueChangeDao; -import org.sonar.db.issue.IssueDao; -import org.sonar.db.loadedtemplate.LoadedTemplateDao; -import org.sonar.db.measure.MeasureDao; -import org.sonar.db.measure.custom.CustomMeasureDao; -import org.sonar.db.metric.MetricDao; -import org.sonar.db.notification.NotificationQueueDao; -import org.sonar.db.organization.OrganizationDao; -import org.sonar.db.permission.AuthorizationDao; -import org.sonar.db.permission.GroupPermissionDao; -import org.sonar.db.permission.UserPermissionDao; -import org.sonar.db.permission.template.PermissionTemplateCharacteristicDao; -import org.sonar.db.permission.template.PermissionTemplateDao; -import org.sonar.db.property.InternalPropertiesDao; -import org.sonar.db.property.PropertiesDao; -import org.sonar.db.purge.PurgeDao; -import org.sonar.db.qualitygate.ProjectQgateAssociationDao; -import org.sonar.db.qualitygate.QualityGateConditionDao; -import org.sonar.db.qualitygate.QualityGateDao; -import org.sonar.db.qualityprofile.ActiveRuleDao; -import org.sonar.db.qualityprofile.QProfileChangeDao; -import org.sonar.db.qualityprofile.QualityProfileDao; -import org.sonar.db.rule.RuleDao; -import org.sonar.db.rule.RuleRepositoryDao; -import org.sonar.db.schemamigration.SchemaMigrationDao; -import org.sonar.db.source.FileSourceDao; -import org.sonar.db.user.AuthorDao; -import org.sonar.db.user.GroupDao; -import org.sonar.db.user.GroupMembershipDao; -import org.sonar.db.user.RoleDao; -import org.sonar.db.user.UserDao; -import org.sonar.db.user.UserGroupDao; -import org.sonar.db.user.UserTokenDao; -import org.sonar.db.webhook.WebhookDeliveryDao; - -public class DbClient { - - private final Database database; - private final MyBatis myBatis; - private final SchemaMigrationDao schemaMigrationDao; - private final AuthorizationDao authorizationDao; - private final OrganizationDao organizationDao; - private final QualityProfileDao qualityProfileDao; - private final LoadedTemplateDao loadedTemplateDao; - private final PropertiesDao propertiesDao; - private final InternalPropertiesDao internalPropertiesDao; - private final SnapshotDao snapshotDao; - private final ComponentDao componentDao; - private final ResourceDao resourceDao; - private final ComponentKeyUpdaterDao componentKeyUpdaterDao; - private final MeasureDao measureDao; - private final UserDao userDao; - private final UserGroupDao userGroupDao; - private final UserTokenDao userTokenDao; - private final GroupMembershipDao groupMembershipDao; - private final RoleDao roleDao; - private final GroupPermissionDao groupPermissionDao; - private final PermissionTemplateDao permissionTemplateDao; - private final PermissionTemplateCharacteristicDao permissionTemplateCharacteristicDao; - private final IssueDao issueDao; - private final IssueChangeDao issueChangeDao; - private final CeActivityDao ceActivityDao; - private final CeQueueDao ceQueueDao; - private final CeTaskInputDao ceTaskInputDao; - private final CeScannerContextDao ceScannerContextDao; - private final FileSourceDao fileSourceDao; - private final AuthorDao authorDao; - private final ComponentLinkDao componentLinkDao; - private final EventDao eventDao; - private final PurgeDao purgeDao; - private final QualityGateDao qualityGateDao; - private final QualityGateConditionDao gateConditionDao; - private final ProjectQgateAssociationDao projectQgateAssociationDao; - private final DuplicationDao duplicationDao; - private final NotificationQueueDao notificationQueueDao; - private final CustomMeasureDao customMeasureDao; - private final MetricDao metricDao; - private final GroupDao groupDao; - private final RuleDao ruleDao; - private final RuleRepositoryDao ruleRepositoryDao; - private final ActiveRuleDao activeRuleDao; - private final QProfileChangeDao qProfileChangeDao; - private final UserPermissionDao userPermissionDao; - private final WebhookDeliveryDao webhookDeliveryDao; - - public DbClient(Database database, MyBatis myBatis, Dao... daos) { - this.database = database; - this.myBatis = myBatis; - - Map<Class, Dao> map = new IdentityHashMap<>(); - for (Dao dao : daos) { - map.put(dao.getClass(), dao); - } - schemaMigrationDao = getDao(map, SchemaMigrationDao.class); - authorizationDao = getDao(map, AuthorizationDao.class); - organizationDao = getDao(map, OrganizationDao.class); - qualityProfileDao = getDao(map, QualityProfileDao.class); - loadedTemplateDao = getDao(map, LoadedTemplateDao.class); - propertiesDao = getDao(map, PropertiesDao.class); - internalPropertiesDao = getDao(map, InternalPropertiesDao.class); - snapshotDao = getDao(map, SnapshotDao.class); - componentDao = getDao(map, ComponentDao.class); - resourceDao = getDao(map, ResourceDao.class); - componentKeyUpdaterDao = getDao(map, ComponentKeyUpdaterDao.class); - measureDao = getDao(map, MeasureDao.class); - userDao = getDao(map, UserDao.class); - userGroupDao = getDao(map, UserGroupDao.class); - userTokenDao = getDao(map, UserTokenDao.class); - groupMembershipDao = getDao(map, GroupMembershipDao.class); - roleDao = getDao(map, RoleDao.class); - groupPermissionDao = getDao(map, GroupPermissionDao.class); - permissionTemplateDao = getDao(map, PermissionTemplateDao.class); - permissionTemplateCharacteristicDao = getDao(map, PermissionTemplateCharacteristicDao.class); - issueDao = getDao(map, IssueDao.class); - issueChangeDao = getDao(map, IssueChangeDao.class); - ceActivityDao = getDao(map, CeActivityDao.class); - ceQueueDao = getDao(map, CeQueueDao.class); - ceTaskInputDao = getDao(map, CeTaskInputDao.class); - ceScannerContextDao = getDao(map, CeScannerContextDao.class); - fileSourceDao = getDao(map, FileSourceDao.class); - authorDao = getDao(map, AuthorDao.class); - componentLinkDao = getDao(map, ComponentLinkDao.class); - eventDao = getDao(map, EventDao.class); - purgeDao = getDao(map, PurgeDao.class); - qualityGateDao = getDao(map, QualityGateDao.class); - gateConditionDao = getDao(map, QualityGateConditionDao.class); - projectQgateAssociationDao = getDao(map, ProjectQgateAssociationDao.class); - duplicationDao = getDao(map, DuplicationDao.class); - notificationQueueDao = getDao(map, NotificationQueueDao.class); - customMeasureDao = getDao(map, CustomMeasureDao.class); - metricDao = getDao(map, MetricDao.class); - groupDao = getDao(map, GroupDao.class); - ruleDao = getDao(map, RuleDao.class); - ruleRepositoryDao = getDao(map, RuleRepositoryDao.class); - activeRuleDao = getDao(map, ActiveRuleDao.class); - qProfileChangeDao = getDao(map, QProfileChangeDao.class); - userPermissionDao = getDao(map, UserPermissionDao.class); - webhookDeliveryDao = getDao(map, WebhookDeliveryDao.class); - } - - public DbSession openSession(boolean batch) { - return myBatis.openSession(batch); - } - - public void closeSession(@Nullable DbSession session) { - MyBatis.closeQuietly(session); - } - - public Database getDatabase() { - return database; - } - - public SchemaMigrationDao schemaMigrationDao() { - return schemaMigrationDao; - } - - public AuthorizationDao authorizationDao() { - return authorizationDao; - } - - public OrganizationDao organizationDao() { - return organizationDao; - } - - public IssueDao issueDao() { - return issueDao; - } - - public IssueChangeDao issueChangeDao() { - return issueChangeDao; - } - - public QualityProfileDao qualityProfileDao() { - return qualityProfileDao; - } - - public LoadedTemplateDao loadedTemplateDao() { - return loadedTemplateDao; - } - - public PropertiesDao propertiesDao() { - return propertiesDao; - } - - public InternalPropertiesDao internalPropertiesDao() { - return internalPropertiesDao; - } - - public SnapshotDao snapshotDao() { - return snapshotDao; - } - - public ComponentDao componentDao() { - return componentDao; - } - - public ResourceDao resourceDao() { - return resourceDao; - } - - public ComponentKeyUpdaterDao componentKeyUpdaterDao() { - return componentKeyUpdaterDao; - } - - public MeasureDao measureDao() { - return measureDao; - } - - public UserDao userDao() { - return userDao; - } - - public UserGroupDao userGroupDao() { - return userGroupDao; - } - - public UserTokenDao userTokenDao() { - return userTokenDao; - } - - public GroupMembershipDao groupMembershipDao() { - return groupMembershipDao; - } - - public RoleDao roleDao() { - return roleDao; - } - - public GroupPermissionDao groupPermissionDao() { - return groupPermissionDao; - } - - public PermissionTemplateDao permissionTemplateDao() { - return permissionTemplateDao; - } - - public PermissionTemplateCharacteristicDao permissionTemplateCharacteristicDao() { - return permissionTemplateCharacteristicDao; - } - - public CeActivityDao ceActivityDao() { - return ceActivityDao; - } - - public CeQueueDao ceQueueDao() { - return ceQueueDao; - } - - public CeTaskInputDao ceTaskInputDao() { - return ceTaskInputDao; - } - - public CeScannerContextDao ceScannerContextDao() { - return ceScannerContextDao; - } - - public FileSourceDao fileSourceDao() { - return fileSourceDao; - } - - public AuthorDao authorDao() { - return authorDao; - } - - public ComponentLinkDao componentLinkDao() { - return componentLinkDao; - } - - public EventDao eventDao() { - return eventDao; - } - - public PurgeDao purgeDao() { - return purgeDao; - } - - public QualityGateDao qualityGateDao() { - return qualityGateDao; - } - - public QualityGateConditionDao gateConditionDao() { - return gateConditionDao; - } - - public ProjectQgateAssociationDao projectQgateAssociationDao() { - return projectQgateAssociationDao; - } - - public DuplicationDao duplicationDao() { - return duplicationDao; - } - - public NotificationQueueDao notificationQueueDao() { - return notificationQueueDao; - } - - public CustomMeasureDao customMeasureDao() { - return customMeasureDao; - } - - public MetricDao metricDao() { - return metricDao; - } - - public GroupDao groupDao() { - return groupDao; - } - - public RuleDao ruleDao() { - return ruleDao; - } - - public RuleRepositoryDao ruleRepositoryDao() { - return ruleRepositoryDao; - } - - public ActiveRuleDao activeRuleDao() { - return activeRuleDao; - } - - public QProfileChangeDao qProfileChangeDao() { - return qProfileChangeDao; - } - - public UserPermissionDao userPermissionDao() { - return userPermissionDao; - } - - public WebhookDeliveryDao webhookDeliveryDao() { - return webhookDeliveryDao; - } - - protected <K extends Dao> K getDao(Map<Class, Dao> map, Class<K> clazz) { - return (K) map.get(clazz); - } - - // should be removed. Still used by some old DAO in sonar-server - public MyBatis getMyBatis() { - return myBatis; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/DbSession.java b/sonar-db/src/main/java/org/sonar/db/DbSession.java deleted file mode 100644 index a53493d3801..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DbSession.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.sql.Connection; -import java.util.List; -import java.util.Map; -import org.apache.ibatis.executor.BatchResult; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.apache.ibatis.session.SqlSession; - -public class DbSession implements SqlSession { - - private SqlSession session; - - public DbSession(SqlSession session) { - this.session = session; - } - - @Override - public void commit() { - session.commit(); - } - - @Override - public void commit(boolean force) { - session.commit(force); - } - - /** - * We only care about the the commit section. - * The rest is simply passed to its parent. - */ - - @Override - public <T> T selectOne(String statement) { - return session.selectOne(statement); - } - - @Override - public <T> T selectOne(String statement, Object parameter) { - return session.selectOne(statement, parameter); - } - - @Override - public <E> List<E> selectList(String statement) { - return session.selectList(statement); - } - - @Override - public <E> List<E> selectList(String statement, Object parameter) { - return session.selectList(statement, parameter); - } - - @Override - public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { - return session.selectList(statement, parameter, rowBounds); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, String mapKey) { - return session.selectMap(statement, mapKey); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { - return session.selectMap(statement, parameter, mapKey); - } - - @Override - public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { - return session.selectMap(statement, parameter, mapKey, rowBounds); - } - - @Override - public void select(String statement, Object parameter, ResultHandler handler) { - session.select(statement, parameter, handler); - } - - @Override - public void select(String statement, ResultHandler handler) { - session.select(statement, handler); - } - - @Override - public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { - session.select(statement, parameter, rowBounds, handler); - } - - @Override - public int insert(String statement) { - return session.insert(statement); - } - - @Override - public int insert(String statement, Object parameter) { - return session.insert(statement, parameter); - } - - @Override - public int update(String statement) { - return session.update(statement); - } - - @Override - public int update(String statement, Object parameter) { - return session.update(statement, parameter); - } - - @Override - public int delete(String statement) { - return session.delete(statement); - } - - @Override - public int delete(String statement, Object parameter) { - return session.delete(statement, parameter); - } - - @Override - public void rollback() { - session.rollback(); - } - - @Override - public void rollback(boolean force) { - session.rollback(force); - } - - @Override - public List<BatchResult> flushStatements() { - return session.flushStatements(); - } - - @Override - public void close() { - session.close(); - } - - @Override - public void clearCache() { - session.clearCache(); - } - - @Override - public Configuration getConfiguration() { - return session.getConfiguration(); - } - - @Override - public <T> T getMapper(Class<T> type) { - return session.getMapper(type); - } - - @Override - public Connection getConnection() { - return session.getConnection(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/DdlUtils.java b/sonar-db/src/main/java/org/sonar/db/DdlUtils.java deleted file mode 100644 index 32675984093..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DdlUtils.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.PrintWriter; -import java.sql.Connection; -import org.apache.commons.io.output.NullWriter; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.jdbc.ScriptRunner; - -/** - * Util class to create Sonar database tables - * - * @since 2.12 - */ -public final class DdlUtils { - - private DdlUtils() { - } - - public static boolean supportsDialect(String dialect) { - return "h2".equals(dialect); - } - - /** - * The connection is commited in this method but not closed. - */ - public static void createSchema(Connection connection, String dialect, boolean createSchemaMigrations) { - if (createSchemaMigrations) { - executeScript(connection, "org/sonar/db/version/schema_migrations-" + dialect + ".ddl"); - } - executeScript(connection, "org/sonar/db/version/schema-" + dialect + ".ddl"); - executeScript(connection, "org/sonar/db/version/rows-" + dialect + ".sql"); - } - - public static void executeScript(Connection connection, String path) { - ScriptRunner scriptRunner = newScriptRunner(connection); - try { - scriptRunner.runScript(Resources.getResourceAsReader(path)); - connection.commit(); - - } catch (Exception e) { - throw new IllegalStateException("Fail to restore: " + path, e); - } - } - - private static ScriptRunner newScriptRunner(Connection connection) { - ScriptRunner scriptRunner = new ScriptRunner(connection); - scriptRunner.setDelimiter(";"); - scriptRunner.setStopOnError(true); - scriptRunner.setLogWriter(new PrintWriter(new NullWriter())); - return scriptRunner; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/DefaultDatabase.java b/sonar-db/src/main/java/org/sonar/db/DefaultDatabase.java deleted file mode 100644 index c1a3c28dfff..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/DefaultDatabase.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import ch.qos.logback.classic.Level; -import com.google.common.annotations.VisibleForTesting; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import javax.sql.DataSource; -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.dbcp.BasicDataSourceFactory; -import org.apache.commons.dbutils.DbUtils; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.config.Settings; -import org.sonar.api.database.DatabaseProperties; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.dialect.Dialect; -import org.sonar.db.dialect.DialectUtils; -import org.sonar.db.profiling.NullConnectionInterceptor; -import org.sonar.db.profiling.ProfiledConnectionInterceptor; -import org.sonar.db.profiling.ProfiledDataSource; -import org.sonar.process.logging.LogbackHelper; - -import static java.lang.String.format; - -/** - * @since 2.12 - */ -public class DefaultDatabase implements Database { - - private static final Logger LOG = Loggers.get(Database.class); - - private static final String DEFAULT_URL = "jdbc:h2:tcp://localhost/sonar"; - private static final String SONAR_JDBC = "sonar.jdbc."; - private static final String SONAR_JDBC_DIALECT = "sonar.jdbc.dialect"; - private static final String SONAR_JDBC_URL = "sonar.jdbc.url"; - - private final LogbackHelper logbackHelper; - private final Settings settings; - private ProfiledDataSource datasource; - private Dialect dialect; - private Properties properties; - - public DefaultDatabase(LogbackHelper logbackHelper, Settings settings) { - this.logbackHelper = logbackHelper; - this.settings = settings; - } - - @Override - public void start() { - try { - initSettings(); - initDataSource(); - checkConnection(); - - } catch (Exception e) { - throw new IllegalStateException("Fail to connect to database", e); - } - } - - @VisibleForTesting - void initSettings() { - properties = new Properties(); - completeProperties(settings, properties, SONAR_JDBC); - completeDefaultProperty(properties, DatabaseProperties.PROP_URL, DEFAULT_URL); - doCompleteProperties(properties); - - dialect = DialectUtils.find(properties.getProperty(SONAR_JDBC_DIALECT), properties.getProperty(SONAR_JDBC_URL)); - properties.setProperty(DatabaseProperties.PROP_DRIVER, dialect.getDefaultDriverClassName()); - } - - private void initDataSource() throws Exception { - // but it's correctly caught by start() - LOG.info("Create JDBC data source for {}", properties.getProperty(DatabaseProperties.PROP_URL, DEFAULT_URL)); - BasicDataSource basicDataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(extractCommonsDbcpProperties(properties)); - datasource = new ProfiledDataSource(basicDataSource, NullConnectionInterceptor.INSTANCE); - datasource.setConnectionInitSqls(dialect.getConnectionInitStatements()); - datasource.setValidationQuery(dialect.getValidationQuery()); - enableSqlLogging(datasource, logbackHelper.getLoggerLevel("sql") == Level.TRACE); - } - - private void checkConnection() { - Connection connection = null; - try { - connection = datasource.getConnection(); - } catch (SQLException e) { - throw new IllegalStateException("Can not connect to database. Please check connectivity and settings (see the properties prefixed by 'sonar.jdbc.').", e); - } finally { - DbUtils.closeQuietly(connection); - } - } - - @Override - public void stop() { - if (datasource != null) { - try { - datasource.close(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to stop JDBC connection pool", e); - } - } - } - - @Override - public final Dialect getDialect() { - return dialect; - } - - @Override - public final DataSource getDataSource() { - return datasource; - } - - public final Properties getProperties() { - return properties; - } - - @Override - public void enableSqlLogging(boolean enable) { - enableSqlLogging(datasource, enable); - } - - private static void enableSqlLogging(ProfiledDataSource ds, boolean enable) { - ds.setConnectionInterceptor(enable ? ProfiledConnectionInterceptor.INSTANCE : NullConnectionInterceptor.INSTANCE); - } - - /** - * Override this method to add JDBC properties at runtime - */ - protected void doCompleteProperties(Properties properties) { - // open-close principle - } - - private static void completeProperties(Settings settings, Properties properties, String prefix) { - List<String> jdbcKeys = settings.getKeysStartingWith(prefix); - for (String jdbcKey : jdbcKeys) { - String value = settings.getString(jdbcKey); - properties.setProperty(jdbcKey, value); - } - } - - @VisibleForTesting - static Properties extractCommonsDbcpProperties(Properties properties) { - Properties result = new Properties(); - for (Map.Entry<Object, Object> entry : properties.entrySet()) { - String key = (String) entry.getKey(); - if (StringUtils.startsWith(key, SONAR_JDBC)) { - result.setProperty(StringUtils.removeStart(key, SONAR_JDBC), (String) entry.getValue()); - } - } - return result; - } - - private static void completeDefaultProperty(Properties props, String key, String defaultValue) { - if (props.getProperty(key) == null) { - props.setProperty(key, defaultValue); - } - } - - @Override - public String toString() { - return format("Database[%s]", properties != null ? properties.getProperty(SONAR_JDBC_URL) : "?"); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/Dto.java b/sonar-db/src/main/java/org/sonar/db/Dto.java deleted file mode 100644 index 8a6d2ff11a8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/Dto.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.Serializable; -import java.util.Date; - -public abstract class Dto<K extends Serializable> { - - private Date createdAt; - private Date updatedAt; - - public abstract K getKey(); - - public Dto setCreatedAt(Date datetime) { - this.createdAt = datetime; - return this; - } - - public Dto setUpdatedAt(Date datetime) { - this.updatedAt = datetime; - return this; - } - - public final Date getCreatedAt() { - return this.createdAt; - } - - public final Date getUpdatedAt() { - return this.updatedAt; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/IsAliveMapper.java b/sonar-db/src/main/java/org/sonar/db/IsAliveMapper.java deleted file mode 100644 index 90ac50ea2fe..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/IsAliveMapper.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -public interface IsAliveMapper { - int IS_ALIVE_RETURNED_VALUE = 1; - - /** - * Always return {@link #IS_ALIVE_RETURNED_VALUE} unless a database or connection error occurs. - */ - int isAlive(); -} diff --git a/sonar-db/src/main/java/org/sonar/db/MyBatis.java b/sonar-db/src/main/java/org/sonar/db/MyBatis.java deleted file mode 100644 index 08eee68aafc..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/MyBatis.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import javax.annotation.Nullable; -import org.apache.ibatis.logging.LogFactory; -import org.apache.ibatis.session.ExecutorType; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.ce.CeActivityMapper; -import org.sonar.db.ce.CeQueueMapper; -import org.sonar.db.ce.CeScannerContextMapper; -import org.sonar.db.ce.CeTaskInputMapper; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.ComponentDtoWithSnapshotId; -import org.sonar.db.component.ComponentKeyUpdaterMapper; -import org.sonar.db.component.ComponentLinkDto; -import org.sonar.db.component.ComponentLinkMapper; -import org.sonar.db.component.ComponentMapper; -import org.sonar.db.component.FilePathWithHashDto; -import org.sonar.db.component.ResourceDto; -import org.sonar.db.component.ResourceMapper; -import org.sonar.db.component.SnapshotDto; -import org.sonar.db.component.SnapshotMapper; -import org.sonar.db.component.UuidWithProjectUuidDto; -import org.sonar.db.component.ViewsSnapshotDto; -import org.sonar.db.debt.RequirementMigrationDto; -import org.sonar.db.duplication.DuplicationMapper; -import org.sonar.db.duplication.DuplicationUnitDto; -import org.sonar.db.event.EventDto; -import org.sonar.db.event.EventMapper; -import org.sonar.db.issue.IssueChangeDto; -import org.sonar.db.issue.IssueChangeMapper; -import org.sonar.db.issue.IssueDto; -import org.sonar.db.issue.IssueMapper; -import org.sonar.db.loadedtemplate.LoadedTemplateDto; -import org.sonar.db.loadedtemplate.LoadedTemplateMapper; -import org.sonar.db.measure.MeasureDto; -import org.sonar.db.measure.MeasureMapper; -import org.sonar.db.measure.custom.CustomMeasureDto; -import org.sonar.db.measure.custom.CustomMeasureMapper; -import org.sonar.db.metric.MetricMapper; -import org.sonar.db.notification.NotificationQueueDto; -import org.sonar.db.notification.NotificationQueueMapper; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.organization.OrganizationMapper; -import org.sonar.db.permission.AuthorizationMapper; -import org.sonar.db.permission.GroupPermissionDto; -import org.sonar.db.permission.GroupPermissionMapper; -import org.sonar.db.permission.UserPermissionDto; -import org.sonar.db.permission.UserPermissionMapper; -import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; -import org.sonar.db.permission.template.PermissionTemplateCharacteristicMapper; -import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.db.permission.template.PermissionTemplateGroupDto; -import org.sonar.db.permission.template.PermissionTemplateMapper; -import org.sonar.db.permission.template.PermissionTemplateUserDto; -import org.sonar.db.property.InternalPropertiesMapper; -import org.sonar.db.property.InternalPropertyDto; -import org.sonar.db.property.PropertiesMapper; -import org.sonar.db.property.ScrapPropertyDto; -import org.sonar.db.purge.IdUuidPair; -import org.sonar.db.purge.PurgeMapper; -import org.sonar.db.purge.PurgeableAnalysisDto; -import org.sonar.db.qualitygate.ProjectQgateAssociationDto; -import org.sonar.db.qualitygate.ProjectQgateAssociationMapper; -import org.sonar.db.qualitygate.QualityGateConditionDto; -import org.sonar.db.qualitygate.QualityGateConditionMapper; -import org.sonar.db.qualitygate.QualityGateDto; -import org.sonar.db.qualitygate.QualityGateMapper; -import org.sonar.db.qualityprofile.ActiveRuleDto; -import org.sonar.db.qualityprofile.ActiveRuleMapper; -import org.sonar.db.qualityprofile.ActiveRuleParamDto; -import org.sonar.db.qualityprofile.QProfileChangeMapper; -import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.db.qualityprofile.QualityProfileMapper; -import org.sonar.db.rule.RuleDto; -import org.sonar.db.rule.RuleMapper; -import org.sonar.db.rule.RuleParamDto; -import org.sonar.db.rule.RuleRepositoryMapper; -import org.sonar.db.schemamigration.SchemaMigrationDto; -import org.sonar.db.schemamigration.SchemaMigrationMapper; -import org.sonar.db.source.FileSourceMapper; -import org.sonar.db.user.AuthorDto; -import org.sonar.db.user.AuthorMapper; -import org.sonar.db.user.GroupDto; -import org.sonar.db.user.GroupMapper; -import org.sonar.db.user.GroupMembershipDto; -import org.sonar.db.user.GroupMembershipMapper; -import org.sonar.db.user.RoleMapper; -import org.sonar.db.user.UserDto; -import org.sonar.db.user.UserGroupDto; -import org.sonar.db.user.UserGroupMapper; -import org.sonar.db.user.UserMapper; -import org.sonar.db.user.UserTokenCount; -import org.sonar.db.user.UserTokenDto; -import org.sonar.db.user.UserTokenMapper; -import org.sonar.db.webhook.WebhookDeliveryMapper; - -public class MyBatis { - - private final Database database; - private SqlSessionFactory sessionFactory; - - public MyBatis(Database database) { - this.database = database; - } - - // FIXME should be visible only to DAOs -> to be moved to AbstractDao - public static void closeQuietly(@Nullable SqlSession session) { - if (session != null) { - try { - session.close(); - } catch (Exception e) { - Loggers.get(MyBatis.class).warn("Fail to close db session", e); - // do not re-throw the exception - } - } - } - - public MyBatis start() { - LogFactory.useSlf4jLogging(); - - MyBatisConfBuilder confBuilder = new MyBatisConfBuilder(database); - - // DTO aliases, keep them sorted alphabetically - confBuilder.loadAlias("ActiveRule", ActiveRuleDto.class); - confBuilder.loadAlias("ActiveRuleParam", ActiveRuleParamDto.class); - confBuilder.loadAlias("Author", AuthorDto.class); - confBuilder.loadAlias("Component", ComponentDto.class); - confBuilder.loadAlias("ComponentLink", ComponentLinkDto.class); - confBuilder.loadAlias("ComponentWithSnapshot", ComponentDtoWithSnapshotId.class); - confBuilder.loadAlias("CustomMeasure", CustomMeasureDto.class); - confBuilder.loadAlias("DuplicationUnit", DuplicationUnitDto.class); - confBuilder.loadAlias("Event", EventDto.class); - confBuilder.loadAlias("FilePathWithHash", FilePathWithHashDto.class); - confBuilder.loadAlias("Group", GroupDto.class); - confBuilder.loadAlias("GroupMembership", GroupMembershipDto.class); - confBuilder.loadAlias("GroupPermission", GroupPermissionDto.class); - confBuilder.loadAlias("IdUuidPair", IdUuidPair.class); - confBuilder.loadAlias("InternalProperty", InternalPropertyDto.class); - confBuilder.loadAlias("IssueChange", IssueChangeDto.class); - confBuilder.loadAlias("Issue", IssueDto.class); - confBuilder.loadAlias("LoadedTemplate", LoadedTemplateDto.class); - confBuilder.loadAlias("Measure", MeasureDto.class); - confBuilder.loadAlias("NotificationQueue", NotificationQueueDto.class); - confBuilder.loadAlias("Organization", OrganizationDto.class); - confBuilder.loadAlias("PermissionTemplateCharacteristic", PermissionTemplateCharacteristicDto.class); - confBuilder.loadAlias("PermissionTemplateGroup", PermissionTemplateGroupDto.class); - confBuilder.loadAlias("PermissionTemplate", PermissionTemplateDto.class); - confBuilder.loadAlias("PermissionTemplateUser", PermissionTemplateUserDto.class); - confBuilder.loadAlias("ProjectQgateAssociation", ProjectQgateAssociationDto.class); - confBuilder.loadAlias("PurgeableAnalysis", PurgeableAnalysisDto.class); - confBuilder.loadAlias("QualityGateCondition", QualityGateConditionDto.class); - confBuilder.loadAlias("QualityGate", QualityGateDto.class); - confBuilder.loadAlias("QualityProfile", QualityProfileDto.class); - confBuilder.loadAlias("RequirementMigration", RequirementMigrationDto.class); - confBuilder.loadAlias("Resource", ResourceDto.class); - confBuilder.loadAlias("RuleParam", RuleParamDto.class); - confBuilder.loadAlias("Rule", RuleDto.class); - confBuilder.loadAlias("SchemaMigration", SchemaMigrationDto.class); - confBuilder.loadAlias("ScrapProperty", ScrapPropertyDto.class); - confBuilder.loadAlias("Snapshot", SnapshotDto.class); - confBuilder.loadAlias("UserGroup", UserGroupDto.class); - confBuilder.loadAlias("UserPermission", UserPermissionDto.class); - confBuilder.loadAlias("UserTokenCount", UserTokenCount.class); - confBuilder.loadAlias("UserToken", UserTokenDto.class); - confBuilder.loadAlias("User", UserDto.class); - confBuilder.loadAlias("UuidWithProjectUuid", UuidWithProjectUuidDto.class); - confBuilder.loadAlias("ViewsSnapshot", ViewsSnapshotDto.class); - - // ResourceMapper has to be loaded before IssueMapper because this last one used it - confBuilder.loadMapper(ResourceMapper.class); - - // keep them sorted alphabetically - Class<?>[] mappers = { - ActiveRuleMapper.class, - AuthorMapper.class, - AuthorizationMapper.class, - CeActivityMapper.class, - CeQueueMapper.class, - CeScannerContextMapper.class, - CeTaskInputMapper.class, - ComponentKeyUpdaterMapper.class, - ComponentLinkMapper.class, - ComponentMapper.class, - CustomMeasureMapper.class, - DuplicationMapper.class, - EventMapper.class, - FileSourceMapper.class, - GroupMapper.class, - GroupMembershipMapper.class, - GroupPermissionMapper.class, - InternalPropertiesMapper.class, - IsAliveMapper.class, - IssueChangeMapper.class, - IssueMapper.class, - LoadedTemplateMapper.class, - MeasureMapper.class, - MetricMapper.class, - NotificationQueueMapper.class, - OrganizationMapper.class, - PermissionTemplateCharacteristicMapper.class, - PermissionTemplateMapper.class, - ProjectQgateAssociationMapper.class, - PropertiesMapper.class, - PurgeMapper.class, - QProfileChangeMapper.class, - QualityGateConditionMapper.class, - QualityGateMapper.class, - QualityProfileMapper.class, - RoleMapper.class, - RuleMapper.class, - RuleRepositoryMapper.class, - SchemaMigrationMapper.class, - SnapshotMapper.class, - UserGroupMapper.class, - UserMapper.class, - UserPermissionMapper.class, - UserTokenMapper.class, - WebhookDeliveryMapper.class - }; - confBuilder.loadMappers(mappers); - - sessionFactory = new SqlSessionFactoryBuilder().build(confBuilder.build()); - return this; - } - - public SqlSessionFactory getSessionFactory() { - return sessionFactory; - } - - /** - * @deprecated since 4.4. Replaced by <code>openSession(false)</code>. - */ - @Deprecated - public SqlSession openSession() { - return openSession(false); - } - - /** - * @since 4.4 - */ - public DbSession openSession(boolean batch) { - if (batch) { - SqlSession session = sessionFactory.openSession(ExecutorType.BATCH); - return new BatchSession(session); - } - SqlSession session = sessionFactory.openSession(ExecutorType.REUSE); - return new DbSession(session); - } - - /** - * Create a PreparedStatement for SELECT requests with scrolling of results - */ - public PreparedStatement newScrollingSelectStatement(DbSession session, String sql) { - int fetchSize = database.getDialect().getScrollDefaultFetchSize(); - return newScrollingSelectStatement(session, sql, fetchSize); - } - - /** - * Create a PreparedStatement for SELECT requests with scrolling of results row by row (only one row - * in memory at a time) - */ - public PreparedStatement newScrollingSingleRowSelectStatement(DbSession session, String sql) { - int fetchSize = database.getDialect().getScrollSingleRowFetchSize(); - return newScrollingSelectStatement(session, sql, fetchSize); - } - - private static PreparedStatement newScrollingSelectStatement(DbSession session, String sql, int fetchSize) { - try { - PreparedStatement stmt = session.getConnection().prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - stmt.setFetchSize(fetchSize); - return stmt; - } catch (SQLException e) { - throw new IllegalStateException("Fail to create SQL statement: " + sql, e); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/MyBatisConfBuilder.java b/sonar-db/src/main/java/org/sonar/db/MyBatisConfBuilder.java deleted file mode 100644 index 2dd2f2918cf..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/MyBatisConfBuilder.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import com.google.common.io.Closeables; -import java.io.InputStream; -import org.apache.ibatis.builder.xml.XMLMapperBuilder; -import org.apache.ibatis.mapping.Environment; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.LocalCacheScope; -import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; -import org.apache.ibatis.type.JdbcType; -import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.dialect.Dialect; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.lang.String.format; - -public final class MyBatisConfBuilder { - private final Configuration conf; - - public MyBatisConfBuilder(Database database) { - this.conf = new Configuration(); - this.conf.setEnvironment(new Environment("production", createTransactionFactory(), database.getDataSource())); - this.conf.setUseGeneratedKeys(true); - this.conf.setLazyLoadingEnabled(false); - this.conf.setJdbcTypeForNull(JdbcType.NULL); - Dialect dialect = database.getDialect(); - this.conf.setDatabaseId(dialect.getId()); - this.conf.getVariables().setProperty("_true", dialect.getTrueSqlValue()); - this.conf.getVariables().setProperty("_false", dialect.getFalseSqlValue()); - this.conf.getVariables().setProperty("_scrollFetchSize", String.valueOf(dialect.getScrollDefaultFetchSize())); - this.conf.setLocalCacheScope(LocalCacheScope.STATEMENT); - } - - public void loadAlias(String alias, Class dtoClass) { - conf.getTypeAliasRegistry().registerAlias(alias, dtoClass); - } - - public void loadMapper(String mapperName) { - String configFile = configFilePath(mapperName); - InputStream input = null; - try { - input = getClass().getResourceAsStream(configFile); - checkArgument(input != null, format("Can not find mapper XML file %s", configFile)); - new XMLMapperBuilder(input, conf, mapperName, conf.getSqlFragments()).parse(); - loadAndConfigureLogger(mapperName); - } catch (Exception e) { - throw new IllegalArgumentException("Unable to load mapper " + mapperName, e); - } finally { - Closeables.closeQuietly(input); - } - } - - public void loadMapper(Class mapperClass) { - String configFile = configFilePath(mapperClass); - InputStream input = null; - try { - input = mapperClass.getResourceAsStream(configFile); - checkArgument(input != null, format("Can not find mapper XML file %s", configFile)); - new SQXMLMapperBuilder(mapperClass, input, conf, conf.getSqlFragments()).parse(); - loadAndConfigureLogger(mapperClass.getName()); - } catch (Exception e) { - throw new IllegalArgumentException("Unable to load mapper " + mapperClass, e); - } finally { - Closeables.closeQuietly(input); - } - } - - private static String configFilePath(Class mapperClass) { - return configFilePath(mapperClass.getName()); - } - - private static String configFilePath(String mapperName) { - return "/" + mapperName.replace('.', '/') + ".xml"; - } - - private void loadAndConfigureLogger(String mapperName) { - conf.addLoadedResource(mapperName); - Loggers.get(mapperName).setLevel(LoggerLevel.INFO); - } - - public void loadMappers(Class<?>... mapperClasses) { - for (Class mapperClass : mapperClasses) { - loadMapper(mapperClass); - } - } - - public Configuration build() { - return conf; - } - - private static JdbcTransactionFactory createTransactionFactory() { - return new JdbcTransactionFactory(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ResultSetIterator.java b/sonar-db/src/main/java/org/sonar/db/ResultSetIterator.java deleted file mode 100644 index 6545555c6d2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ResultSetIterator.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.Closeable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.apache.commons.dbutils.DbUtils; - -/** - * Forward-only {@link java.util.Iterator} over a {@link java.sql.ResultSet}. Rows are - * lazily loaded. The underlying ResultSet must be closed by calling the method - * {@link #close()} - * <p/> - * As a safeguard, the ResultSet is automatically closed after the last element has - * been retrieved via {@link #next()} or {@link #hasNext()} is called (which will return false). - * This automagic behavior is not enough to remove explicit calls to {@link #close()} - * from caller methods. Errors raised before end of traversal must still be handled. - */ -public abstract class ResultSetIterator<E> implements Iterator<E>, Closeable { - - private final ResultSet rs; - private final PreparedStatement stmt; - - private volatile boolean didNext = false; - private volatile boolean hasNext = false; - private volatile boolean closed = false; - - public ResultSetIterator(PreparedStatement stmt) throws SQLException { - this.stmt = stmt; - this.rs = stmt.executeQuery(); - } - - protected ResultSetIterator(ResultSet rs) { - this.stmt = null; - this.rs = rs; - } - - @Override - public boolean hasNext() { - if (closed) { - return false; - } - if (!didNext) { - hasNext = doNextQuietly(); - if (hasNext) { - didNext = true; - } else { - close(); - } - } - return hasNext; - } - - @Override - public E next() { - if (!hasNext()) { - close(); - throw new NoSuchElementException(); - } - try { - return read(rs); - } catch (SQLException e) { - throw new IllegalStateException("Fail to read result set row", e); - } finally { - hasNext = doNextQuietly(); - if (!hasNext) { - close(); - } - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public void close() { - closed = true; - DbUtils.closeQuietly(rs); - DbUtils.closeQuietly(stmt); - } - - protected abstract E read(ResultSet rs) throws SQLException; - - private boolean doNextQuietly() { - try { - return rs.next(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to read row of JDBC result set", e); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/RowNotFoundException.java b/sonar-db/src/main/java/org/sonar/db/RowNotFoundException.java deleted file mode 100644 index 86614240093..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/RowNotFoundException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -/** - * The RuntimeException thrown by default when a element is not found at the DAO layer. - * When selecting by id or key, the methods respect one of the following pattern: - * <ul> - * <li>selectOrFailByKey return the element or throws a RowNotFoundException</li> - * <li>selectByUuid return an Optional (now) or a nullable element (legacy)</li> - * </ul> - */ -public class RowNotFoundException extends RuntimeException { - public RowNotFoundException(String message) { - super(message); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/SQXMLMapperBuilder.java b/sonar-db/src/main/java/org/sonar/db/SQXMLMapperBuilder.java deleted file mode 100644 index 690ba2cfcf4..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/SQXMLMapperBuilder.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.InputStream; -import java.util.Map; -import org.apache.ibatis.builder.xml.XMLMapperBuilder; -import org.apache.ibatis.parsing.XNode; -import org.apache.ibatis.session.Configuration; - -/** - * Subclass of {@link XMLMapperBuilder} which fixes the fact that {@link XMLMapperBuilder} does not support loading - * Mapper interfaces which belongs to the ClassLoader of a plugin. - */ -public class SQXMLMapperBuilder extends XMLMapperBuilder { - private final Class<?> mapperType; - - public SQXMLMapperBuilder(Class<?> mapperType, InputStream inputStream, Configuration configuration, Map<String, XNode> sqlFragments) { - super(inputStream, configuration, mapperType.getName(), sqlFragments); - this.mapperType = mapperType; - } - - @Override - public void parse() { - if (!configuration.isResourceLoaded(mapperType.getName())) { - super.parse(); - retryBindMapperForNamespace(); - } - - super.parse(); - } - - private void retryBindMapperForNamespace() { - if (!configuration.hasMapper(mapperType)) { - // Spring may not know the real resource name so we set a flag - // to prevent loading again this resource from the mapper interface - // look at MapperAnnotationBuilder#loadXmlResource - configuration.addLoadedResource("namespace:" + mapperType.getName()); - configuration.addMapper(mapperType); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/WildcardPosition.java b/sonar-db/src/main/java/org/sonar/db/WildcardPosition.java deleted file mode 100644 index 7269f089ce2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/WildcardPosition.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -public enum WildcardPosition { - BEFORE, AFTER, BEFORE_AND_AFTER -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDao.java b/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDao.java deleted file mode 100644 index a0dc3ee387e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDao.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import com.google.common.base.Optional; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import javax.annotation.Nullable; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeUpdates; - -public class CeActivityDao implements Dao { - - private final System2 system2; - - public CeActivityDao(System2 system2) { - this.system2 = system2; - } - - public Optional<CeActivityDto> selectByUuid(DbSession dbSession, String uuid) { - return Optional.fromNullable(mapper(dbSession).selectByUuid(uuid)); - } - - public void insert(DbSession dbSession, CeActivityDto dto) { - dto.setCreatedAt(system2.now()); - dto.setUpdatedAt(system2.now()); - dto.setIsLast(dto.getStatus() != CeActivityDto.Status.CANCELED); - - CeActivityMapper ceActivityMapper = mapper(dbSession); - if (dto.getIsLast()) { - ceActivityMapper.updateIsLastToFalseForLastKey(dto.getIsLastKey(), dto.getUpdatedAt()); - } - ceActivityMapper.insert(dto); - } - - public List<CeActivityDto> selectOlderThan(DbSession dbSession, long beforeDate) { - return mapper(dbSession).selectOlderThan(beforeDate); - } - - public void deleteByUuids(DbSession dbSession, Set<String> uuids) { - executeLargeUpdates(uuids, mapper(dbSession)::deleteByUuids); - } - - /** - * Ordered by id desc -> newest to oldest - */ - public List<CeActivityDto> selectByQuery(DbSession dbSession, CeTaskQuery query, int offset, int pageSize) { - if (query.isShortCircuitedByComponentUuids()) { - return Collections.emptyList(); - } - - return mapper(dbSession).selectByQuery(query, offset, pageSize); - } - - public int countLastByStatusAndComponentUuid(DbSession dbSession, CeActivityDto.Status status, @Nullable String componentUuid) { - return mapper(dbSession).countLastByStatusAndComponentUuid(status, componentUuid); - } - - private static CeActivityMapper mapper(DbSession dbSession) { - return dbSession.getMapper(CeActivityMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDto.java b/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDto.java deleted file mode 100644 index 67dcc2b376c..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityDto.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.lang.String.format; - -public class CeActivityDto { - - private static final int MAX_SIZE_ERROR_MESSAGE = 1000; - - public enum Status { - SUCCESS, FAILED, CANCELED - } - - private String uuid; - private String componentUuid; - private String analysisUuid; - private Status status; - private String taskType; - private boolean isLast; - private String isLastKey; - private String submitterLogin; - private long submittedAt; - private Long startedAt; - private Long executedAt; - private long createdAt; - private long updatedAt; - private Long executionTimeMs; - /** - * The error message of the activity. Shall be non null only when status is FAILED. When status is FAILED, can be null - * (eg. for activity created before the column has been introduced). - * <p> - * This property is populated when inserting <strong>AND when reading</strong> - * </p> - */ - private String errorMessage; - /** - * The error stacktrace (if any). Shall be non null only when status is FAILED. When status is FAILED, can be null - * because exception such as MessageException do not have a stacktrace (ie. functional exceptions). - * <p> - * This property can be populated when inserting but <strong>is populated only when reading by a specific UUID.</strong> - * </p> - * - * @see CeActivityDao#selectByUuid(DbSession, String) - */ - private String errorStacktrace; - /** - * Flag indicating whether the analysis of the current activity has a scanner context or not. - * <p> - * This property can not be populated when inserting but <strong>is populated when reading</strong>. - * </p> - */ - private boolean hasScannerContext; - - CeActivityDto() { - // required for MyBatis - } - - public CeActivityDto(CeQueueDto queueDto) { - this.uuid = queueDto.getUuid(); - this.taskType = queueDto.getTaskType(); - this.componentUuid = queueDto.getComponentUuid(); - this.isLastKey = format("%s%s", taskType, Strings.nullToEmpty(componentUuid)); - this.submitterLogin = queueDto.getSubmitterLogin(); - this.submittedAt = queueDto.getCreatedAt(); - this.startedAt = queueDto.getStartedAt(); - } - - public String getUuid() { - return uuid; - } - - public CeActivityDto setUuid(String s) { - checkArgument(s.length() <= 40, "Value is too long for column CE_ACTIVITY.UUID: %s", s); - this.uuid = s; - return this; - } - - public String getTaskType() { - return taskType; - } - - public CeActivityDto setTaskType(String s) { - this.taskType = s; - return this; - } - - @CheckForNull - public String getComponentUuid() { - return componentUuid; - } - - public CeActivityDto setComponentUuid(@Nullable String s) { - checkArgument(s == null || s.length() <= 40, "Value is too long for column CE_ACTIVITY.COMPONENT_UUID: %s", s); - this.componentUuid = s; - return this; - } - - public Status getStatus() { - return status; - } - - public CeActivityDto setStatus(Status s) { - this.status = s; - return this; - } - - public boolean getIsLast() { - return isLast; - } - - CeActivityDto setIsLast(boolean b) { - this.isLast = b; - return this; - } - - public String getIsLastKey() { - return isLastKey; - } - - @CheckForNull - public String getSubmitterLogin() { - return submitterLogin; - } - - public long getSubmittedAt() { - return submittedAt; - } - - public CeActivityDto setSubmittedAt(long submittedAt) { - this.submittedAt = submittedAt; - return this; - } - - @CheckForNull - public Long getStartedAt() { - return startedAt; - } - - public CeActivityDto setStartedAt(@Nullable Long l) { - this.startedAt = l; - return this; - } - - @CheckForNull - public Long getExecutedAt() { - return executedAt; - } - - public CeActivityDto setExecutedAt(@Nullable Long l) { - this.executedAt = l; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public CeActivityDto setCreatedAt(long l) { - this.createdAt = l; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public CeActivityDto setUpdatedAt(long l) { - this.updatedAt = l; - return this; - } - - @CheckForNull - public Long getExecutionTimeMs() { - return executionTimeMs; - } - - public CeActivityDto setExecutionTimeMs(@Nullable Long l) { - checkArgument(l == null || l >= 0, "Execution time must be positive: %s", l); - this.executionTimeMs = l; - return this; - } - - @CheckForNull - public String getAnalysisUuid() { - return analysisUuid; - } - - public CeActivityDto setAnalysisUuid(@Nullable String s) { - this.analysisUuid = s; - return this; - } - - @CheckForNull - public String getErrorMessage() { - return errorMessage; - } - - public CeActivityDto setErrorMessage(@Nullable String errorMessage) { - this.errorMessage = ensureNotTooBig(errorMessage, MAX_SIZE_ERROR_MESSAGE); - return this; - } - - @CheckForNull - private static String ensureNotTooBig(@Nullable String str, int maxSize) { - if (str == null) { - return null; - } - if (str.length() <= maxSize) { - return str; - } - return str.substring(0, maxSize); - } - - @CheckForNull - public String getErrorStacktrace() { - return errorStacktrace; - } - - @CheckForNull - public CeActivityDto setErrorStacktrace(@Nullable String errorStacktrace) { - this.errorStacktrace = errorStacktrace; - return this; - } - - public boolean isHasScannerContext() { - return hasScannerContext; - } - - protected void setHasScannerContext(boolean hasScannerContext) { - this.hasScannerContext = hasScannerContext; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("uuid", uuid) - .add("taskType", taskType) - .add("componentUuid", componentUuid) - .add("analysisUuid", analysisUuid) - .add("status", status) - .add("isLast", isLast) - .add("isLastKey", isLastKey) - .add("submitterLogin", submitterLogin) - .add("submittedAt", submittedAt) - .add("startedAt", startedAt) - .add("executedAt", executedAt) - .add("createdAt", createdAt) - .add("updatedAt", updatedAt) - .add("executionTimeMs", executionTimeMs) - .add("errorMessage", errorMessage) - .add("errorStacktrace", errorStacktrace) - .add("hasScannerContext", hasScannerContext) - .toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityMapper.java b/sonar-db/src/main/java/org/sonar/db/ce/CeActivityMapper.java deleted file mode 100644 index e8838e782f2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeActivityMapper.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; - -public interface CeActivityMapper { - - @CheckForNull - CeActivityDto selectByUuid(@Param("uuid") String uuid); - - List<CeActivityDto> selectByComponentUuid(@Param("componentUuid") String componentUuid); - - List<CeActivityDto> selectByQuery(@Param("query") CeTaskQuery query, @Param("offset") int offset, @Param("pageSize") int pageSize); - - List<CeActivityDto> selectOlderThan(@Param("beforeDate") long beforeDate); - - int countLastByStatusAndComponentUuid(@Param("status") CeActivityDto.Status status, @Nullable @Param("componentUuid") String componentUuid); - - void insert(CeActivityDto dto); - - void updateIsLastToFalseForLastKey(@Param("isLastKey") String isLastKey, @Param("updatedAt") long updatedAt); - - void deleteByUuids(@Param("uuids") List<String> uuids); -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDao.java b/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDao.java deleted file mode 100644 index d494515230e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDao.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import com.google.common.base.Optional; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.session.RowBounds; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static java.util.Collections.emptyList; -import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; -import static org.sonar.db.ce.CeQueueDto.Status.PENDING; - -public class CeQueueDao implements Dao { - - private static final RowBounds ONE_ROW_LIMIT = new RowBounds(0, 1); - - private final System2 system2; - - public CeQueueDao(System2 system2) { - this.system2 = system2; - } - - /** - * Ordered by ascending id: oldest to newest - */ - public List<CeQueueDto> selectAllInAscOrder(DbSession session) { - return mapper(session).selectAllInAscOrder(); - } - - public List<CeQueueDto> selectByQueryInDescOrder(DbSession dbSession, CeTaskQuery query, int pageSize) { - if (query.isShortCircuitedByComponentUuids() - || query.isOnlyCurrents() - || query.getMaxExecutedAt() != null) { - return emptyList(); - } - - return mapper(dbSession).selectByQueryInDescOrder(query, new RowBounds(0, pageSize)); - } - - public int countByQuery(DbSession dbSession, CeTaskQuery query) { - if (query.isShortCircuitedByComponentUuids() - || query.isOnlyCurrents() - || query.getMaxExecutedAt() != null) { - return 0; - } - - return mapper(dbSession).countByQuery(query); - } - - /** - * Ordered by ascending id: oldest to newest - */ - public List<CeQueueDto> selectByComponentUuid(DbSession session, String componentUuid) { - return mapper(session).selectByComponentUuid(componentUuid); - } - - public Optional<CeQueueDto> selectByUuid(DbSession session, String uuid) { - return Optional.fromNullable(mapper(session).selectByUuid(uuid)); - } - - public CeQueueDto insert(DbSession session, CeQueueDto dto) { - if (dto.getCreatedAt() == 0L || dto.getUpdatedAt() == 0L) { - dto.setCreatedAt(system2.now()); - dto.setUpdatedAt(system2.now()); - } - - mapper(session).insert(dto); - return dto; - } - - public void deleteByUuid(DbSession session, String uuid) { - mapper(session).deleteByUuid(uuid); - } - - /** - * Update all rows with: STATUS='PENDING', STARTED_AT=NULL, UPDATED_AT={now} - */ - public void resetAllToPendingStatus(DbSession session) { - mapper(session).resetAllToPendingStatus(system2.now()); - } - - public int countByStatus(DbSession dbSession, CeQueueDto.Status status) { - return mapper(dbSession).countByStatusAndComponentUuid(status, null); - } - - public int countByStatusAndComponentUuid(DbSession dbSession, CeQueueDto.Status status, @Nullable String componentUuid) { - return mapper(dbSession).countByStatusAndComponentUuid(status, componentUuid); - } - - public Optional<CeQueueDto> peek(DbSession session) { - List<String> taskUuids = mapper(session).selectEligibleForPeek(ONE_ROW_LIMIT); - if (taskUuids.isEmpty()) { - return Optional.absent(); - } - - String taskUuid = taskUuids.get(0); - return tryToPeek(session, taskUuid); - } - - private Optional<CeQueueDto> tryToPeek(DbSession session, String taskUuid) { - int touchedRows = mapper(session).updateIfStatus(taskUuid, IN_PROGRESS, system2.now(), system2.now(), PENDING); - if (touchedRows != 1) { - return Optional.absent(); - } - - CeQueueDto result = mapper(session).selectByUuid(taskUuid); - session.commit(); - return Optional.of(result); - } - - private static CeQueueMapper mapper(DbSession session) { - return session.getMapper(CeQueueMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDto.java b/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDto.java deleted file mode 100644 index d39b730e30c..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueDto.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import com.google.common.base.MoreObjects; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkArgument; - -public class CeQueueDto { - - public enum Status { - PENDING, IN_PROGRESS - } - - private String uuid; - private String taskType; - private String componentUuid; - private Status status; - private String submitterLogin; - private Long startedAt; - private long createdAt; - private long updatedAt; - - public String getUuid() { - return uuid; - } - - public CeQueueDto setUuid(String s) { - checkArgument(s.length() <= 40, "Value of UUID is too long: %s", s); - this.uuid = s; - return this; - } - - @CheckForNull - public String getComponentUuid() { - return componentUuid; - } - - public CeQueueDto setComponentUuid(@Nullable String s) { - checkArgument(s == null || s.length() <= 40, "Value of component UUID is too long: %s", s); - this.componentUuid = s; - return this; - } - - public Status getStatus() { - return status; - } - - public CeQueueDto setStatus(Status s) { - this.status = s; - return this; - } - - public String getTaskType() { - return taskType; - } - - public CeQueueDto setTaskType(String s) { - checkArgument(s.length() <= 15, "Value of task type is too long: %s", s); - this.taskType = s; - return this; - } - - @CheckForNull - public String getSubmitterLogin() { - return submitterLogin; - } - - public CeQueueDto setSubmitterLogin(@Nullable String s) { - checkArgument(s == null || s.length() <= 255, "Value of submitter login is too long: %s", s); - this.submitterLogin = s; - return this; - } - - @CheckForNull - public Long getStartedAt() { - return startedAt; - } - - public CeQueueDto setStartedAt(@Nullable Long l) { - this.startedAt = l; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public CeQueueDto setCreatedAt(long l) { - this.createdAt = l; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public CeQueueDto setUpdatedAt(long l) { - this.updatedAt = l; - return this; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("uuid", uuid) - .add("taskType", taskType) - .add("componentUuid", componentUuid) - .add("status", status) - .add("submitterLogin", submitterLogin) - .add("startedAt", startedAt) - .add("createdAt", createdAt) - .add("updatedAt", updatedAt) - .toString(); - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - CeQueueDto that = (CeQueueDto) o; - return uuid.equals(that.uuid); - - } - - @Override - public int hashCode() { - return uuid.hashCode(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueMapper.java b/sonar-db/src/main/java/org/sonar/db/ce/CeQueueMapper.java deleted file mode 100644 index e3556a9e05a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeQueueMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface CeQueueMapper { - - List<CeQueueDto> selectByComponentUuid(@Param("componentUuid") String componentUuid); - - List<CeQueueDto> selectAllInAscOrder(); - - List<CeQueueDto> selectByQueryInDescOrder(@Param("query") CeTaskQuery query, RowBounds rowBounds); - - int countByQuery(@Param("query") CeTaskQuery query); - - List<String> selectEligibleForPeek(RowBounds rowBounds); - - @CheckForNull - CeQueueDto selectByUuid(@Param("uuid") String uuid); - - int countByStatusAndComponentUuid(@Param("status") CeQueueDto.Status status, @Nullable @Param("componentUuid") String componentUuid); - - void insert(CeQueueDto dto); - - void resetAllToPendingStatus(@Param("updatedAt") long updatedAt); - - int updateIfStatus(@Param("uuid") String uuid, - @Param("newStatus") CeQueueDto.Status newStatus, - @Nullable @Param("startedAt") Long startedAt, - @Param("updatedAt") long updatedAt, - @Param("oldStatus") CeQueueDto.Status oldStatus); - - void deleteByUuid(@Param("uuid") String uuid); -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextDao.java b/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextDao.java deleted file mode 100644 index 2bdf88965a4..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextDao.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Optional; -import org.apache.commons.io.IOUtils; -import org.sonar.api.utils.System2; -import org.sonar.core.util.CloseableIterator; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; - -public class CeScannerContextDao implements Dao { - - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - private final System2 system; - - public CeScannerContextDao(System2 system) { - this.system = system; - } - - /** - * @throws IllegalArgumentException if {@code scannerContextLines} is empty or fully read. - */ - public void insert(DbSession dbSession, String taskUuid, CloseableIterator<String> scannerContextLines) { - checkArgument(scannerContextLines.hasNext(), "Scanner context can not be empty"); - long now = system.now(); - Connection connection = dbSession.getConnection(); - try (PreparedStatement stmt = connection.prepareStatement( - "INSERT INTO ce_scanner_context (task_uuid, created_at, updated_at, context_data) VALUES (?, ?, ?, ?)"); - InputStream inputStream = new LogsIteratorInputStream(scannerContextLines, UTF_8)) { - stmt.setString(1, taskUuid); - stmt.setLong(2, now); - stmt.setLong(3, now); - stmt.setBinaryStream(4, inputStream); - stmt.executeUpdate(); - connection.commit(); - } catch (SQLException | IOException e) { - throw new IllegalStateException("Fail to insert scanner context for task " + taskUuid, e); - } - } - - /** - * The scanner context is very likely to contain lines, which are forcefully separated by {@code \n} characters, - * whichever the platform SQ is running on ({@see LogsIteratorInputStream}). - */ - public Optional<String> selectScannerContext(DbSession dbSession, String taskUuid) { - try (PreparedStatement stmt = dbSession.getConnection().prepareStatement("select context_data from ce_scanner_context where task_uuid=?")) { - stmt.setString(1, taskUuid); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return Optional.of(IOUtils.toString(rs.getBinaryStream(1), UTF_8)); - } - return Optional.empty(); - } - } catch (SQLException | IOException e) { - throw new IllegalStateException("Fail to retrieve scanner context of task " + taskUuid, e); - } - } - - public void deleteByUuids(DbSession dbSession, Collection<String> uuids) { - DatabaseUtils.executeLargeUpdates(uuids, mapper(dbSession)::deleteByUuids); - } - - private static CeScannerContextMapper mapper(DbSession dbSession) { - return dbSession.getMapper(CeScannerContextMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextMapper.java b/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextMapper.java deleted file mode 100644 index 9d116d17a28..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeScannerContextMapper.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface CeScannerContextMapper { - - void deleteByUuids(@Param("uuids") List<String> uuids); -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputDao.java b/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputDao.java deleted file mode 100644 index 3593db1e9d7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputDao.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.io.InputStream; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import org.apache.commons.io.IOUtils; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; - -public class CeTaskInputDao implements Dao { - - private final System2 system; - - public CeTaskInputDao(System2 system) { - this.system = system; - } - - public void insert(DbSession dbSession, String taskUuid, InputStream data) { - long now = system.now(); - Connection connection = dbSession.getConnection(); - try (PreparedStatement stmt = connection.prepareStatement( - "INSERT INTO ce_task_input (task_uuid, created_at, updated_at, input_data) VALUES (?, ?, ?, ?)")) { - stmt.setString(1, taskUuid); - stmt.setLong(2, now); - stmt.setLong(3, now); - stmt.setBinaryStream(4, data); - stmt.executeUpdate(); - connection.commit(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to insert data of CE task " + taskUuid, e); - } - } - - public Optional<DataStream> selectData(DbSession dbSession, String taskUuid) { - PreparedStatement stmt = null; - ResultSet rs = null; - DataStream result = null; - try { - stmt = dbSession.getConnection().prepareStatement("SELECT input_data FROM ce_task_input WHERE task_uuid=? AND input_data IS NOT NULL"); - stmt.setString(1, taskUuid); - rs = stmt.executeQuery(); - if (rs.next()) { - result = new DataStream(stmt, rs, rs.getBinaryStream(1)); - return Optional.of(result); - } - return Optional.empty(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to select data of CE task " + taskUuid, e); - } finally { - if (result == null) { - DatabaseUtils.closeQuietly(rs); - DatabaseUtils.closeQuietly(stmt); - } - } - } - - public List<String> selectUuidsNotInQueue(DbSession dbSession) { - return dbSession.getMapper(CeTaskInputMapper.class).selectUuidsNotInQueue(); - } - - public void deleteByUuids(DbSession dbSession, Collection<String> uuids) { - CeTaskInputMapper mapper = dbSession.getMapper(CeTaskInputMapper.class); - DatabaseUtils.executeLargeUpdates(uuids, mapper::deleteByUuids); - } - - public static class DataStream implements AutoCloseable { - private final PreparedStatement stmt; - private final ResultSet rs; - private final InputStream stream; - - private DataStream(PreparedStatement stmt, ResultSet rs, InputStream stream) { - this.stmt = stmt; - this.rs = rs; - this.stream = stream; - } - - public InputStream getInputStream() { - return stream; - } - - @Override - public void close() { - IOUtils.closeQuietly(stream); - DatabaseUtils.closeQuietly(rs); - DatabaseUtils.closeQuietly(stmt); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputMapper.java b/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputMapper.java deleted file mode 100644 index 80ed6ce39f3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskInputMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface CeTaskInputMapper { - - void deleteByUuids(@Param("uuids") List<String> uuids); - - List<String> selectUuidsNotInQueue(); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskQuery.java b/sonar-db/src/main/java/org/sonar/db/ce/CeTaskQuery.java deleted file mode 100644 index 3598144db19..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskQuery.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.ArrayList; -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.DatabaseUtils; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * Db Query used for CE_QUEUE and CE_ACTIVITY tables - */ -public class CeTaskQuery { - - public static final int MAX_COMPONENT_UUIDS = DatabaseUtils.PARTITION_SIZE_FOR_ORACLE; - - private boolean onlyCurrents = false; - // SONAR-7681 a public implementation of List must be used in MyBatis - potential concurrency exceptions otherwise - private ArrayList<String> componentUuids; - private ArrayList<String> statuses; - private String type; - private Long minSubmittedAt; - private Long maxExecutedAt; - - @CheckForNull - public List<String> getComponentUuids() { - return componentUuids; - } - - public CeTaskQuery setComponentUuids(@Nullable List<String> l) { - this.componentUuids = l == null ? null : newArrayList(l); - return this; - } - - public boolean isShortCircuitedByComponentUuids() { - return componentUuids != null && (componentUuids.isEmpty() || componentUuids.size() > MAX_COMPONENT_UUIDS); - } - - public CeTaskQuery setComponentUuid(@Nullable String s) { - if (s == null) { - this.componentUuids = null; - } else { - this.componentUuids = newArrayList(s); - } - return this; - } - - public boolean isOnlyCurrents() { - return onlyCurrents; - } - - public CeTaskQuery setOnlyCurrents(boolean onlyCurrents) { - this.onlyCurrents = onlyCurrents; - return this; - } - - @CheckForNull - public List<String> getStatuses() { - return statuses; - } - - public CeTaskQuery setStatuses(@Nullable List<String> statuses) { - this.statuses = statuses == null ? null : newArrayList(statuses); - return this; - } - - @CheckForNull - public String getType() { - return type; - } - - public CeTaskQuery setType(@Nullable String type) { - this.type = type; - return this; - } - - @CheckForNull - public Long getMaxExecutedAt() { - return maxExecutedAt; - } - - public CeTaskQuery setMaxExecutedAt(@Nullable Long l) { - this.maxExecutedAt = l; - return this; - } - - @CheckForNull - public Long getMinSubmittedAt() { - return minSubmittedAt; - } - - public CeTaskQuery setMinSubmittedAt(@Nullable Long l) { - this.minSubmittedAt = l; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskTypes.java b/sonar-db/src/main/java/org/sonar/db/ce/CeTaskTypes.java deleted file mode 100644 index 69fd2afc00d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/CeTaskTypes.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -public final class CeTaskTypes { - - public static final String REPORT = "REPORT"; - - private CeTaskTypes() { - // only statics - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/LogsIteratorInputStream.java b/sonar-db/src/main/java/org/sonar/db/ce/LogsIteratorInputStream.java deleted file mode 100644 index 57914414443..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/LogsIteratorInputStream.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import org.sonar.core.util.CloseableIterator; - -import static com.google.common.base.Preconditions.checkArgument; - -/** - * An {@link InputStream} that will read from a {@link CloseableIterator} of {@link String}, inserting {@code \n} between - * each element of the Iterator. - */ -final class LogsIteratorInputStream extends InputStream { - private static final int UNSET = -1; - private static final int END_OF_STREAM = -1; - - private final Charset charset; - private final byte[] lineFeed; - private CloseableIterator<String> logsIterator; - private byte[] buf; - private int nextChar = UNSET; - - LogsIteratorInputStream(CloseableIterator<String> logsIterator, Charset charset) { - checkArgument(logsIterator.hasNext(), "LogsIterator can't be empty or already read"); - this.charset = charset; - this.lineFeed = "\n".getBytes(charset); - this.logsIterator = logsIterator; - } - - @Override - public int read() throws IOException { - if (nextChar == UNSET || nextChar >= buf.length) { - fill(); - if (nextChar == UNSET) { - return END_OF_STREAM; - } - } - return buf[nextChar++]; - } - - private void fill() { - if (logsIterator.hasNext()) { - byte[] line = logsIterator.next().getBytes(charset); - boolean hasNextLine = logsIterator.hasNext(); - int bufLength = hasNextLine ? (line.length + lineFeed.length) : line.length; - // empty last line - if (bufLength == 0) { - this.buf = null; - this.nextChar = UNSET; - } else { - this.buf = new byte[bufLength]; - System.arraycopy(line, 0, buf, 0, line.length); - if (hasNextLine) { - System.arraycopy(lineFeed, 0, buf, line.length, lineFeed.length); - } - this.nextChar = 0; - } - } else { - this.buf = null; - this.nextChar = UNSET; - } - } - - @Override - public void close() throws IOException { - this.logsIterator.close(); - this.buf = null; - - super.close(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/ce/package-info.java b/sonar-db/src/main/java/org/sonar/db/ce/package-info.java deleted file mode 100644 index e92e18cd0a2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/ce/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.ce; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentDao.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentDao.java deleted file mode 100644 index 58d9ecea350..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentDao.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.base.Optional; -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.Scopes; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Collections.emptyList; -import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang.StringUtils.isBlank; -import static org.sonar.db.DatabaseUtils.buildLikeValue; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeUpdates; -import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; - -public class ComponentDao implements Dao { - - public ComponentDto selectOrFailById(DbSession session, long id) { - Optional<ComponentDto> componentDto = selectById(session, id); - if (!componentDto.isPresent()) { - throw new RowNotFoundException(String.format("Component id does not exist: %d", id)); - } - return componentDto.get(); - } - - public Optional<ComponentDto> selectById(DbSession session, long id) { - return Optional.fromNullable(mapper(session).selectById(id)); - } - - public Optional<ComponentDto> selectByUuid(DbSession session, String uuid) { - return Optional.fromNullable(mapper(session).selectByUuid(uuid)); - } - - public ComponentDto selectOrFailByUuid(DbSession session, String uuid) { - Optional<ComponentDto> componentDto = selectByUuid(session, uuid); - if (!componentDto.isPresent()) { - throw new RowNotFoundException(String.format("Component with uuid '%s' not found", uuid)); - } - return componentDto.get(); - } - - public List<ComponentDto> selectByQuery(DbSession session, ComponentQuery query, int offset, int limit) { - return selectByQueryImpl(session, null, query, offset, limit); - } - - public List<ComponentDto> selectByQuery(DbSession dbSession, String organizationUuid, ComponentQuery query, int offset, int limit) { - requireNonNull(organizationUuid, "organizationUuid can't be null"); - return selectByQueryImpl(dbSession, organizationUuid, query, offset, limit); - } - - private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) { - Set<Long> componentIds = query.getComponentIds(); - if (componentIds != null && componentIds.isEmpty()) { - return emptyList(); - } - return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit)); - } - - public int countByQuery(DbSession session, ComponentQuery query) { - return countByQueryImpl(session, null, query); - } - - public int countByQuery(DbSession session, String organizationUuid, ComponentQuery query) { - requireNonNull(organizationUuid, "organizationUuid can't be null"); - return countByQueryImpl(session, organizationUuid, query); - } - - private static int countByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query) { - Set<Long> componentIds = query.getComponentIds(); - if (componentIds != null && componentIds.isEmpty()) { - return 0; - } - return mapper(session).countByQuery(organizationUuid, query); - } - - public List<ComponentDto> selectSubProjectsByComponentUuids(DbSession session, Collection<String> keys) { - if (keys.isEmpty()) { - return emptyList(); - } - return mapper(session).selectSubProjectsByComponentUuids(keys); - } - - public List<ComponentDto> selectDescendantModules(DbSession session, String rootComponentUuid) { - return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, false); - } - - public List<ComponentDto> selectEnabledDescendantModules(DbSession session, String rootComponentUuid) { - return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, true); - } - - public List<FilePathWithHashDto> selectEnabledDescendantFiles(DbSession session, String rootComponentUuid) { - return mapper(session).selectDescendantFiles(rootComponentUuid, Scopes.FILE, true); - } - - public List<FilePathWithHashDto> selectEnabledFilesFromProject(DbSession session, String rootComponentUuid) { - return mapper(session).selectEnabledFilesFromProject(rootComponentUuid); - } - - public List<ComponentDto> selectByIds(DbSession session, Collection<Long> ids) { - return executeLargeInputs(ids, mapper(session)::selectByIds); - } - - public List<ComponentDto> selectByUuids(DbSession session, Collection<String> uuids) { - return executeLargeInputs(uuids, mapper(session)::selectByUuids); - } - - public List<String> selectExistingUuids(DbSession session, Collection<String> uuids) { - return executeLargeInputs(uuids, mapper(session)::selectExistingUuids); - } - - /** - * Return all components of a project (including disable ones) - */ - public List<ComponentDto> selectAllComponentsFromProjectKey(DbSession session, String projectKey) { - return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, null, false); - } - - public List<ComponentDto> selectEnabledModulesFromProjectKey(DbSession session, String projectKey) { - return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, Scopes.PROJECT, true); - } - - public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys) { - return executeLargeInputs(keys, mapper(session)::selectByKeys); - } - - public List<ComponentDto> selectComponentsHavingSameKeyOrderedById(DbSession session, String key) { - return mapper(session).selectComponentsHavingSameKeyOrderedById(key); - } - - /** - * List of ancestors, ordered from root to parent. The list is empty - * if the component is a tree root. Disabled components are excluded by design - * as tree represents the more recent analysis. - */ - public List<ComponentDto> selectAncestors(DbSession dbSession, ComponentDto component) { - if (component.isRoot()) { - return Collections.emptyList(); - } - List<String> ancestorUuids = component.getUuidPathAsList(); - List<ComponentDto> ancestors = selectByUuids(dbSession, ancestorUuids); - return Ordering.explicit(ancestorUuids).onResultOf(ComponentDto::uuid).immutableSortedCopy(ancestors); - } - - /** - * Select the children or the leaves of a base component, given by its UUID. The components that are not present in last - * analysis are ignored. - * - * An empty list is returned if the base component does not exist or if the base component is a leaf. - */ - public List<ComponentDto> selectDescendants(DbSession dbSession, ComponentTreeQuery query) { - Optional<ComponentDto> componentOpt = selectByUuid(dbSession, query.getBaseUuid()); - if (!componentOpt.isPresent()) { - return emptyList(); - } - ComponentDto component = componentOpt.get(); - return mapper(dbSession).selectDescendants(query, componentOpt.get().uuid(), query.getUuidPath(component)); - } - - public ComponentDto selectOrFailByKey(DbSession session, String key) { - Optional<ComponentDto> component = selectByKey(session, key); - if (!component.isPresent()) { - throw new RowNotFoundException(String.format("Component key '%s' not found", key)); - } - return component.get(); - } - - public Optional<ComponentDto> selectByKey(DbSession session, String key) { - return Optional.fromNullable(mapper(session).selectByKey(key)); - } - - public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { - return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW); - } - - public List<String> selectProjectsFromView(DbSession session, String viewUuid, String projectViewUuid) { - return mapper(session).selectProjectsFromView("%." + viewUuid + ".%", projectViewUuid); - } - - /** - * Returns all projects (Scope {@link org.sonar.api.resources.Scopes#PROJECT} and qualifier - * {@link org.sonar.api.resources.Qualifiers#PROJECT}) which are enabled. - * - * Used by Views. - */ - public List<ComponentDto> selectProjects(DbSession session) { - return mapper(session).selectProjects(); - } - - /** - * Select all root components (projects and views), including disabled ones, for a given organization. - */ - public List<ComponentDto> selectAllRootsByOrganization(DbSession dbSession, String organizationUuid) { - return mapper(dbSession).selectAllRootsByOrganization(organizationUuid); - } - - /** - * Select a page of provisioned (root) components. Results are ordered by ascending name. - * @param dbSession - * @param organizationUuid uuid of the organization - * @param textQuery optional text query to match component name or key - * @param qualifiers filter on qualifiers. Must not be null nor empty - * @param rowBounds pagination - */ - public List<ComponentDto> selectProvisioned(DbSession dbSession, String organizationUuid, @Nullable String textQuery, Set<String> qualifiers, RowBounds rowBounds) { - checkArgument(!qualifiers.isEmpty(), "qualifiers must not be empty"); - return mapper(dbSession).selectProvisioned(organizationUuid, buildUpperLikeSql(textQuery), qualifiers, rowBounds); - } - - /** - * Count number of provisioned (root) components. - * @param dbSession - * @param organizationUuid uuid of the organization - * @param textQuery optional text query to match component name or key - * @param qualifiers filter on qualifiers. Must not be null nor empty - */ - public int countProvisioned(DbSession dbSession, String organizationUuid, @Nullable String textQuery, Set<String> qualifiers) { - checkArgument(!qualifiers.isEmpty(), "qualifiers must not be empty"); - return mapper(dbSession).countProvisioned(organizationUuid, buildUpperLikeSql(textQuery), qualifiers); - } - - @CheckForNull - private static String buildUpperLikeSql(@Nullable String textQuery) { - if (isBlank(textQuery)) { - return null; - } - return buildLikeValue(textQuery.toUpperCase(Locale.ENGLISH), BEFORE_AND_AFTER); - } - - public List<ComponentDto> selectGhostProjects(DbSession session, String organizationUuid, @Nullable String query, int offset, int limit) { - return mapper(session).selectGhostProjects(organizationUuid, buildUpperLikeSql(query), new RowBounds(offset, limit)); - } - - public long countGhostProjects(DbSession session, String organizationUuid, @Nullable String query) { - return mapper(session).countGhostProjects(organizationUuid, buildUpperLikeSql(query)); - } - - /** - * Selects all components that are relevant for indexing. The result is not returned (since it is usually too big), but handed over to the <code>handler</code> - * @param session the database session - * @param projectUuid the project uuid, which is selected with all of its children - * @param handler the action to be applied to every result - */ - public void selectForIndexing(DbSession session, @Nullable String projectUuid, ResultHandler handler) { - requireNonNull(handler); - mapper(session).selectForIndexing(projectUuid, handler); - } - - /** - * Retrieves all components with a specific root project Uuid, no other filtering is done by this method. - * - * Used by Views plugin - */ - public List<ComponentDto> selectByProjectUuid(String projectUuid, DbSession dbSession) { - return mapper(dbSession).selectByProjectUuid(projectUuid); - } - - /** - * Retrieve enabled components keys with given qualifiers - * - * Used by Views plugin - */ - public Set<ComponentDto> selectComponentsByQualifiers(DbSession dbSession, Set<String> qualifiers) { - checkArgument(!qualifiers.isEmpty(), "Qualifiers cannot be empty"); - return new HashSet<>(mapper(dbSession).selectComponentsByQualifiers(qualifiers)); - } - - public List<ComponentDto> selectProjectsByNameQuery(DbSession dbSession, @Nullable String nameQuery, boolean includeModules) { - String nameQueryForSql = nameQuery == null ? null : buildLikeValue(nameQuery, BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); - return mapper(dbSession).selectProjectsByNameQuery(nameQueryForSql, includeModules); - } - - public void insert(DbSession session, ComponentDto item) { - mapper(session).insert(item); - } - - public void insert(DbSession session, Collection<ComponentDto> items) { - for (ComponentDto item : items) { - insert(session, item); - } - } - - public void insert(DbSession session, ComponentDto item, ComponentDto... others) { - insert(session, Lists.asList(item, others)); - } - - public void update(DbSession session, ComponentUpdateDto component) { - mapper(session).update(component); - } - - public void updateBEnabledToFalse(DbSession session, Collection<String> uuids) { - executeLargeUpdates(uuids, mapper(session)::updateBEnabledToFalse); - } - - public void applyBChangesForRootComponentUuid(DbSession session, String projectUuid) { - mapper(session).applyBChangesForRootComponentUuid(projectUuid); - } - - public void resetBChangedForRootComponentUuid(DbSession session, String projectUuid) { - mapper(session).resetBChangedForRootComponentUuid(projectUuid); - } - - public void delete(DbSession session, long componentId) { - mapper(session).delete(componentId); - } - - private static ComponentMapper mapper(DbSession session) { - return session.getMapper(ComponentMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentDto.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentDto.java deleted file mode 100644 index 959d0a38381..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentDto.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import java.util.Date; -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.sonar.api.component.Component; -import org.sonar.api.resources.Scopes; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.db.component.ComponentValidator.checkComponentKey; -import static org.sonar.db.component.ComponentValidator.checkComponentName; - -public class ComponentDto implements Component { - - public static final String UUID_PATH_SEPARATOR = "."; - public static final String UUID_PATH_OF_ROOT = UUID_PATH_SEPARATOR; - private static final Splitter UUID_PATH_SPLITTER = Splitter.on(UUID_PATH_SEPARATOR).omitEmptyStrings(); - - /** - * ID generated by database. Do not use. - */ - private Long id; - - /** - * The UUID of the organization the component belongs to. Can't be null in DB. - */ - private String organizationUuid; - - /** - * Non-empty and unique functional key - */ - private String kee; - - /** - * Not empty . Max size is 50 (note that effective UUID values are 40 characters with - * the current algorithm in use). Obviously it is unique. - * It is generated by Compute Engine. - */ - private String uuid; - - /** - * Not empty path of ancestor UUIDS, excluding itself. Value is suffixed by a dot in - * order to support LIKE conditions when requesting descendants of a component - * and to avoid Oracle NULL on root components. - * Example: - * - on root module: UUID="1" UUID_PATH="." - * - on module: UUID="2" UUID_PATH=".1." - * - on directory: UUID="3" UUID_PATH=".1.2." - * - on file: UUID="4" UUID_PATH=".1.2.3." - * - on view: UUID="5" UUID_PATH="." - * - on sub-view: UUID="6" UUID_PATH=".5." - * - * @since 6.0 - */ - private String uuidPath; - - /** - * Non-null UUID of root component. Equals UUID column on root components - * Example: - * - on root module: UUID="1" PROJECT_UUID="1" - * - on module: UUID="2" PROJECT_UUID="1" - * - on directory: UUID="3" PROJECT_UUID="1" - * - on file: UUID="4" PROJECT_UUID="1" - * - on view: UUID="5" PROJECT_UUID="5" - * - on sub-view: UUID="6" PROJECT_UUID="5" - */ - private String projectUuid; - - /** - * Badly named, it is not the root ! - * - on root module: UUID="1" ROOT_UUID="1" - * - on modules, whatever depth, value is the root module: UUID="2" ROOT_UUID="1" - * - on directory, value is the closest module: UUID="3" ROOT_UUID="2" - * - on file, value is the closest module: UUID="4" ROOT_UUID="2" - * - on view: UUID="5" ROOT_UUID="5" - * - on sub-view: UUID="6" ROOT_UUID="5" - * @since 6.0 - */ - private String rootUuid; - - private String moduleUuid; - private String moduleUuidPath; - private String copyComponentUuid; - private String developerUuid; - private String scope; - private String qualifier; - private String path; - private String deprecatedKey; - private String name; - private String longName; - private String language; - private String description; - private boolean enabled = true; - - private Date createdAt; - private Long authorizationUpdatedAt; - - public Long getId() { - return id; - } - - public ComponentDto setId(Long id) { - this.id = id; - return this; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - public ComponentDto setOrganizationUuid(String organizationUuid) { - this.organizationUuid = organizationUuid; - return this; - } - - public String uuid() { - return uuid; - } - - public ComponentDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - public String getUuidPath() { - return uuidPath; - } - - /** - * List of ancestor UUIDs, ordered by depth in tree. - */ - List<String> getUuidPathAsList() { - return UUID_PATH_SPLITTER.splitToList(uuidPath); - } - - public ComponentDto setUuidPath(String s) { - this.uuidPath = s; - return this; - } - - @Override - public String key() { - return kee; - } - - public String scope() { - return scope; - } - - public ComponentDto setScope(String scope) { - this.scope = scope; - return this; - } - - @Override - public String qualifier() { - return qualifier; - } - - public ComponentDto setQualifier(String qualifier) { - this.qualifier = qualifier; - return this; - } - - @CheckForNull - public String deprecatedKey() { - return deprecatedKey; - } - - public ComponentDto setDeprecatedKey(@Nullable String deprecatedKey) { - this.deprecatedKey = deprecatedKey; - return this; - } - - /** - * Return the root project uuid. On a root project, return itself - */ - public String projectUuid() { - return projectUuid; - } - - public ComponentDto setProjectUuid(String projectUuid) { - this.projectUuid = projectUuid; - return this; - } - - public boolean isRoot() { - return UUID_PATH_OF_ROOT.equals(uuidPath); - } - - /** - * Return the direct module of a component. Will be null on projects - */ - @CheckForNull - public String moduleUuid() { - return moduleUuid; - } - - public ComponentDto setModuleUuid(@Nullable String moduleUuid) { - this.moduleUuid = moduleUuid; - return this; - } - - /** - * Return the path from the project to the last modules - */ - public String moduleUuidPath() { - return moduleUuidPath; - } - - public ComponentDto setModuleUuidPath(String moduleUuidPath) { - this.moduleUuidPath = moduleUuidPath; - return this; - } - - @CheckForNull - @Override - public String path() { - return path; - } - - public ComponentDto setPath(@Nullable String path) { - this.path = path; - return this; - } - - @Override - public String name() { - return name; - } - - public ComponentDto setName(String name) { - this.name = checkComponentName(name); - return this; - } - - @Override - public String longName() { - return longName; - } - - public ComponentDto setLongName(String longName) { - this.longName = longName; - return this; - } - - @CheckForNull - public String language() { - return language; - } - - public ComponentDto setLanguage(@Nullable String language) { - this.language = language; - return this; - } - - @CheckForNull - public String description() { - return description; - } - - public ComponentDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - public String getRootUuid() { - return rootUuid; - } - - public ComponentDto setRootUuid(String rootUuid) { - this.rootUuid = rootUuid; - return this; - } - - public boolean isEnabled() { - return enabled; - } - - public ComponentDto setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - - @CheckForNull - public String getCopyResourceUuid() { - return copyComponentUuid; - } - - public ComponentDto setCopyComponentUuid(@Nullable String copyComponentUuid) { - this.copyComponentUuid = copyComponentUuid; - return this; - } - - @CheckForNull - public String getDeveloperUuid() { - return developerUuid; - } - - public ComponentDto setDeveloperUuid(@Nullable String developerUuid) { - this.developerUuid = developerUuid; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public ComponentDto setCreatedAt(Date datetime) { - this.createdAt = datetime; - return this; - } - - /** - * Only available on projects - */ - @CheckForNull - public Long getAuthorizationUpdatedAt() { - return authorizationUpdatedAt; - } - - public ComponentDto setAuthorizationUpdatedAt(@Nullable Long authorizationUpdatedAt) { - this.authorizationUpdatedAt = authorizationUpdatedAt; - return this; - } - - public String getKey() { - return key(); - } - - public ComponentDto setKey(String key) { - this.kee = checkComponentKey(key); - return this; - } - - public boolean isRootProject() { - return moduleUuid == null && Scopes.PROJECT.equals(scope); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ComponentDto that = (ComponentDto) o; - return uuid != null ? uuid.equals(that.uuid) : (that.uuid == null); - - } - - @Override - public int hashCode() { - return uuid != null ? uuid.hashCode() : 0; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("id", id) - .append("uuid", uuid) - .append("uuidPath", uuidPath) - .append("kee", kee) - .append("scope", scope) - .append("qualifier", qualifier) - .append("projectUuid", projectUuid) - .append("moduleUuid", moduleUuid) - .append("moduleUuidPath", moduleUuidPath) - .append("rootUuid", rootUuid) - .append("copyComponentUuid", copyComponentUuid) - .append("developerUuid", developerUuid) - .append("path", path) - .append("deprecatedKey", deprecatedKey) - .append("name", name) - .append("longName", longName) - .append("language", language) - .append("enabled", enabled) - .append("authorizationUpdatedAt", authorizationUpdatedAt) - .toString(); - } - - public static String formatUuidPathFromParent(ComponentDto parent) { - checkArgument(!Strings.isNullOrEmpty(parent.getUuidPath())); - checkArgument(!Strings.isNullOrEmpty(parent.uuid())); - return parent.getUuidPath() + parent.uuid() + UUID_PATH_SEPARATOR; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentDtoWithSnapshotId.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentDtoWithSnapshotId.java deleted file mode 100644 index 64517022943..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentDtoWithSnapshotId.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -public class ComponentDtoWithSnapshotId extends ComponentDto { - private Long snapshotId; - - public Long getSnapshotId() { - return snapshotId; - } - - public ComponentDtoWithSnapshotId setSnapshotId(Long snapshotId) { - this.snapshotId = snapshotId; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterDao.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterDao.java deleted file mode 100644 index 5ca05d074cd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterDao.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import org.apache.commons.lang.StringUtils; -import org.apache.ibatis.session.SqlSession; -import org.sonar.api.resources.Qualifiers; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.core.component.ComponentKeys.checkModuleKey; -import static org.sonar.core.component.ComponentKeys.isValidModuleKey; - -/** - * Class used to rename the key of a project and its resources. - * - * @since 3.2 - */ -public class ComponentKeyUpdaterDao implements Dao { - private static final Set<String> PROJECT_OR_MODULE_QUALIFIERS = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.MODULE); - - private MyBatis mybatis; - - public ComponentKeyUpdaterDao(MyBatis mybatis) { - this.mybatis = mybatis; - } - - public void updateKey(String projectUuid, String newKey) { - DbSession session = mybatis.openSession(true); - ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class); - try { - if (mapper.countResourceByKey(newKey) > 0) { - throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists."); - } - - // must SELECT first everything - ResourceDto project = mapper.selectProject(projectUuid); - String projectOldKey = project.getKey(); - List<ResourceDto> resources = mapper.selectProjectResources(projectUuid); - resources.add(project); - - // and then proceed with the batch UPDATE at once - runBatchUpdateForAllResources(resources, projectOldKey, newKey, mapper); - - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public Map<String, String> checkModuleKeysBeforeRenaming(String projectUuid, String stringToReplace, String replacementString) { - SqlSession session = mybatis.openSession(false); - ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class); - Map<String, String> result = Maps.newHashMap(); - try { - Set<ResourceDto> modules = collectAllModules(projectUuid, stringToReplace, mapper); - for (ResourceDto module : modules) { - String newKey = computeNewKey(module.getKey(), stringToReplace, replacementString); - if (mapper.countResourceByKey(newKey) > 0) { - result.put(module.getKey(), "#duplicate_key#"); - } else { - result.put(module.getKey(), newKey); - } - } - } finally { - MyBatis.closeQuietly(session); - } - return result; - } - - public static void checkIsProjectOrModule(ComponentDto component) { - checkArgument(PROJECT_OR_MODULE_QUALIFIERS.contains(component.qualifier()), "Component updated must be a module or a key"); - } - - /** - * - * @return a map with currentKey/newKey is a bulk update was executed - */ - public Map<String, String> simulateBulkUpdateKey(DbSession dbSession, String projectUuid, String stringToReplace, String replacementString) { - return collectAllModules(projectUuid, stringToReplace, mapper(dbSession)) - .stream() - .collect(Collectors.toMap( - ResourceDto::getKey, - component -> { - String newKey = computeNewKey(component.getKey(), stringToReplace, replacementString); - checkModuleKey(newKey); - return newKey; - })); - } - - /** - * @return a map with the component key as key, and boolean as true if key already exists in db - */ - public Map<String, Boolean> checkComponentKeys(DbSession dbSession, List<String> newComponentKeys) { - return newComponentKeys.stream().collect(Collectors.toMap(Function.identity(), key -> mapper(dbSession).countResourceByKey(key) > 0)); - } - - public static String computeNewKey(String key, String stringToReplace, String replacementString) { - return key.replace(stringToReplace, replacementString); - } - - public void bulkUpdateKey(DbSession session, String projectUuid, String stringToReplace, String replacementString) { - ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class); - // must SELECT first everything - Set<ResourceDto> modules = collectAllModules(projectUuid, stringToReplace, mapper); - checkNewNameOfAllModules(modules, stringToReplace, replacementString, mapper); - Map<ResourceDto, List<ResourceDto>> allResourcesByModuleMap = Maps.newHashMap(); - for (ResourceDto module : modules) { - allResourcesByModuleMap.put(module, mapper.selectProjectResources(module.getUuid())); - } - - // and then proceed with the batch UPDATE at once - for (ResourceDto module : modules) { - String oldModuleKey = module.getKey(); - String newModuleKey = computeNewKey(module.getKey(), stringToReplace, replacementString); - Collection<ResourceDto> resources = Lists.newArrayList(module); - resources.addAll(allResourcesByModuleMap.get(module)); - runBatchUpdateForAllResources(resources, oldModuleKey, newModuleKey, mapper); - } - } - - private static void runBatchUpdateForAllResources(Collection<ResourceDto> resources, String oldKey, String newKey, ComponentKeyUpdaterMapper mapper) { - for (ResourceDto resource : resources) { - String oldResourceKey = resource.getKey(); - String newResourceKey = newKey + oldResourceKey.substring(oldKey.length(), oldResourceKey.length()); - resource.setKey(newResourceKey); - String oldResourceDeprecatedKey = resource.getDeprecatedKey(); - if (StringUtils.isNotBlank(oldResourceDeprecatedKey)) { - String newResourceDeprecatedKey = newKey + oldResourceDeprecatedKey.substring(oldKey.length(), oldResourceDeprecatedKey.length()); - resource.setDeprecatedKey(newResourceDeprecatedKey); - } - mapper.update(resource); - } - } - - private static Set<ResourceDto> collectAllModules(String projectUuid, String stringToReplace, ComponentKeyUpdaterMapper mapper) { - ResourceDto project = mapper.selectProject(projectUuid); - Set<ResourceDto> modules = Sets.newHashSet(); - if (project.getKey().contains(stringToReplace)) { - modules.add(project); - } - for (ResourceDto submodule : mapper.selectDescendantProjects(projectUuid)) { - modules.addAll(collectAllModules(submodule.getUuid(), stringToReplace, mapper)); - } - return modules; - } - - private static void checkNewNameOfAllModules(Set<ResourceDto> modules, String stringToReplace, String replacementString, ComponentKeyUpdaterMapper mapper) { - for (ResourceDto module : modules) { - String newKey = computeNewKey(module.getKey(), stringToReplace, replacementString); - checkArgument(isValidModuleKey(newKey), "Malformed key for '%s'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.", newKey); - if (mapper.countResourceByKey(newKey) > 0) { - throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists."); - } - } - } - - private static ComponentKeyUpdaterMapper mapper(DbSession dbSession) { - return dbSession.getMapper(ComponentKeyUpdaterMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterMapper.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterMapper.java deleted file mode 100644 index 5f042d12070..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentKeyUpdaterMapper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -/** - * @since 3.2 - */ -public interface ComponentKeyUpdaterMapper { - - int countResourceByKey(String key); - - ResourceDto selectProject(@Param("uuid") String uuid); - - List<ResourceDto> selectProjectResources(@Param("rootUuid") String rootUuid); - - List<ResourceDto> selectDescendantProjects(@Param("rootUuid") String rootUuid); - - void update(ResourceDto resource); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDao.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDao.java deleted file mode 100644 index dbc50a39584..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDao.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static java.util.Collections.emptyList; - -public class ComponentLinkDao implements Dao { - - public List<ComponentLinkDto> selectByComponentUuid(DbSession session, String componentUuid) { - return session.getMapper(ComponentLinkMapper.class).selectByComponentUuid(componentUuid); - } - - public List<ComponentLinkDto> selectByComponentUuids(DbSession dbSession, List<String> componentUuids) { - return componentUuids.isEmpty() ? emptyList() : mapper(dbSession).selectByComponentUuids(componentUuids); - } - - @CheckForNull - public ComponentLinkDto selectById(DbSession session, long id) { - return session.getMapper(ComponentLinkMapper.class).selectById(id); - } - - public ComponentLinkDto insert(DbSession session, ComponentLinkDto dto) { - session.getMapper(ComponentLinkMapper.class).insert(dto); - return dto; - } - - public void update(DbSession session, ComponentLinkDto dto) { - session.getMapper(ComponentLinkMapper.class).update(dto); - } - - public void delete(DbSession session, long id) { - session.getMapper(ComponentLinkMapper.class).delete(id); - } - - private static ComponentLinkMapper mapper(DbSession dbSession) { - return dbSession.getMapper(ComponentLinkMapper.class); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDto.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDto.java deleted file mode 100644 index 7ef034ab05d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkDto.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.collect.ImmutableList; -import java.util.List; - -/** - * Component links should be merge in a 'links' column (using protobuf for instance) of the projects table. - * But to do this we'll have to wait for the measure filters page (where links are displayed) to be rewritten in JS/WS (because it's in Rails for the moment). - */ -public class ComponentLinkDto { - - public static final String TYPE_HOME_PAGE = "homepage"; - public static final String TYPE_CI = "ci"; - public static final String TYPE_ISSUE_TRACKER = "issue"; - public static final String TYPE_SOURCES = "scm"; - public static final String TYPE_SOURCES_DEV = "scm_dev"; - - public static final List<String> PROVIDED_TYPES = ImmutableList.of(TYPE_HOME_PAGE, TYPE_CI, TYPE_ISSUE_TRACKER, TYPE_SOURCES, TYPE_SOURCES_DEV); - - private Long id; - private String componentUuid; - private String type; - private String name; - private String href; - - public String getName() { - return name; - } - - public ComponentLinkDto setName(String name) { - this.name = name; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public ComponentLinkDto setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - public String getHref() { - return href; - } - - public ComponentLinkDto setHref(String href) { - this.href = href; - return this; - } - - public Long getId() { - return id; - } - - public String getIdAsString() { - return String.valueOf(id); - } - - public ComponentLinkDto setId(Long id) { - this.id = id; - return this; - } - - public String getType() { - return type; - } - - public ComponentLinkDto setType(String type) { - this.type = type; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkMapper.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkMapper.java deleted file mode 100644 index f3b2653a660..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentLinkMapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface ComponentLinkMapper { - - List<ComponentLinkDto> selectByComponentUuid(String componentUuid); - - List<ComponentLinkDto> selectByComponentUuids(@Param("componentUuids") List<String> componentUuids); - - ComponentLinkDto selectById(@Param("id") long id); - - void insert(ComponentLinkDto dto); - - void update(ComponentLinkDto dto); - - void delete(long id); -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentMapper.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentMapper.java deleted file mode 100644 index 1dbcc9bea8e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentMapper.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; - -public interface ComponentMapper { - - @CheckForNull - ComponentDto selectByKey(String key); - - @CheckForNull - ComponentDto selectById(long id); - - @CheckForNull - ComponentDto selectByUuid(String uuid); - - /** - * Return sub project of component keys - */ - List<ComponentDto> selectSubProjectsByComponentUuids(@Param("uuids") Collection<String> uuids); - - List<ComponentDto> selectByKeys(@Param("keys") Collection<String> keys); - - List<ComponentDto> selectByIds(@Param("ids") Collection<Long> ids); - - List<ComponentDto> selectByUuids(@Param("uuids") Collection<String> uuids); - - List<ComponentDto> selectByProjectUuid(@Param("projectUuid") String projectUuid); - - List<String> selectExistingUuids(@Param("uuids") Collection<String> uuids); - - List<ComponentDto> selectComponentsByQualifiers(@Param("qualifiers") Collection<String> qualifiers); - - /** - * Counts the number of components with the specified id belonging to the specified organization. - * - * @return 1 or 0. Either because the organization uuid is not the one of the component or because the component does - * not exist. - */ - int countComponentByOrganizationAndId(@Param("organizationUuid") String organizationUuid, @Param("componentId") long componentId); - - List<ComponentDto> selectByQuery(@Nullable @Param("organizationUuid") String organizationUuid, @Param("query") ComponentQuery query, RowBounds rowBounds); - - int countByQuery(@Nullable @Param("organizationUuid") String organizationUuid, @Param("query") ComponentQuery query); - - List<ComponentDto> selectDescendants(@Param("query") ComponentTreeQuery query, @Param("baseUuid") String baseUuid, @Param("baseUuidPath") String baseUuidPath); - - /** - * Returns all enabled projects (Scope {@link org.sonar.api.resources.Scopes#PROJECT} and qualifier - * {@link org.sonar.api.resources.Qualifiers#PROJECT}) no matter if they are ghost project, provisioned projects or - * regular ones. - */ - List<ComponentDto> selectProjects(); - - List<ComponentDto> selectAllRootsByOrganization(@Param("organizationUuid") String organizationUuid); - - /** - * Return all descendant modules (including itself) from a given component uuid and scope - */ - List<ComponentDto> selectDescendantModules(@Param("moduleUuid") String moduleUuid, @Param(value = "scope") String scope, - @Param(value = "excludeDisabled") boolean excludeDisabled); - - /** - * Return all files from a given project uuid and scope - */ - List<FilePathWithHashDto> selectEnabledFilesFromProject(@Param("projectUuid") String projectUuid); - - /** - * Return all descendant files from a given module uuid and scope - */ - List<FilePathWithHashDto> selectDescendantFiles(@Param("moduleUuid") String moduleUuid, @Param(value = "scope") String scope, - @Param(value = "excludeDisabled") boolean excludeDisabled); - - /** - * Return uuids and project uuids from list of qualifiers - * <p/> - * It's using a join on snapshots in order to use he indexed columns snapshots.qualifier - */ - List<UuidWithProjectUuidDto> selectUuidsForQualifiers(@Param("qualifiers") String... qualifiers); - - /** - * Return components of a given scope of a project - * - * @param scope scope of components to return. If null, all components are returned - */ - List<ComponentDto> selectComponentsFromProjectKeyAndScope(@Param("projectKey") String projectKey, @Nullable @Param("scope") String scope, - @Param(value = "excludeDisabled") boolean excludeDisabled); - - /** - * Return technical projects from a view or a sub-view - */ - List<String> selectProjectsFromView(@Param("viewUuidLikeQuery") String viewUuidLikeQuery, @Param("projectViewUuid") String projectViewUuid); - - List<ComponentDto> selectProvisioned(@Param("organizationUuid") String organizationUuid, @Nullable @Param("keyOrNameLike") String keyOrNameLike, - @Param("qualifiers") Set<String> qualifiers, RowBounds rowBounds); - - int countProvisioned(@Param("organizationUuid") String organizationUuid, @Nullable @Param("keyOrNameLike") String keyOrNameLike, @Param("qualifiers") Set<String> qualifiers); - - List<ComponentDto> selectGhostProjects(@Param("organizationUuid") String organizationUuid, @Nullable @Param("query") String query, RowBounds rowBounds); - - long countGhostProjects(@Param("organizationUuid") String organizationUuid, @Nullable @Param("query") String query); - - List<ComponentDto> selectComponentsHavingSameKeyOrderedById(String key); - - List<ComponentDto> selectProjectsByNameQuery(@Param("nameQuery") @Nullable String nameQuery, @Param("includeModules") boolean includeModules); - - void selectForIndexing(@Param("projectUuid") @Nullable String projectUuid, ResultHandler handler); - - void insert(ComponentDto componentDto); - - void update(ComponentUpdateDto component); - - void updateBEnabledToFalse(@Param("uuids") List<String> uuids); - - void applyBChangesForRootComponentUuid(@Param("projectUuid") String projectUuid); - - void resetBChangedForRootComponentUuid(@Param("projectUuid") String projectUuid); - - void delete(long componentId); -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentQuery.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentQuery.java deleted file mode 100644 index 17764ae0834..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentQuery.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Locale; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.WildcardPosition; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.db.DatabaseUtils.buildLikeValue; - -public class ComponentQuery { - private final String nameOrKeyQuery; - private final String[] qualifiers; - private final String language; - private final Set<Long> componentIds; - - /** - * Used by Dev Cockpit 1.9. - * Could be removed when Developer Cockpit doesn't use it anymore. - * - * @deprecated since 5.4, use {@link Builder} instead - */ - @Deprecated - public ComponentQuery(@Nullable String nameOrKeyQuery, String... qualifiers) { - this.nameOrKeyQuery = nameOrKeyQuery; - this.qualifiers = Builder.validateQualifiers(qualifiers); - this.language = null; - this.componentIds = null; - } - - private ComponentQuery(Builder builder) { - this.nameOrKeyQuery = builder.nameOrKeyQuery; - this.qualifiers = builder.qualifiers; - this.language = builder.language; - this.componentIds = builder.componentIds; - } - - public String[] getQualifiers() { - return qualifiers; - } - - @CheckForNull - public String getNameOrKeyQuery() { - return nameOrKeyQuery; - } - - /** - * Used by MyBatis mapper - */ - @CheckForNull - public String getNameOrKeyUpperLikeQuery() { - return buildLikeValue(nameOrKeyQuery, WildcardPosition.BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); - } - - @CheckForNull - public String getLanguage() { - return language; - } - - @CheckForNull - public Set<Long> getComponentIds() { - return componentIds; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String nameOrKeyQuery; - private String[] qualifiers; - private String language; - private Set<Long> componentIds; - - public Builder setNameOrKeyQuery(@Nullable String nameOrKeyQuery) { - this.nameOrKeyQuery = nameOrKeyQuery; - return this; - } - - public Builder setQualifiers(String... qualifiers) { - this.qualifiers = qualifiers; - return this; - } - - public Builder setLanguage(@Nullable String language) { - this.language = language; - return this; - } - - public Builder setComponentIds(@Nullable Set<Long> componentIds) { - this.componentIds = componentIds; - return this; - } - - protected static String[] validateQualifiers(@Nullable String... qualifiers) { - checkArgument(qualifiers != null && qualifiers.length > 0, "At least one qualifier must be provided"); - return qualifiers; - } - - public ComponentQuery build() { - validateQualifiers(this.qualifiers); - return new ComponentQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentTreeQuery.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentTreeQuery.java deleted file mode 100644 index 69d02d9eb33..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentTreeQuery.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Locale; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.WildcardPosition; - -import static com.google.common.collect.Lists.newArrayList; -import static java.util.Objects.requireNonNull; -import static org.sonar.db.DatabaseUtils.buildLikeValue; -import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; - -public class ComponentTreeQuery { - - public enum Strategy { - CHILDREN, LEAVES - } - - @CheckForNull - private final String nameOrKeyQuery; - // SONAR-7681 a public implementation of List must be used in MyBatis - potential concurrency exceptions otherwise - @CheckForNull - private final ArrayList<String> qualifiers; - private final String baseUuid; - private final Strategy strategy; - - private ComponentTreeQuery(Builder builder) { - this.nameOrKeyQuery = builder.nameOrKeyQuery; - this.qualifiers = builder.qualifiers == null ? null : newArrayList(builder.qualifiers); - this.baseUuid = builder.baseUuid; - this.strategy = requireNonNull(builder.strategy); - } - - @CheckForNull - public Collection<String> getQualifiers() { - return qualifiers; - } - - @CheckForNull - public String getNameOrKeyQuery() { - return nameOrKeyQuery; - } - - /** - * Used by MyBatis mapper - */ - @CheckForNull - public String getNameOrKeyUpperLikeQuery() { - return nameOrKeyQuery == null ? null : buildLikeValue(nameOrKeyQuery, BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); - } - - public String getBaseUuid() { - return baseUuid; - } - - public Strategy getStrategy() { - return strategy; - } - - public String getUuidPath(ComponentDto component) { - switch (strategy) { - case CHILDREN: - return component.getUuidPath() + component.uuid() + "."; - case LEAVES: - return buildLikeValue(component.getUuidPath() + component.uuid() + ".", WildcardPosition.AFTER); - default: - throw new IllegalArgumentException("Unknown strategy : " + strategy); - } - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - @CheckForNull - private String nameOrKeyQuery; - @CheckForNull - private Collection<String> qualifiers; - private String baseUuid; - private Strategy strategy; - - private Builder() { - // private constructor - } - - public ComponentTreeQuery build() { - requireNonNull(baseUuid); - return new ComponentTreeQuery(this); - } - - public Builder setNameOrKeyQuery(@Nullable String nameOrKeyQuery) { - this.nameOrKeyQuery = nameOrKeyQuery; - return this; - } - - public Builder setQualifiers(Collection<String> qualifiers) { - this.qualifiers = qualifiers; - return this; - } - - public Builder setBaseUuid(String uuid) { - this.baseUuid = uuid; - return this; - } - - public Builder setStrategy(Strategy strategy) { - this.strategy = requireNonNull(strategy); - return this; - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentUpdateDto.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentUpdateDto.java deleted file mode 100644 index e2e6aac13ca..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentUpdateDto.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class ComponentUpdateDto { - private String uuid; - - /** - * if true, the component is being updated - * See https://jira.sonarsource.com/browse/SONAR-7700 - */ - private boolean bChanged; - private String bCopyComponentUuid; - private String bDescription; - private boolean bEnabled; - private String bUuidPath; - private String bLanguage; - private String bLongName; - private String bModuleUuid; - private String bModuleUuidPath; - private String bName; - private String bPath; - private String bQualifier; - - public ComponentUpdateDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - public String getUuid() { - return uuid; - } - - public boolean isBChanged() { - return bChanged; - } - - @CheckForNull - public String getBCopyComponentUuid() { - return bCopyComponentUuid; - } - - @CheckForNull - public String getBDescription() { - return bDescription; - } - - public boolean isBEnabled() { - return bEnabled; - } - - public String getBUuidPath() { - return bUuidPath; - } - - @CheckForNull - public String getBLanguage() { - return bLanguage; - } - - @CheckForNull - public String getBLongName() { - return bLongName; - } - - @CheckForNull - public String getBModuleUuid() { - return bModuleUuid; - } - - @CheckForNull - public String getBModuleUuidPath() { - return bModuleUuidPath; - } - - @CheckForNull - public String getBName() { - return bName; - } - - @CheckForNull - public String getBPath() { - return bPath; - } - - @CheckForNull - public String getBQualifier() { - return bQualifier; - } - - public ComponentUpdateDto setBChanged(boolean b) { - this.bChanged = b; - return this; - } - - public ComponentUpdateDto setBCopyComponentUuid(@Nullable String s) { - this.bCopyComponentUuid = s; - return this; - } - - public ComponentUpdateDto setBEnabled(boolean b) { - this.bEnabled = b; - return this; - } - - public ComponentUpdateDto setBUuidPath(String bUuidPath) { - this.bUuidPath = bUuidPath; - return this; - } - - public ComponentUpdateDto setBName(@Nullable String s) { - this.bName = s; - return this; - } - - public ComponentUpdateDto setBLongName(@Nullable String s) { - this.bLongName = s; - return this; - } - - public ComponentUpdateDto setBDescription(@Nullable String s) { - this.bDescription = s; - return this; - } - - public ComponentUpdateDto setBModuleUuid(@Nullable String s) { - this.bModuleUuid = s; - return this; - } - - public ComponentUpdateDto setBModuleUuidPath(@Nullable String s) { - this.bModuleUuidPath = s; - return this; - } - - public ComponentUpdateDto setBPath(@Nullable String s) { - this.bPath = s; - return this; - } - - public ComponentUpdateDto setBLanguage(@Nullable String s) { - this.bLanguage = s; - return this; - } - - public ComponentUpdateDto setBQualifier(@Nullable String s) { - this.bQualifier = s; - return this; - } - - /** - * Copy the A-fields to B-fields. The field bChanged is kept to false. - */ - public static ComponentUpdateDto copyFrom(ComponentDto from) { - return new ComponentUpdateDto() - .setUuid(from.uuid()) - .setBChanged(false) - .setBCopyComponentUuid(from.getCopyResourceUuid()) - .setBDescription(from.description()) - .setBEnabled(from.isEnabled()) - .setBUuidPath(from.getUuidPath()) - .setBLanguage(from.language()) - .setBLongName(from.longName()) - .setBModuleUuid(from.moduleUuid()) - .setBModuleUuidPath(from.moduleUuidPath()) - .setBName(from.name()) - .setBPath(from.path()) - .setBQualifier(from.qualifier()); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ComponentValidator.java b/sonar-db/src/main/java/org/sonar/db/component/ComponentValidator.java deleted file mode 100644 index e5c66883d72..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ComponentValidator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Strings.isNullOrEmpty; -import static org.sonar.core.component.ComponentKeys.MAX_COMPONENT_KEY_LENGTH; - -public class ComponentValidator { - private static final int MAX_COMPONENT_NAME_LENGTH = 2000; - private static final int MAX_COMPONENT_QUALIFIER_LENGTH = 10; - - private ComponentValidator() { - // prevent instantiation - } - - public static String checkComponentName(String name) { - checkArgument(!isNullOrEmpty(name), "Component name can't be empty"); - checkArgument(name.length() <= MAX_COMPONENT_NAME_LENGTH, "Component name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - name.length(), MAX_COMPONENT_NAME_LENGTH, name); - return name; - } - - public static String checkComponentKey(String key) { - checkArgument(!isNullOrEmpty(key), "Component key can't be empty"); - checkArgument(key.length() <= MAX_COMPONENT_KEY_LENGTH, "Component key length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - key.length(), MAX_COMPONENT_KEY_LENGTH, key); - return key; - } - - public static String checkComponentQualifier(String qualifier) { - checkArgument(!isNullOrEmpty(qualifier), "Component qualifier can't be empty"); - checkArgument(qualifier.length() <= MAX_COMPONENT_QUALIFIER_LENGTH, "Component qualifier length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - qualifier.length(), MAX_COMPONENT_QUALIFIER_LENGTH, qualifier); - return qualifier; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/FilePathWithHashDto.java b/sonar-db/src/main/java/org/sonar/db/component/FilePathWithHashDto.java deleted file mode 100644 index 5893c3e544d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/FilePathWithHashDto.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import javax.annotation.CheckForNull; - -public class FilePathWithHashDto { - - private String uuid; - private String moduleUuid; - private String path; - private String srcHash; - private String revision; - - public String getSrcHash() { - return srcHash; - } - - public void setSrcHash(String srcHash) { - this.srcHash = srcHash; - } - - public String getModuleUuid() { - return moduleUuid; - } - - public void setModuleUuid(String moduleUuid) { - this.moduleUuid = moduleUuid; - } - - @CheckForNull - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getRevision() { - return revision; - } - - public void setRevision(String revision) { - this.revision = revision; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java deleted file mode 100644 index 70c84928174..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceDao.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import org.apache.ibatis.session.SqlSession; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; - -public class ResourceDao implements Dao { - - private final System2 system2; - - public ResourceDao(System2 system2) { - this.system2 = system2; - } - - public void updateAuthorizationDate(Long projectId, SqlSession session) { - session.getMapper(ResourceMapper.class).updateAuthorizationDate(projectId, system2.now()); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceDto.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceDto.java deleted file mode 100644 index 0fc5e2415b8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceDto.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static org.sonar.db.component.ComponentValidator.checkComponentKey; -import static org.sonar.db.component.ComponentValidator.checkComponentName; - -public class ResourceDto { - - private Long id; - private String uuid; - private String projectUuid; - private String moduleUuid; - private String moduleUuidPath; - private String key; - private String deprecatedKey; - private String name; - private String longName; - private String rootUuid; - private String path; - private String scope; - private String qualifier; - private boolean enabled = true; - private String description; - private String language; - private String copyComponentUuid; - private String developerUuid; - private Date createdAt; - private Long authorizationUpdatedAt; - - public Long getId() { - return id; - } - - public ResourceDto setId(Long id) { - this.id = id; - return this; - } - - public String getUuid() { - return uuid; - } - - public ResourceDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - public String getProjectUuid() { - return projectUuid; - } - - public ResourceDto setProjectUuid(String projectUuid) { - this.projectUuid = projectUuid; - return this; - } - - public String getModuleUuid() { - return moduleUuid; - } - - public ResourceDto setModuleUuid(String moduleUuid) { - this.moduleUuid = moduleUuid; - return this; - } - - public String getModuleUuidPath() { - return moduleUuidPath; - } - - public ResourceDto setModuleUuidPath(String moduleUuidPath) { - this.moduleUuidPath = moduleUuidPath; - return this; - } - - public String getName() { - return name; - } - - public ResourceDto setName(String name) { - this.name = checkComponentName(name); - return this; - } - - public String getKey() { - return key; - } - - public ResourceDto setKey(String s) { - this.key = checkComponentKey(s); - return this; - } - - public String getDeprecatedKey() { - return deprecatedKey; - } - - public ResourceDto setDeprecatedKey(String s) { - this.deprecatedKey = s; - return this; - } - - public String getRootUuid() { - return rootUuid; - } - - public ResourceDto setRootUuid(String rootUuid) { - this.rootUuid = rootUuid; - return this; - } - - public String getPath() { - return path; - } - - public ResourceDto setPath(String s) { - this.path = s; - return this; - } - - public String getLongName() { - return longName; - } - - public ResourceDto setLongName(String longName) { - this.longName = longName; - return this; - } - - public String getScope() { - return scope; - } - - public ResourceDto setScope(String scope) { - this.scope = scope; - return this; - } - - public String getQualifier() { - return qualifier; - } - - public ResourceDto setQualifier(String qualifier) { - this.qualifier = qualifier; - return this; - } - - public boolean isEnabled() { - return enabled; - } - - public ResourceDto setEnabled(boolean b) { - this.enabled = b; - return this; - } - - public String getDescription() { - return description; - } - - public ResourceDto setDescription(String description) { - this.description = description; - return this; - } - - public String getLanguage() { - return language; - } - - public ResourceDto setLanguage(String language) { - this.language = language; - return this; - } - - @CheckForNull - public String getCopyComponentUuid() { - return copyComponentUuid; - } - - public ResourceDto setCopyComponentUuid(@Nullable String copyComponentUuid) { - this.copyComponentUuid = copyComponentUuid; - return this; - } - - @CheckForNull - public String getDeveloperUuid() { - return developerUuid; - } - - public ResourceDto setDeveloperUuid(@Nullable String developerUuid) { - this.developerUuid = developerUuid; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public ResourceDto setCreatedAt(Date date) { - this.createdAt = date; - return this; - } - - public Long getAuthorizationUpdatedAt() { - return authorizationUpdatedAt; - } - - public ResourceDto setAuthorizationUpdatedAt(Long authorizationUpdatedAt) { - this.authorizationUpdatedAt = authorizationUpdatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceMapper.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceMapper.java deleted file mode 100644 index 06bc63393c9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceMapper.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import org.apache.ibatis.annotations.Param; - -public interface ResourceMapper { - - void updateAuthorizationDate(@Param("projectId") Long projectId, @Param("authorizationDate") Long authorizationDate); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/SnapshotDao.java b/sonar-db/src/main/java/org/sonar/db/component/SnapshotDao.java deleted file mode 100644 index 15409db9997..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/SnapshotDao.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.session.RowBounds; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.collect.FluentIterable.from; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class SnapshotDao implements Dao { - - public static boolean isLast(SnapshotDto snapshotTested, @Nullable SnapshotDto previousLastSnapshot) { - return previousLastSnapshot == null || previousLastSnapshot.getCreatedAt() < snapshotTested.getCreatedAt(); - } - - public Optional<SnapshotDto> selectByUuid(DbSession dbSession, String analysisUuid) { - List<SnapshotDto> dtos = mapper(dbSession).selectByUuids(Collections.singletonList(analysisUuid)); - if (dtos.isEmpty()) { - return Optional.empty(); - } - return Optional.of(dtos.iterator().next()); - } - - public List<SnapshotDto> selectByUuids(DbSession dbSession, Collection<String> analysisUuids) { - return executeLargeInputs(analysisUuids, mapper(dbSession)::selectByUuids); - } - - public Optional<SnapshotDto> selectLastAnalysisByComponentUuid(DbSession session, String componentUuid) { - return Optional.ofNullable(mapper(session).selectLastSnapshotByComponentUuid(componentUuid)); - } - - public Optional<SnapshotDto> selectLastAnalysisByRootComponentUuid(DbSession session, String componentUuid) { - return Optional.ofNullable(mapper(session).selectLastSnapshotByRootComponentUuid(componentUuid)); - } - - public List<SnapshotDto> selectLastAnalysesByRootComponentUuids(DbSession dbSession, Collection<String> componentUuids) { - return executeLargeInputs(componentUuids, mapper(dbSession)::selectLastSnapshotsByRootComponentUuids); - } - - public List<SnapshotDto> selectAnalysesByQuery(DbSession session, SnapshotQuery query) { - return mapper(session).selectSnapshotsByQuery(query); - } - - @CheckForNull - public SnapshotDto selectAnalysisByQuery(DbSession session, SnapshotQuery query) { - List<SnapshotDto> dtos = mapper(session).selectSnapshotsByQuery(query); - if (dtos.isEmpty()) { - return null; - } - checkState(dtos.size() == 1, "Expected one analysis to be returned, got %s", dtos.size()); - return dtos.get(0); - } - - /** - * Since this relies on tables EVENTS, this can return results only for root components (PROJECT, VIEW or DEVELOPER). - */ - public List<SnapshotDto> selectPreviousVersionSnapshots(DbSession session, String componentUuid, String lastVersion) { - return mapper(session).selectPreviousVersionSnapshots(componentUuid, lastVersion); - } - - @CheckForNull - public SnapshotDto selectOldestSnapshot(DbSession session, String componentUuid) { - List<SnapshotDto> snapshotDtos = mapper(session).selectOldestSnapshots(componentUuid, new RowBounds(0, 1)); - return snapshotDtos.isEmpty() ? null : snapshotDtos.get(0); - } - - public void switchIsLastFlagAndSetProcessedStatus(DbSession dbSession, String componentUuid, String analysisUuid) { - SnapshotMapper mapper = mapper(dbSession); - mapper.unsetIsLastFlagForComponentUuid(componentUuid); - mapper(dbSession).setIsLastFlagForAnalysisUuid(analysisUuid); - } - - public SnapshotDto insert(DbSession session, SnapshotDto item) { - mapper(session).insert(item); - return item; - } - - public void insert(DbSession session, Collection<SnapshotDto> items) { - for (SnapshotDto item : items) { - insert(session, item); - } - } - - public void insert(DbSession session, SnapshotDto item, SnapshotDto... others) { - insert(session, Lists.asList(item, others)); - } - - public void update(DbSession dbSession, SnapshotDto analysis) { - mapper(dbSession).update(analysis); - } - - /** - * Used by Governance - */ - @CheckForNull - public ViewsSnapshotDto selectSnapshotBefore(String componentUuid, long date, DbSession dbSession) { - return from(mapper(dbSession).selectSnapshotBefore(componentUuid, date)) - .first() - .orNull(); - } - - private static SnapshotMapper mapper(DbSession session) { - return session.getMapper(SnapshotMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/SnapshotDto.java b/sonar-db/src/main/java/org/sonar/db/component/SnapshotDto.java deleted file mode 100644 index e326b4da511..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/SnapshotDto.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public final class SnapshotDto { - - /** - * This status is set on the snapshot at the beginning of the batch - */ - public static final String STATUS_UNPROCESSED = "U"; - public static final String STATUS_PROCESSED = "P"; - - private Long id; - private String uuid; - private String componentUuid; - private Long createdAt; - private Long buildDate; - private String status = STATUS_UNPROCESSED; - private Integer purgeStatus; - private Boolean last; - private String version; - private String periodMode; - private String periodParam; - private Long periodDate; - - public Long getId() { - return id; - } - - public SnapshotDto setId(Long id) { - this.id = id; - return this; - } - - public SnapshotDto setUuid(String s) { - this.uuid = s; - return this; - } - - public String getUuid() { - return this.uuid; - } - - public Long getBuildDate() { - return buildDate; - } - - public SnapshotDto setBuildDate(Long buildDate) { - this.buildDate = buildDate; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public SnapshotDto setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - public String getStatus() { - return status; - } - - public SnapshotDto setStatus(String status) { - this.status = status; - return this; - } - - @CheckForNull - public Integer getPurgeStatus() { - return purgeStatus; - } - - public SnapshotDto setPurgeStatus(@Nullable Integer purgeStatus) { - this.purgeStatus = purgeStatus; - return this; - } - - public Boolean getLast() { - return last; - } - - public SnapshotDto setLast(Boolean last) { - this.last = last; - return this; - } - - /** - * Version is only available on projects and modules - */ - @CheckForNull - public String getVersion() { - return version; - } - - public SnapshotDto setVersion(@Nullable String version) { - this.version = version; - return this; - } - - public SnapshotDto setPeriodMode(@Nullable String p) { - periodMode = p; - return this; - } - - @CheckForNull - public String getPeriodMode() { - return periodMode; - } - - public SnapshotDto setPeriodParam(@Nullable String p) { - periodParam = p; - return this; - } - - @CheckForNull - public String getPeriodModeParameter() { - return periodParam; - } - - public SnapshotDto setPeriodDate(@Nullable Long date) { - periodDate = date; - return this; - } - - @CheckForNull - public Long getPeriodDate() { - return periodDate; - } - - public SnapshotDto setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - return this; - } - - /** - * @return analysis date - */ - public Long getCreatedAt() { - return createdAt; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/SnapshotMapper.java b/sonar-db/src/main/java/org/sonar/db/component/SnapshotMapper.java deleted file mode 100644 index 60f979748d5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/SnapshotMapper.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Collection; -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface SnapshotMapper { - - List<SnapshotDto> selectByUuids(@Param("uuids") List<String> uuids); - - void insert(SnapshotDto snapshot); - - @CheckForNull - SnapshotDto selectLastSnapshotByComponentUuid(@Param("componentUuid") String componentUuid); - - @CheckForNull - SnapshotDto selectLastSnapshotByRootComponentUuid(@Param("componentUuid") String componentUuid); - - List<SnapshotDto> selectLastSnapshotsByRootComponentUuids(@Param("componentUuids") Collection<String> componentIds); - - List<SnapshotDto> selectSnapshotsByQuery(@Param("query") SnapshotQuery query); - - List<SnapshotDto> selectPreviousVersionSnapshots(@Param("componentUuid") String componentUuid, @Param("lastVersion") String lastVersion); - - List<SnapshotDto> selectOldestSnapshots(@Param("componentUuid") String componentUuid, RowBounds rowBounds); - - List<ViewsSnapshotDto> selectSnapshotBefore(@Param("componentUuid") String componentUuid, @Param("date") long date); - - void unsetIsLastFlagForComponentUuid(@Param("componentUuid") String componentUuid); - - void setIsLastFlagForAnalysisUuid(@Param("analysisUuid") String analysisUuid); - - void update(SnapshotDto analysis); -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/SnapshotQuery.java b/sonar-db/src/main/java/org/sonar/db/component/SnapshotQuery.java deleted file mode 100644 index 6464c6dd120..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/SnapshotQuery.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public final class SnapshotQuery { - - public enum SORT_FIELD { - BY_DATE("created_at"); - final String fieldName; - - SORT_FIELD(String fieldName) { - this.fieldName = fieldName; - } - } - - public enum SORT_ORDER { - ASC("asc"), DESC("desc"); - final String order; - - SORT_ORDER(String order) { - this.order = order; - } - } - - private String componentUuid; - private Long createdAfter; - private Long createdBefore; - private String status; - private String version; - private Boolean isLast; - private String sortField; - private String sortOrder; - - /** - * filter to return snapshots created at or after a given date - */ - @CheckForNull - public Long getCreatedAfter() { - return createdAfter; - } - - public SnapshotQuery setCreatedAfter(@Nullable Long createdAfter) { - this.createdAfter = createdAfter; - return this; - } - - /** - * filter to return snapshots created before a given date - */ - @CheckForNull - public Long getCreatedBefore() { - return createdBefore; - } - - public SnapshotQuery setCreatedBefore(@Nullable Long createdBefore) { - this.createdBefore = createdBefore; - return this; - } - - @CheckForNull - public Boolean getIsLast() { - return isLast; - } - - public SnapshotQuery setIsLast(@Nullable Boolean isLast) { - this.isLast = isLast; - return this; - } - - @CheckForNull - public String getComponentUuid() { - return componentUuid; - } - - public SnapshotQuery setComponentUuid(@Nullable String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - @CheckForNull - public String getStatus() { - return status; - } - - public SnapshotQuery setStatus(@Nullable String status) { - this.status = status; - return this; - } - - @CheckForNull - public String getVersion() { - return version; - } - - public SnapshotQuery setVersion(@Nullable String version) { - this.version = version; - return this; - } - - public SnapshotQuery setSort(SORT_FIELD sortField, SORT_ORDER sortOrder) { - this.sortField = sortField.fieldName; - this.sortOrder = sortOrder.order; - return this; - } - - @CheckForNull - public String getSortField() { - return sortField; - } - - @CheckForNull - public String getSortOrder() { - return sortOrder; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/UuidWithProjectUuidDto.java b/sonar-db/src/main/java/org/sonar/db/component/UuidWithProjectUuidDto.java deleted file mode 100644 index ff6b6e4af39..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/UuidWithProjectUuidDto.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -public class UuidWithProjectUuidDto { - - private String uuid; - private String projectUuid; - - public String getProjectUuid() { - return projectUuid; - } - - public UuidWithProjectUuidDto setProjectUuid(String projectUuid) { - this.projectUuid = projectUuid; - return this; - } - - public String getUuid() { - return uuid; - } - - public UuidWithProjectUuidDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/ViewsSnapshotDto.java b/sonar-db/src/main/java/org/sonar/db/component/ViewsSnapshotDto.java deleted file mode 100644 index 11db59068ef..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/ViewsSnapshotDto.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -public class ViewsSnapshotDto { - private String uuid; - private Long createdAt; - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public Long getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/component/package-info.java b/sonar-db/src/main/java/org/sonar/db/component/package-info.java deleted file mode 100644 index 41329cf7154..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/component/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.component; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/debt/RequirementMigrationDto.java b/sonar-db/src/main/java/org/sonar/db/debt/RequirementMigrationDto.java deleted file mode 100644 index 091fa0fc778..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/debt/RequirementMigrationDto.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.debt; - -import java.io.Serializable; -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -/** - * Only used in {@link org.sonar.server.startup.CopyRequirementsFromCharacteristicsToRules} - */ -public class RequirementMigrationDto implements Serializable { - - private Integer id; - private Integer parentId; - private Integer rootId; - private Integer ruleId; - private String functionKey; - private Double coefficientValue; - private String coefficientUnit; - private Double offsetValue; - private String offsetUnit; - private Date createdAt; - private Date updatedAt; - private boolean enabled; - - public Integer getId() { - return id; - } - - public RequirementMigrationDto setId(Integer id) { - this.id = id; - return this; - } - - public Integer getParentId() { - return parentId; - } - - public RequirementMigrationDto setParentId(Integer i) { - this.parentId = i; - return this; - } - - public Integer getRootId() { - return rootId; - } - - public RequirementMigrationDto setRootId(Integer rootId) { - this.rootId = rootId; - return this; - } - - public Integer getRuleId() { - return ruleId; - } - - public RequirementMigrationDto setRuleId(Integer ruleId) { - this.ruleId = ruleId; - return this; - } - - public String getFunction() { - return functionKey; - } - - public RequirementMigrationDto setFunction(String function) { - this.functionKey = function; - return this; - } - - @CheckForNull - public Double getCoefficientValue() { - return coefficientValue; - } - - public RequirementMigrationDto setCoefficientValue(@Nullable Double coefficientValue) { - this.coefficientValue = coefficientValue; - return this; - } - - @CheckForNull - public String getCoefficientUnit() { - return coefficientUnit; - } - - public RequirementMigrationDto setCoefficientUnit(@Nullable String coefficientUnit) { - this.coefficientUnit = coefficientUnit; - return this; - } - - @CheckForNull - public Double getOffsetValue() { - return offsetValue; - } - - public RequirementMigrationDto setOffsetValue(@Nullable Double offset) { - this.offsetValue = offset; - return this; - } - - @CheckForNull - public String getOffsetUnit() { - return offsetUnit; - } - - public RequirementMigrationDto setOffsetUnit(@Nullable String offsetUnit) { - this.offsetUnit = offsetUnit; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public RequirementMigrationDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - @CheckForNull - public Date getUpdatedAt() { - return updatedAt; - } - - public RequirementMigrationDto setUpdatedAt(@Nullable Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public boolean isEnabled() { - return enabled; - } - - public RequirementMigrationDto setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/debt/package-info.java b/sonar-db/src/main/java/org/sonar/db/debt/package-info.java deleted file mode 100644 index 7e9c4a9cb33..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/debt/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.debt; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/AbstractDialect.java b/sonar-db/src/main/java/org/sonar/db/dialect/AbstractDialect.java deleted file mode 100644 index f442c088c21..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/AbstractDialect.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import java.util.Collections; -import java.util.List; - -/** - * @since 3.2 - */ -abstract class AbstractDialect implements Dialect { - private final String id; - private final String activeRecordDialectCode; - private final String defaultDriverClassName; - private final String trueSqlValue; - private final String falseSqlValue; - private final String validationQuery; - - protected AbstractDialect(String id, String activeRecordDialectCode, String defaultDriverClassName, String trueSqlValue, String falseSqlValue, - String validationQuery) { - this.id = id; - this.activeRecordDialectCode = activeRecordDialectCode; - this.defaultDriverClassName = defaultDriverClassName; - this.trueSqlValue = trueSqlValue; - this.falseSqlValue = falseSqlValue; - this.validationQuery = validationQuery; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getActiveRecordDialectCode() { - return activeRecordDialectCode; - } - - @Override - public String getDefaultDriverClassName() { - return defaultDriverClassName; - } - - @Override - public final String getTrueSqlValue() { - return trueSqlValue; - } - - @Override - public final String getFalseSqlValue() { - return falseSqlValue; - } - - @Override - public final String getValidationQuery() { - return validationQuery; - } - - @Override - public List<String> getConnectionInitStatements() { - return Collections.emptyList(); - } - - @Override - public int getScrollDefaultFetchSize() { - return 200; - } - - @Override - public int getScrollSingleRowFetchSize() { - return 1; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/Dialect.java b/sonar-db/src/main/java/org/sonar/db/dialect/Dialect.java deleted file mode 100644 index a7f02670fb9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/Dialect.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import java.util.List; - -/** - * @since 1.12 - */ -public interface Dialect { - - /** - * @return the sonar dialect Id to be matched with the sonar.jdbc.dialect property when provided - */ - String getId(); - - /** - * @return the activerecord dialect to be used - */ - String getActiveRecordDialectCode(); - - /** - * Used to autodetect a dialect for a given driver URL - * - * @param jdbcConnectionURL a jdbc driver url such as jdbc:mysql://localhost:3306/sonar - * @return true if the dialect supports surch url - */ - boolean matchesJdbcURL(String jdbcConnectionURL); - - /** - * @since 2.13 - */ - String getDefaultDriverClassName(); - - List<String> getConnectionInitStatements(); - - /** - * @since 2.14 - */ - String getTrueSqlValue(); - - /** - * @since 2.14 - */ - String getFalseSqlValue(); - - /** - * Query used to validate the jdbc connection. - * - * @since 3.2 - */ - String getValidationQuery(); - - /** - * Fetch size to be used when scrolling large result sets. - * - * @since 5.0 - */ - int getScrollDefaultFetchSize(); - - /** - * Fetch size to scroll one row at a time. It sounds strange because obviously value is 1 in most cases, - * but it's different on MySQL... - * - * @since 5.0 - */ - int getScrollSingleRowFetchSize(); - - /** - * Indicates whether DB migration can be perform on the DB vendor implementation associated with the current dialect. - * - * @return a boolean - */ - boolean supportsMigration(); -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/DialectUtils.java b/sonar-db/src/main/java/org/sonar/db/dialect/DialectUtils.java deleted file mode 100644 index ce20c6cf893..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/DialectUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterators; -import java.util.NoSuchElementException; -import javax.annotation.CheckForNull; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.utils.MessageException; - -public final class DialectUtils { - - private static final Dialect[] DIALECTS = new Dialect[] {new H2(), new MySql(), new Oracle(), new PostgreSql(), new MsSql()}; - - private DialectUtils() { - // only static stuff - } - - public static Dialect find(final String dialectId, final String jdbcConnectionUrl) { - Dialect match = StringUtils.isNotBlank(dialectId) ? findById(dialectId) : findByJdbcUrl(jdbcConnectionUrl); - if (match == null) { - throw MessageException.of("Unable to determine database dialect to use within sonar with dialect " + dialectId + " jdbc url " + jdbcConnectionUrl); - } - return match; - } - - @CheckForNull - private static Dialect findByJdbcUrl(final String jdbcConnectionUrl) { - return findDialect(dialect -> dialect != null && dialect.matchesJdbcURL(StringUtils.trimToEmpty(jdbcConnectionUrl))); - } - - @CheckForNull - private static Dialect findById(final String dialectId) { - return findDialect(dialect -> dialect != null && dialect.getId().equals(dialectId)); - } - - @CheckForNull - private static Dialect findDialect(Predicate<Dialect> predicate) { - try { - return Iterators.find(Iterators.forArray(DIALECTS), predicate); - } catch (NoSuchElementException ex) { - return null; - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/H2.java b/sonar-db/src/main/java/org/sonar/db/dialect/H2.java deleted file mode 100644 index e94cbf0a348..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/H2.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import org.apache.commons.lang.StringUtils; - -/** - * @since 1.12 - */ -public class H2 extends AbstractDialect { - - public static final String ID = "h2"; - - public H2() { - super(ID, ".h2.", "org.h2.Driver", "true", "false", "SELECT 1"); - } - - @Override - public boolean matchesJdbcURL(String jdbcConnectionURL) { - return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:h2:"); - } - - @Override - public boolean supportsMigration() { - return false; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/MsSql.java b/sonar-db/src/main/java/org/sonar/db/dialect/MsSql.java deleted file mode 100644 index 802688af9b3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/MsSql.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import org.apache.commons.lang.StringUtils; - -public class MsSql extends AbstractDialect { - - public static final String ID = "mssql"; - - public MsSql() { - super(ID, "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "1", "0", "SELECT 1"); - } - - @Override - public boolean matchesJdbcURL(String jdbcConnectionURL) { - return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:sqlserver:"); - } - - @Override - public boolean supportsMigration() { - return true; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/MySql.java b/sonar-db/src/main/java/org/sonar/db/dialect/MySql.java deleted file mode 100644 index bb16869d798..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/MySql.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import org.apache.commons.lang.StringUtils; - -/** - * @since 1.12 - */ -public class MySql extends AbstractDialect { - - public static final String ID = "mysql"; - - public MySql() { - super(ID, "mysql", "com.mysql.jdbc.Driver", "true", "false", "SELECT 1"); - } - - @Override - public boolean matchesJdbcURL(String jdbcConnectionURL) { - return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:mysql:"); - } - - @Override - public int getScrollDefaultFetchSize() { - return Integer.MIN_VALUE; - } - - @Override - public int getScrollSingleRowFetchSize() { - return Integer.MIN_VALUE; - } - - @Override - public boolean supportsMigration() { - return true; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/Oracle.java b/sonar-db/src/main/java/org/sonar/db/dialect/Oracle.java deleted file mode 100644 index ac49a24a9ad..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/Oracle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import org.apache.commons.lang.StringUtils; - -/** - * @since 1.12 - */ -public class Oracle extends AbstractDialect { - - public static final String ID = "oracle"; - private static final List<String> INIT_STATEMENTS = ImmutableList.of("ALTER SESSION SET NLS_SORT='BINARY'"); - - public Oracle() { - super(ID, "oracle", "oracle.jdbc.OracleDriver", "1", "0", "SELECT 1 FROM DUAL"); - } - - @Override - public boolean matchesJdbcURL(String jdbcConnectionURL) { - return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:oracle:"); - } - - @Override - public boolean supportsMigration() { - return true; - } - - @Override - public List<String> getConnectionInitStatements() { - return INIT_STATEMENTS; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/PostgreSql.java b/sonar-db/src/main/java/org/sonar/db/dialect/PostgreSql.java deleted file mode 100644 index bdb81f80abc..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/PostgreSql.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.dialect; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import org.apache.commons.lang.StringUtils; - -/** - * @since 1.12 - */ -public class PostgreSql extends AbstractDialect { - - public static final String ID = "postgresql"; - static final List<String> INIT_STATEMENTS = ImmutableList.of("SET standard_conforming_strings=on", "SET backslash_quote=off"); - - public PostgreSql() { - super(ID, "postgre", "org.postgresql.Driver", "true", "false", "SELECT 1"); - } - - @Override - public boolean matchesJdbcURL(String jdbcConnectionURL) { - return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:postgresql:"); - } - - @Override - public List<String> getConnectionInitStatements() { - return INIT_STATEMENTS; - } - - @Override - public boolean supportsMigration() { - return true; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/dialect/package-info.java b/sonar-db/src/main/java/org/sonar/db/dialect/package-info.java deleted file mode 100644 index 5602ddce667..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/dialect/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.dialect; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationDao.java b/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationDao.java deleted file mode 100644 index 8883f303e03..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationDao.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.duplication; - -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class DuplicationDao implements Dao { - - /** - * @param analysisUuid snapshot id of the project from the previous analysis (islast=true) - */ - public List<DuplicationUnitDto> selectCandidates(DbSession session, @Nullable String analysisUuid, String language, Collection<String> hashes) { - return executeLargeInputs( - hashes, - partition -> session.getMapper(DuplicationMapper.class).selectCandidates(analysisUuid, language, partition)); - } - - /** - * Insert rows in the table DUPLICATIONS_INDEX. - * Note that generated ids are not returned. - */ - public void insert(DbSession session, DuplicationUnitDto dto) { - session.getMapper(DuplicationMapper.class).batchInsert(dto); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationMapper.java b/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationMapper.java deleted file mode 100644 index 8edec655644..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationMapper.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.duplication; - -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; - -public interface DuplicationMapper { - - List<DuplicationUnitDto> selectCandidates( - @Nullable @Param("analysisUuid") String analysisUuid, - @Param("language") String language, - @Param("hashes") Collection<String> hashes); - - void batchInsert(DuplicationUnitDto unit); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationUnitDto.java b/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationUnitDto.java deleted file mode 100644 index 8754d3540f8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/duplication/DuplicationUnitDto.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.duplication; - -public final class DuplicationUnitDto { - - private long id; - private String analysisUuid; - private String componentUuid; - - private String hash; - private int indexInFile; - private int startLine; - private int endLine; - - // Return by join - private String componentKey; - - public long getId() { - return id; - } - - public DuplicationUnitDto setId(long id) { - this.id = id; - return this; - } - - public String getAnalysisUuid() { - return analysisUuid; - } - - public DuplicationUnitDto setAnalysisUuid(String analysisUuid) { - this.analysisUuid = analysisUuid; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public DuplicationUnitDto setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - public String getHash() { - return hash; - } - - public DuplicationUnitDto setHash(String hash) { - this.hash = hash; - return this; - } - - public int getIndexInFile() { - return indexInFile; - } - - public DuplicationUnitDto setIndexInFile(int indexInFile) { - this.indexInFile = indexInFile; - return this; - } - - public int getStartLine() { - return startLine; - } - - public DuplicationUnitDto setStartLine(int startLine) { - this.startLine = startLine; - return this; - } - - public int getEndLine() { - return endLine; - } - - public DuplicationUnitDto setEndLine(int endLine) { - this.endLine = endLine; - return this; - } - - public String getComponentKey() { - return componentKey; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/duplication/package-info.java b/sonar-db/src/main/java/org/sonar/db/duplication/package-info.java deleted file mode 100644 index a04d60231c9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/duplication/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.duplication; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/event/EventDao.java b/sonar-db/src/main/java/org/sonar/db/event/EventDao.java deleted file mode 100644 index c1414d33b01..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/event/EventDao.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import java.util.List; -import java.util.Optional; -import javax.annotation.Nullable; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class EventDao implements Dao { - - public Optional<EventDto> selectByUuid(DbSession dbSession, String uuid) { - return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid)); - } - - public List<EventDto> selectByComponentUuid(DbSession session, String componentUuid) { - return session.getMapper(EventMapper.class).selectByComponentUuid(componentUuid); - } - - public List<EventDto> selectByAnalysisUuid(DbSession dbSession, String uuid) { - return mapper(dbSession).selectByAnalysisUuid(uuid); - } - - public List<EventDto> selectByAnalysisUuids(DbSession dbSession, List<String> analyses) { - return executeLargeInputs(analyses, mapper(dbSession)::selectByAnalysisUuids); - } - - public EventDto insert(DbSession session, EventDto dto) { - session.getMapper(EventMapper.class).insert(dto); - - return dto; - } - - public void update(DbSession dbSession, String uuid, @Nullable String name, @Nullable String description) { - mapper(dbSession).update(uuid, name, description); - } - - public void delete(DbSession session, Long id) { - mapper(session).deleteById(id); - } - - public void delete(DbSession session, String uuid) { - mapper(session).deleteByUuid(uuid); - } - - private static EventMapper mapper(DbSession session) { - return session.getMapper(EventMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/event/EventDto.java b/sonar-db/src/main/java/org/sonar/db/event/EventDto.java deleted file mode 100644 index 7ca49964351..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/event/EventDto.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static org.sonar.db.event.EventValidator.checkEventCategory; -import static org.sonar.db.event.EventValidator.checkEventDescription; -import static org.sonar.db.event.EventValidator.checkEventName; - -public class EventDto { - - public static final String CATEGORY_VERSION = "Version"; - public static final String CATEGORY_ALERT = "Alert"; - public static final String CATEGORY_PROFILE = "Profile"; - - private Long id; - private String uuid; - private String analysisUuid; - private String componentUuid; - private String name; - private String description; - private String category; - private Long date; - private Long createdAt; - private String data; - - public Long getId() { - return id; - } - - public EventDto setId(Long id) { - this.id = id; - return this; - } - - public String getUuid() { - return uuid; - } - - public EventDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - public String getAnalysisUuid() { - return analysisUuid; - } - - public EventDto setAnalysisUuid(String analysisUuid) { - this.analysisUuid = analysisUuid; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public EventDto setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - @CheckForNull - public String getName() { - return name; - } - - /** - * The name of an event should not be null, but we must accept null values as the DB column is not nullable - */ - public EventDto setName(@Nullable String name) { - this.name = checkEventName(name); - return this; - } - - @CheckForNull - public String getCategory() { - return category; - } - - /** - * The category of an event should not be null, but we must accept null values as the DB column is not nullable - */ - public EventDto setCategory(@Nullable String category) { - this.category = checkEventCategory(category); - return this; - } - - public Long getCreatedAt() { - return createdAt; - } - - public EventDto setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - return this; - } - - @CheckForNull - public String getData() { - return data; - } - - public EventDto setData(@Nullable String data) { - this.data = data; - return this; - } - - public Long getDate() { - return date; - } - - public EventDto setDate(Long date) { - this.date = date; - return this; - } - - @CheckForNull - public String getDescription() { - return description; - } - - public EventDto setDescription(@Nullable String description) { - this.description = checkEventDescription(description); - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/event/EventMapper.java b/sonar-db/src/main/java/org/sonar/db/event/EventMapper.java deleted file mode 100644 index 121e86a4ae3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/event/EventMapper.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; - -public interface EventMapper { - - EventDto selectByUuid(String uuid); - - List<EventDto> selectByComponentUuid(String componentUuid); - - List<EventDto> selectByAnalysisUuid(String analysisUuid); - - List<EventDto> selectByAnalysisUuids(@Param("analysisUuids") List<String> list); - - void insert(EventDto dto); - - void update(@Param("uuid") String uuid, @Param("name") @Nullable String name, @Param("description") @Nullable String description); - - void deleteById(long id); - - void deleteByUuid(String uuid); -} diff --git a/sonar-db/src/main/java/org/sonar/db/event/EventValidator.java b/sonar-db/src/main/java/org/sonar/db/event/EventValidator.java deleted file mode 100644 index 278ca7e6e62..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/event/EventValidator.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkArgument; - -class EventValidator { - private static final int MAX_NAME_LENGTH = 400; - private static final int MAX_CATEGORY_LENGTH = 50; - private static final int MAX_DESCRIPTION_LENGTH = 4000; - - private EventValidator() { - // prevent instantiation - } - - @CheckForNull - static String checkEventName(@Nullable String name) { - if (name == null) { - return null; - } - checkArgument(name.length() <= MAX_NAME_LENGTH, "Event name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - name.length(), MAX_NAME_LENGTH, name); - return name; - } - - @CheckForNull - static String checkEventCategory(@Nullable String category) { - if (category == null) { - return null; - } - checkArgument(category.length() <= MAX_CATEGORY_LENGTH, "Event category length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - category.length(), MAX_CATEGORY_LENGTH, category); - return category; - } - - @CheckForNull - static String checkEventDescription(@Nullable String description) { - if (description == null) { - return null; - } - checkArgument(description.length() <= MAX_DESCRIPTION_LENGTH, "Event description length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - description.length(), MAX_DESCRIPTION_LENGTH, description); - return description; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/event/package-info.java b/sonar-db/src/main/java/org/sonar/db/event/package-info.java deleted file mode 100644 index 7b9f716263c..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/event/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.event; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDao.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDao.java deleted file mode 100644 index 79423e9f79d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDao.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import org.sonar.core.issue.FieldDiffs; -import org.sonar.core.util.stream.Collectors; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -import static java.util.Collections.singletonList; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class IssueChangeDao implements Dao { - - private final MyBatis mybatis; - - public IssueChangeDao(MyBatis mybatis) { - this.mybatis = mybatis; - } - - public List<FieldDiffs> selectChangelogByIssue(DbSession session, String issueKey) { - return selectByTypeAndIssueKeys(session, singletonList(issueKey), IssueChangeDto.TYPE_FIELD_CHANGE) - .stream() - .map(IssueChangeDto::toFieldDiffs) - .collect(Collectors.toList()); - } - - public List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(String componentUuid) { - DbSession session = mybatis.openSession(false); - try { - IssueChangeMapper mapper = mapper(session); - return mapper.selectChangelogOfNonClosedIssuesByComponent(componentUuid, IssueChangeDto.TYPE_FIELD_CHANGE); - - } finally { - MyBatis.closeQuietly(session); - } - } - - public List<IssueChangeDto> selectByTypeAndIssueKeys(DbSession session, Collection<String> issueKeys, String changeType) { - return executeLargeInputs(issueKeys, issueKeys1 -> mapper(session).selectByIssuesAndType(issueKeys1, changeType)); - } - - public Optional<IssueChangeDto> selectCommentByKey(DbSession session, String commentKey) { - return Optional.ofNullable(mapper(session).selectByKeyAndType(commentKey, IssueChangeDto.TYPE_COMMENT)); - } - - public void insert(DbSession session, IssueChangeDto change) { - mapper(session).insert(change); - } - - public boolean delete(DbSession session, String key) { - IssueChangeMapper mapper = mapper(session); - int count = mapper.delete(key); - session.commit(); - return count == 1; - } - - public boolean update(DbSession dbSession, IssueChangeDto change) { - int count = mapper(dbSession).update(change); - return count == 1; - } - - private static IssueChangeMapper mapper(DbSession session) { - return session.getMapper(IssueChangeMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDto.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDto.java deleted file mode 100644 index 53f2ebda604..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeDto.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import java.io.Serializable; -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.utils.System2; -import org.sonar.core.issue.DefaultIssueComment; -import org.sonar.core.issue.FieldDiffs; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * @since 3.6 - */ -public final class IssueChangeDto implements Serializable { - - public static final String TYPE_FIELD_CHANGE = "diff"; - public static final String TYPE_COMMENT = "comment"; - - private Long id; - private String kee; - private String issueKey; - private String userLogin; - private String changeType; - private String changeData; - - // technical dates - private Long createdAt; - private Long updatedAt; - - // functional date - private Long issueChangeCreationDate; - - public static IssueChangeDto of(DefaultIssueComment comment) { - IssueChangeDto dto = newDto(comment.issueKey()); - dto.setKey(comment.key()); - dto.setChangeType(IssueChangeDto.TYPE_COMMENT); - dto.setChangeData(comment.markdownText()); - dto.setUserLogin(comment.userLogin()); - dto.setIssueChangeCreationDate(comment.createdAt() == null ? null : comment.createdAt().getTime()); - return dto; - } - - public static IssueChangeDto of(String issueKey, FieldDiffs diffs) { - IssueChangeDto dto = newDto(issueKey); - dto.setChangeType(IssueChangeDto.TYPE_FIELD_CHANGE); - dto.setChangeData(diffs.toString()); - dto.setUserLogin(diffs.userLogin()); - dto.setIssueChangeCreationDate(diffs.creationDate() == null ? null : diffs.creationDate().getTime()); - return dto; - } - - private static IssueChangeDto newDto(String issueKey) { - IssueChangeDto dto = new IssueChangeDto(); - dto.setIssueKey(issueKey); - - // technical dates - do not use the context date - dto.setCreatedAt(System2.INSTANCE.now()); - dto.setUpdatedAt(System2.INSTANCE.now()); - return dto; - } - - public Long getId() { - return id; - } - - public IssueChangeDto setId(Long id) { - this.id = id; - return this; - } - - @CheckForNull - public String getKey() { - return kee; - } - - public IssueChangeDto setKey(@Nullable String key) { - this.kee = key; - return this; - } - - public String getIssueKey() { - return issueKey; - } - - public IssueChangeDto setIssueKey(String s) { - this.issueKey = s; - return this; - } - - @CheckForNull - public String getUserLogin() { - return userLogin; - } - - public IssueChangeDto setUserLogin(@Nullable String userLogin) { - this.userLogin = userLogin; - return this; - } - - public String getChangeType() { - return changeType; - } - - public IssueChangeDto setChangeType(String changeType) { - this.changeType = changeType; - return this; - } - - public String getChangeData() { - return changeData; - } - - public IssueChangeDto setChangeData(String changeData) { - this.changeData = changeData; - return this; - } - - public Long getCreatedAt() { - return createdAt; - } - - public IssueChangeDto setCreatedAt(Long createdAt) { - this.createdAt = checkNotNull(createdAt); - return this; - } - - public Long getUpdatedAt() { - return updatedAt; - } - - public IssueChangeDto setUpdatedAt(@Nullable Long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public Long getIssueChangeCreationDate() { - return issueChangeCreationDate; - } - - public IssueChangeDto setIssueChangeCreationDate(@Nullable Long issueChangeCreationDate) { - this.issueChangeCreationDate = issueChangeCreationDate; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - - public DefaultIssueComment toComment() { - return new DefaultIssueComment() - .setMarkdownText(changeData) - .setKey(kee) - .setCreatedAt(new Date(createdAt)) - .setUpdatedAt(updatedAt == null ? null : new Date(updatedAt)) - .setUserLogin(userLogin) - .setIssueKey(issueKey) - .setNew(false); - } - - public FieldDiffs toFieldDiffs() { - return FieldDiffs.parse(changeData) - .setUserLogin(userLogin) - // issueChangeCreationDate can be null as it has been introduced after createdAt - .setCreationDate(issueChangeCreationDate != null ? new Date(issueChangeCreationDate) : new Date(createdAt)) - .setIssueKey(issueKey); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeMapper.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeMapper.java deleted file mode 100644 index 1d6db5b2994..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueChangeMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface IssueChangeMapper { - - void insert(IssueChangeDto dto); - - int delete(String key); - - int update(IssueChangeDto change); - - @CheckForNull - IssueChangeDto selectByKeyAndType(@Param("key") String key, @Param("changeType") String type); - - /** - * Issue changes by chronological date of creation - */ - List<IssueChangeDto> selectByIssuesAndType(@Param("issueKeys") List<String> issueKeys, - @Param("changeType") String changeType); - - List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(@Param("componentUuid") String componentUuid, @Param("changeType") String changeType); -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueDao.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueDao.java deleted file mode 100644 index 4555aad7e3e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueDao.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static com.google.common.collect.FluentIterable.from; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class IssueDao implements Dao { - - public java.util.Optional<IssueDto> selectByKey(DbSession session, String key) { - return java.util.Optional.ofNullable(mapper(session).selectByKey(key)); - } - - public IssueDto selectOrFailByKey(DbSession session, String key) { - java.util.Optional<IssueDto> issue = selectByKey(session, key); - if (!issue.isPresent()) { - throw new RowNotFoundException(String.format("Issue with key '%s' does not exist", key)); - } - return issue.get(); - } - - /** - * Gets a list issues by their keys. The result does NOT contain {@code null} values for issues not found, so - * the size of result may be less than the number of keys. A single issue is returned - * if input keys contain multiple occurrences of a key. - * <p>Results may be in a different order as input keys (see {@link #selectByOrderedKeys(DbSession, List)}).</p> - */ - public List<IssueDto> selectByKeys(final DbSession session, List<String> keys) { - return executeLargeInputs(keys, mapper(session)::selectByKeys); - } - - /** - * Gets a list issues by their keys. The result does NOT contain {@code null} values for issues not found, so - * the size of result may be less than the number of keys. A single issue is returned - * if input keys contain multiple occurrences of a key. - * <p>Contrary to {@link #selectByKeys(DbSession, List)}, results are in the same order as input keys.</p> - */ - public List<IssueDto> selectByOrderedKeys(DbSession session, List<String> keys) { - List<IssueDto> unordered = selectByKeys(session, keys); - return from(keys).transform(new KeyToIssue(unordered)).filter(Predicates.notNull()).toList(); - } - - private static class KeyToIssue implements Function<String, IssueDto> { - private final Map<String, IssueDto> map = new HashMap<>(); - - private KeyToIssue(Collection<IssueDto> unordered) { - for (IssueDto dto : unordered) { - map.put(dto.getKey(), dto); - } - } - - @Nullable - @Override - public IssueDto apply(@Nonnull String issueKey) { - return map.get(issueKey); - } - } - - public Set<String> selectComponentUuidsOfOpenIssuesForProjectUuid(DbSession session, String projectUuid) { - return mapper(session).selectComponentUuidsOfOpenIssuesForProjectUuid(projectUuid); - } - - public void insert(DbSession session, IssueDto dto) { - mapper(session).insert(dto); - } - - public void insert(DbSession session, IssueDto dto, IssueDto... others) { - IssueMapper mapper = mapper(session); - mapper.insert(dto); - for (IssueDto other : others) { - mapper.insert(other); - } - } - - public void update(DbSession session, IssueDto dto) { - mapper(session).update(dto); - } - - private static IssueMapper mapper(DbSession session) { - return session.getMapper(IssueMapper.class); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueDto.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueDto.java deleted file mode 100644 index 8133ab289e2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueDto.java +++ /dev/null @@ -1,726 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; -import com.google.common.base.Preconditions; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.protobuf.InvalidProtocolBufferException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Date; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.resources.Project; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.RuleType; -import org.sonar.api.utils.Duration; -import org.sonar.api.utils.KeyValueFormat; -import org.sonar.core.issue.DefaultIssue; -import org.sonar.core.util.Uuids; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.protobuf.DbIssues; -import org.sonar.db.rule.RuleDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.api.utils.DateUtils.dateToLong; -import static org.sonar.api.utils.DateUtils.longToDate; - -public final class IssueDto implements Serializable { - - private static final char TAGS_SEPARATOR = ','; - private static final Joiner TAGS_JOINER = Joiner.on(TAGS_SEPARATOR).skipNulls(); - private static final Splitter TAGS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings(); - - private Long id; - private int type; - private String kee; - private String componentUuid; - private String projectUuid; - private Integer ruleId; - private String severity; - private boolean manualSeverity; - private String message; - private Integer line; - private Double gap; - private Long effort; - private String status; - private String resolution; - private String checksum; - private String assignee; - private String authorLogin; - private String issueAttributes; - private byte[] locations; - private long createdAt; - private long updatedAt; - - // functional dates stored as Long - private Long issueCreationDate; - private Long issueUpdateDate; - private Long issueCloseDate; - - /** - * Temporary date used only during scan - */ - private Long selectedAt; - - // joins - private String ruleKey; - private String ruleRepo; - private String language; - private String componentKey; - private String moduleUuid; - private String moduleUuidPath; - private String projectKey; - private String filePath; - private String tags; - - /** - * On batch side, component keys and uuid are useless - */ - public static IssueDto toDtoForComputationInsert(DefaultIssue issue, int ruleId, long now) { - return new IssueDto() - .setKee(issue.key()) - .setType(issue.type()) - .setLine(issue.line()) - .setLocations((DbIssues.Locations) issue.getLocations()) - .setMessage(issue.message()) - .setGap(issue.gap()) - .setEffort(issue.effortInMinutes()) - .setResolution(issue.resolution()) - .setStatus(issue.status()) - .setSeverity(issue.severity()) - .setManualSeverity(issue.manualSeverity()) - .setChecksum(issue.checksum()) - .setAssignee(issue.assignee()) - .setRuleId(ruleId) - .setRuleKey(issue.ruleKey().repository(), issue.ruleKey().rule()) - .setTags(issue.tags()) - .setComponentUuid(issue.componentUuid()) - .setComponentKey(issue.componentKey()) - .setModuleUuid(issue.moduleUuid()) - .setModuleUuidPath(issue.moduleUuidPath()) - .setProjectUuid(issue.projectUuid()) - .setProjectKey(issue.projectKey()) - .setIssueAttributes(KeyValueFormat.format(issue.attributes())) - .setAuthorLogin(issue.authorLogin()) - .setIssueCreationDate(issue.creationDate()) - .setIssueCloseDate(issue.closeDate()) - .setIssueUpdateDate(issue.updateDate()) - .setSelectedAt(issue.selectedAt()) - - // technical dates - .setCreatedAt(now) - .setUpdatedAt(now); - } - - /** - * On server side, we need component keys and uuid - */ - public static IssueDto toDtoForServerInsert(DefaultIssue issue, ComponentDto component, ComponentDto project, int ruleId, long now) { - return toDtoForComputationInsert(issue, ruleId, now) - .setComponent(component) - .setProject(project); - } - - public static IssueDto toDtoForUpdate(DefaultIssue issue, long now) { - // Invariant fields, like key and rule, can't be updated - return new IssueDto() - .setKee(issue.key()) - .setType(issue.type()) - .setLine(issue.line()) - .setLocations((DbIssues.Locations) issue.getLocations()) - .setMessage(issue.message()) - .setGap(issue.gap()) - .setEffort(issue.effortInMinutes()) - .setResolution(issue.resolution()) - .setStatus(issue.status()) - .setSeverity(issue.severity()) - .setChecksum(issue.checksum()) - .setManualSeverity(issue.manualSeverity()) - .setAssignee(issue.assignee()) - .setIssueAttributes(KeyValueFormat.format(issue.attributes())) - .setAuthorLogin(issue.authorLogin()) - .setRuleKey(issue.ruleKey().repository(), issue.ruleKey().rule()) - .setTags(issue.tags()) - .setComponentUuid(issue.componentUuid()) - .setComponentKey(issue.componentKey()) - .setModuleUuid(issue.moduleUuid()) - .setModuleUuidPath(issue.moduleUuidPath()) - .setProjectUuid(issue.projectUuid()) - .setProjectKey(issue.projectKey()) - .setIssueCreationDate(issue.creationDate()) - .setIssueCloseDate(issue.closeDate()) - .setIssueUpdateDate(issue.updateDate()) - .setSelectedAt(issue.selectedAt()) - - // technical date - .setUpdatedAt(now); - } - - public static IssueDto createFor(Project project, RuleDto rule) { - return new IssueDto() - .setProjectUuid(project.getUuid()) - .setRuleId(rule.getId()) - .setKee(Uuids.create()); - } - - public String getKey() { - return getKee(); - } - - public Long getId() { - return id; - } - - public IssueDto setId(@Nullable Long id) { - this.id = id; - return this; - } - - public String getKee() { - return kee; - } - - public IssueDto setKee(String s) { - this.kee = s; - return this; - } - - public IssueDto setComponent(ComponentDto component) { - this.componentKey = component.getKey(); - this.componentUuid = component.uuid(); - this.moduleUuid = component.moduleUuid(); - this.moduleUuidPath = component.moduleUuidPath(); - this.filePath = component.path(); - return this; - } - - public IssueDto setProject(ComponentDto project) { - this.projectKey = project.getKey(); - this.projectUuid = project.uuid(); - return this; - } - - public Integer getRuleId() { - return ruleId; - } - - /** - * please use setRule(RuleDto rule) - */ - public IssueDto setRuleId(Integer ruleId) { - this.ruleId = ruleId; - return this; - } - - @CheckForNull - public String getSeverity() { - return severity; - } - - public IssueDto setSeverity(@Nullable String s) { - checkArgument(s == null || s.length() <= 10, "Value is too long for issue severity: %s", s); - this.severity = s; - return this; - } - - public boolean isManualSeverity() { - return manualSeverity; - } - - public IssueDto setManualSeverity(boolean manualSeverity) { - this.manualSeverity = manualSeverity; - return this; - } - - @CheckForNull - public String getMessage() { - return message; - } - - public IssueDto setMessage(@Nullable String s) { - checkArgument(s == null || s.length() <= 4000, "Value is too long for issue message: %s", s); - this.message = s; - return this; - } - - @CheckForNull - public Integer getLine() { - return line; - } - - public IssueDto setLine(@Nullable Integer i) { - checkArgument(i == null || i >= 0, "Value of issue line must be positive: %d", i); - this.line = i; - return this; - } - - @CheckForNull - public Double getGap() { - return gap; - } - - public IssueDto setGap(@Nullable Double d) { - checkArgument(d == null || d >= 0, "Value of issue gap must be positive: %d", d); - this.gap = d; - return this; - } - - @CheckForNull - public Long getEffort() { - return effort; - } - - public IssueDto setEffort(@Nullable Long l) { - checkArgument(l == null || l >= 0, "Value of issue effort must be positive: %d", l); - this.effort = l; - return this; - } - - public String getStatus() { - return status; - } - - public IssueDto setStatus(@Nullable String s) { - checkArgument(s == null || s.length() <= 20, "Value is too long for issue status: %s", s); - this.status = s; - return this; - } - - @CheckForNull - public String getResolution() { - return resolution; - } - - public IssueDto setResolution(@Nullable String s) { - checkArgument(s == null || s.length() <= 20, "Value is too long for issue resolution: %s", s); - this.resolution = s; - return this; - } - - @CheckForNull - public String getChecksum() { - return checksum; - } - - public IssueDto setChecksum(@Nullable String s) { - checkArgument(s == null || s.length() <= 1000, "Value is too long for issue checksum: %s", s); - this.checksum = s; - return this; - } - - @CheckForNull - public String getAssignee() { - return assignee; - } - - public IssueDto setAssignee(@Nullable String s) { - checkArgument(s == null || s.length() <= 255, "Value is too long for issue assignee: %s", s); - this.assignee = s; - return this; - } - - @CheckForNull - public String getAuthorLogin() { - return authorLogin; - } - - public IssueDto setAuthorLogin(@Nullable String s) { - checkArgument(s == null || s.length() <= 255, "Value is too long for issue author login: %s", s); - this.authorLogin = s; - return this; - } - - @CheckForNull - public String getIssueAttributes() { - return issueAttributes; - } - - public IssueDto setIssueAttributes(@Nullable String s) { - checkArgument(s == null || s.length() <= 4000, "Value is too long for issue attributes: %s", s); - this.issueAttributes = s; - return this; - } - - /** - * Technical date - */ - public long getCreatedAt() { - return createdAt; - } - - public IssueDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - /** - * Technical date - */ - public long getUpdatedAt() { - return updatedAt; - } - - public IssueDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public Long getIssueCreationTime() { - return issueCreationDate; - } - - public IssueDto setIssueCreationTime(Long time) { - this.issueCreationDate = time; - return this; - } - - public Date getIssueCreationDate() { - return longToDate(issueCreationDate); - } - - public IssueDto setIssueCreationDate(@Nullable Date d) { - this.issueCreationDate = dateToLong(d); - return this; - } - - public Long getIssueUpdateTime() { - return issueUpdateDate; - } - - public IssueDto setIssueUpdateTime(Long time) { - this.issueUpdateDate = time; - return this; - } - - public Date getIssueUpdateDate() { - return longToDate(issueUpdateDate); - } - - public IssueDto setIssueUpdateDate(@Nullable Date d) { - this.issueUpdateDate = dateToLong(d); - return this; - } - - public Long getIssueCloseTime() { - return issueCloseDate; - } - - public IssueDto setIssueCloseTime(Long time) { - this.issueCloseDate = time; - return this; - } - - public Date getIssueCloseDate() { - return longToDate(issueCloseDate); - } - - public IssueDto setIssueCloseDate(@Nullable Date d) { - this.issueCloseDate = dateToLong(d); - return this; - } - - public String getRule() { - return ruleKey; - } - - public IssueDto setRule(RuleDto rule) { - Preconditions.checkNotNull(rule.getId(), "Rule must be persisted."); - this.ruleId = rule.getId(); - this.ruleKey = rule.getRuleKey(); - this.ruleRepo = rule.getRepositoryKey(); - this.language = rule.getLanguage(); - return this; - } - - public String getRuleRepo() { - return ruleRepo; - } - - public RuleKey getRuleKey() { - return RuleKey.of(ruleRepo, ruleKey); - } - - public String getLanguage() { - return language; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setRule(RuleDto)} instead - */ - public IssueDto setLanguage(String language) { - this.language = language; - return this; - } - - public String getComponentKey() { - return componentKey; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setComponent(ComponentDto)} instead - */ - public IssueDto setComponentKey(String componentKey) { - this.componentKey = componentKey; - return this; - } - - /** - * Can be null on Views or Devs - */ - @CheckForNull - public String getComponentUuid() { - return componentUuid; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setComponent(ComponentDto)} instead - */ - public IssueDto setComponentUuid(@Nullable String s) { - checkArgument(s == null || s.length() <= 50, "Value is too long for column ISSUES.COMPONENT_UUID: %s", s); - this.componentUuid = s; - return this; - } - - @CheckForNull - public String getModuleUuid() { - return moduleUuid; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setComponent(ComponentDto)} instead - */ - public IssueDto setModuleUuid(@Nullable String moduleUuid) { - this.moduleUuid = moduleUuid; - return this; - } - - @CheckForNull - public String getModuleUuidPath() { - return moduleUuidPath; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setComponent(ComponentDto)} instead - */ - public IssueDto setModuleUuidPath(@Nullable String moduleUuidPath) { - this.moduleUuidPath = moduleUuidPath; - return this; - } - - /** - * Used by the issue tracking mechanism, but it should used the component uuid instead - */ - public String getProjectKey() { - return projectKey; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setProject(ComponentDto)} instead - */ - public IssueDto setProjectKey(String projectKey) { - this.projectKey = projectKey; - return this; - } - - /** - * Can be null on Views or Devs - */ - @CheckForNull - public String getProjectUuid() { - return projectUuid; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setProject(ComponentDto)} instead - */ - public IssueDto setProjectUuid(@Nullable String s) { - checkArgument(s == null || s.length() <= 50, "Value is too long for column ISSUES.PROJECT_UUID: %s", s); - this.projectUuid = s; - return this; - } - - @CheckForNull - public Long getSelectedAt() { - return selectedAt; - } - - public IssueDto setSelectedAt(@Nullable Long d) { - this.selectedAt = d; - return this; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setRule(RuleDto)} instead - */ - public IssueDto setRuleKey(String repo, String rule) { - this.ruleRepo = repo; - this.ruleKey = rule; - return this; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setProject(ComponentDto)} instead - */ - public String getFilePath() { - return filePath; - } - - /** - * Should only be used to persist in E/S - * <p/> - * Please use {@link #setProject(ComponentDto)} instead - */ - public IssueDto setFilePath(String filePath) { - this.filePath = filePath; - return this; - } - - public Set<String> getTags() { - return ImmutableSet.copyOf(TAGS_SPLITTER.split(tags == null ? "" : tags)); - } - - public IssueDto setTags(@Nullable Collection<String> tags) { - if (tags == null || tags.isEmpty()) { - setTagsString(null); - } else { - setTagsString(TAGS_JOINER.join(tags)); - } - return this; - } - - public IssueDto setTagsString(@Nullable String s) { - checkArgument(s == null || s.length() <= 4000, "Value is too long for column ISSUES.TAGS: %s", s); - this.tags = s; - return this; - } - - public String getTagsString() { - return tags; - } - - @CheckForNull - public byte[] getLocations() { - return locations; - } - - @CheckForNull - public DbIssues.Locations parseLocations() { - if (locations != null) { - try { - return DbIssues.Locations.parseFrom(locations); - } catch (InvalidProtocolBufferException e) { - throw new IllegalStateException(String.format("Fail to read ISSUES.LOCATIONS [KEE=%s]", kee), e); - } - } - return null; - } - - public IssueDto setLocations(@Nullable byte[] locations) { - this.locations = locations; - return this; - } - - public IssueDto setLocations(@Nullable DbIssues.Locations locations) { - if (locations == null) { - this.locations = null; - } else { - this.locations = locations.toByteArray(); - } - return this; - } - - public int getType() { - return type; - } - - public IssueDto setType(int type) { - this.type = type; - return this; - } - - public IssueDto setType(RuleType type) { - this.type = type.getDbConstant(); - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - - public DefaultIssue toDefaultIssue() { - DefaultIssue issue = new DefaultIssue(); - issue.setKey(kee); - issue.setType(RuleType.valueOf(type)); - issue.setStatus(status); - issue.setResolution(resolution); - issue.setMessage(message); - issue.setGap(gap); - issue.setEffort(effort != null ? Duration.create(effort) : null); - issue.setLine(line); - issue.setChecksum(checksum); - issue.setSeverity(severity); - issue.setAssignee(assignee); - issue.setAttributes(KeyValueFormat.parse(MoreObjects.firstNonNull(issueAttributes, ""))); - issue.setComponentKey(componentKey); - issue.setComponentUuid(componentUuid); - issue.setModuleUuid(moduleUuid); - issue.setModuleUuidPath(moduleUuidPath); - issue.setProjectUuid(projectUuid); - issue.setProjectKey(projectKey); - issue.setManualSeverity(manualSeverity); - issue.setRuleKey(getRuleKey()); - issue.setTags(getTags()); - issue.setLanguage(language); - issue.setAuthorLogin(authorLogin); - issue.setNew(false); - issue.setCreationDate(longToDate(issueCreationDate)); - issue.setCloseDate(longToDate(issueCloseDate)); - issue.setUpdateDate(longToDate(issueUpdateDate)); - issue.setSelectedAt(selectedAt); - issue.setLocations(parseLocations()); - return issue; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueMapper.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueMapper.java deleted file mode 100644 index 58934e4d50f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueMapper.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import java.util.List; -import java.util.Set; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; - -public interface IssueMapper { - - IssueDto selectByKey(String key); - - void selectNonClosedByComponentUuid(@Param("componentUuid") String componentUuid, ResultHandler resultHandler); - - Set<String> selectComponentUuidsOfOpenIssuesForProjectUuid(String projectUuid); - - List<IssueDto> selectByKeys(List<String> keys); - - void insert(IssueDto issue); - - int update(IssueDto issue); - - int updateIfBeforeSelectedDate(IssueDto issue); -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/IssueTesting.java b/sonar-db/src/main/java/org/sonar/db/issue/IssueTesting.java deleted file mode 100644 index 748d3bb8b02..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/IssueTesting.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.utils.DateUtils; -import org.sonar.core.util.Uuids; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.rule.RuleDto; - -public class IssueTesting { - - private IssueTesting() { - - } - - /** - * Full IssueDto used to feed database with fake data. Tests must not rely on the - * field contents declared here. They should override the fields they need to test, - * for example: - * <pre> - * issueDao.insert(dbSession, IssueTesting.newDto(rule, file, project).setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FALSE_POSITIVE)); - * </pre> - */ - public static IssueDto newDto(RuleDto rule, ComponentDto file, ComponentDto project) { - return new IssueDto() - .setKee(Uuids.create()) - .setRule(rule) - .setType(RuleType.CODE_SMELL) - .setComponent(file) - .setProject(project) - .setStatus(Issue.STATUS_OPEN) - .setResolution(null) - .setSeverity(Severity.MAJOR) - .setEffort(10L) - .setIssueCreationDate(DateUtils.parseDate("2014-09-04")) - .setIssueUpdateDate(DateUtils.parseDate("2014-12-04")) - .setCreatedAt(1_400_000_000_000L) - .setUpdatedAt(1_400_000_000_000L); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/issue/package-info.java b/sonar-db/src/main/java/org/sonar/db/issue/package-info.java deleted file mode 100644 index 844358c2030..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/issue/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.issue; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDao.java b/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDao.java deleted file mode 100644 index d72b5507918..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDao.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.loadedtemplate; - -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -public class LoadedTemplateDao implements Dao { - - private MyBatis mybatis; - - public LoadedTemplateDao(MyBatis mybatis) { - this.mybatis = mybatis; - } - - public int countByTypeAndKey(String type, String key) { - SqlSession session = mybatis.openSession(false); - try { - return countByTypeAndKey(type, key, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public int countByTypeAndKey(String type, String key, SqlSession session) { - return session.getMapper(LoadedTemplateMapper.class).countByTypeAndKey(type, key); - } - - public void insert(LoadedTemplateDto loadedTemplateDto) { - SqlSession session = mybatis.openSession(false); - try { - insert(loadedTemplateDto, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void insert(LoadedTemplateDto loadedTemplateDto, SqlSession session) { - session.getMapper(LoadedTemplateMapper.class).insert(loadedTemplateDto); - } - - public void delete(DbSession session, String type, String key) { - session.getMapper(LoadedTemplateMapper.class).delete(type, key); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDto.java b/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDto.java deleted file mode 100644 index 0fecf4d728e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDto.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.loadedtemplate; - -import java.util.Objects; - -public final class LoadedTemplateDto { - - public static final String DASHBOARD_TYPE = "DASHBOARD"; - public static final String FILTER_TYPE = "FILTER"; - public static final String QUALITY_PROFILE_TYPE = "QUALITY_PROFILE"; - public static final String PERMISSION_TEMPLATE_TYPE = "PERM_TEMPLATE"; - public static final String QUALITY_GATE_TYPE = "QUALITY_GATE"; - public static final String ONE_SHOT_TASK_TYPE = "ONE_SHOT_TASK"; - public static final String ISSUE_FILTER_TYPE = "ISSUE_FILTER"; - - private Long id; - private String key; - private String type; - - public LoadedTemplateDto() { - } - - public LoadedTemplateDto(String key, String type) { - this.key = key; - this.type = type; - } - - public Long getId() { - return id; - } - - public LoadedTemplateDto setId(Long l) { - this.id = l; - return this; - } - - public String getKey() { - return key; - } - - public LoadedTemplateDto setKey(String key) { - this.key = key; - return this; - } - - public String getType() { - return type; - } - - public LoadedTemplateDto setType(String type) { - this.type = type; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - LoadedTemplateDto other = (LoadedTemplateDto) o; - return Objects.equals(id, other.id) && Objects.equals(key, other.key) && Objects.equals(type, other.type); - } - - @Override - public int hashCode() { - return id != null ? id.hashCode() : 0; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateMapper.java b/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateMapper.java deleted file mode 100644 index 20b5f278eee..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.loadedtemplate; - -import org.apache.ibatis.annotations.Param; - -public interface LoadedTemplateMapper { - - int countByTypeAndKey(@Param("type") String type, @Param("key") String key); - - void insert(LoadedTemplateDto template); - - void delete(@Param("type") String type, @Param("key") String key); -} diff --git a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/package-info.java b/sonar-db/src/main/java/org/sonar/db/loadedtemplate/package-info.java deleted file mode 100644 index 081c236d7a7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/loadedtemplate/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.loadedtemplate; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/measure/MeasureDao.java b/sonar-db/src/main/java/org/sonar/db/measure/MeasureDao.java deleted file mode 100644 index 5f3db408ce3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/MeasureDao.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import org.apache.ibatis.session.ResultHandler; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.component.ComponentDto; - -import static java.util.Collections.emptyList; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; - -public class MeasureDao implements Dao { - - public Optional<MeasureDto> selectSingle(DbSession dbSession, MeasureQuery query) { - List<MeasureDto> measures = selectByQuery(dbSession, query); - return Optional.ofNullable(Iterables.getOnlyElement(measures, null)); - } - - /** - * Selects the measures of either the last analysis (when {@link MeasureQuery#analysisUuid} is {@code null}) or of the - * specified analysis (given by {@link MeasureQuery#analysisUuid}). - * The components can be specified either as : - * - A list of projects in {@link MeasureQuery#projectUuids} - * - A list of components in {@link MeasureQuery#componentUuids} with one mandatory project in {@link MeasureQuery#projectUuids} - * - One single component in {@link MeasureQuery#componentUuids} - * <p> - * In addition, this method returns measures which are not associated to any developer, unless one is specified in - * {@link MeasureQuery#personId}. - * </p> - * <p> - * Returned measure can optionally be filtered metric (either by specifying {@link MeasureQuery#metricIds} - * or {@link MeasureQuery#metricKeys}). - * </p> - */ - public List<MeasureDto> selectByQuery(DbSession dbSession, MeasureQuery query) { - if (query.returnsEmpty()) { - return emptyList(); - } - if (query.isOnComponents()) { - return executeLargeInputs( - query.getComponentUuids(), - componentUuids -> { - MeasureQuery pageQuery = MeasureQuery.copyWithSubsetOfComponentUuids(query, componentUuids); - return mapper(dbSession).selectByQueryOnComponents(pageQuery); - }); - } - if (query.isOnProjects()) { - return executeLargeInputs( - query.getProjectUuids(), - projectUuids -> { - MeasureQuery pageQuery = MeasureQuery.copyWithSubsetOfProjectUuids(query, projectUuids); - return mapper(dbSession).selectByQueryOnProjects(pageQuery); - }); - } - return mapper(dbSession).selectByQueryOnSingleComponent(query); - } - - public void selectByQuery(DbSession dbSession, MeasureQuery query, ResultHandler resultHandler) { - if (query.returnsEmpty()) { - return; - } - if (query.isOnComponents()) { - executeLargeInputsWithoutOutput( - query.getComponentUuids(), - componentUuids -> { - MeasureQuery pageQuery = MeasureQuery.copyWithSubsetOfComponentUuids(query, componentUuids); - mapper(dbSession).selectByQueryOnComponents(pageQuery, resultHandler); - return null; - }); - } - if (query.isOnProjects()) { - executeLargeInputsWithoutOutput( - query.getProjectUuids(), - projectUuids -> { - MeasureQuery pageQuery = MeasureQuery.copyWithSubsetOfProjectUuids(query, projectUuids); - mapper(dbSession).selectByQueryOnProjects(pageQuery, resultHandler); - return null; - }); - } - mapper(dbSession).selectByQueryOnSingleComponent(query, resultHandler); - } - - public List<MeasureDto> selectTreeByQuery(DbSession dbSession, ComponentDto baseComponent, MeasureTreeQuery query) { - if (query.returnsEmpty()) { - return emptyList(); - } - return mapper(dbSession).selectTreeByQuery(query, baseComponent.uuid(), query.getUuidPath(baseComponent)); - } - - public List<PastMeasureDto> selectPastMeasures(DbSession dbSession, String componentUuid, String analysisUuid, Collection<Integer> metricIds) { - if (metricIds.isEmpty()) { - return emptyList(); - } - return executeLargeInputs( - metricIds, - ids -> mapper(dbSession).selectPastMeasuresOnSingleAnalysis(componentUuid, analysisUuid, ids)); - } - - /** - * Select measures of: - * - one component - * - for a list of metrics - * - with analysis from a date (inclusive) - optional - * - with analysis to a date (exclusive) - optional - * - * If no constraints on dates, all the history is returned - */ - public List<MeasureDto> selectPastMeasures(DbSession dbSession, PastMeasureQuery query) { - return mapper(dbSession).selectPastMeasuresOnSeveralAnalyses(query); - } - - /** - * Used by developer cockpit. - */ - public List<MeasureDto> selectProjectMeasuresOfDeveloper(DbSession dbSession, long developerId, Collection<Integer> metricIds) { - return executeLargeInputs( - metricIds, - ids -> mapper(dbSession).selectProjectMeasuresOfDeveloper(developerId, metricIds)); - } - - public void insert(DbSession session, MeasureDto measureDto) { - mapper(session).insert(measureDto); - } - - public void insert(DbSession session, Collection<MeasureDto> items) { - for (MeasureDto item : items) { - insert(session, item); - } - } - - public void insert(DbSession session, MeasureDto item, MeasureDto... others) { - insert(session, Lists.asList(item, others)); - } - - private static MeasureMapper mapper(DbSession session) { - return session.getMapper(MeasureMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/MeasureDto.java b/sonar-db/src/main/java/org/sonar/db/measure/MeasureDto.java deleted file mode 100644 index b7e1d4e7310..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/MeasureDto.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import com.google.common.base.MoreObjects; -import java.nio.charset.StandardCharsets; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class MeasureDto { - private static final int MAX_TEXT_VALUE_LENGTH = 4000; - - private Double value; - private String textValue; - private byte[] dataValue; - private Double variation; - private String alertStatus; - private String alertText; - private String description; - private String componentUuid; - private String analysisUuid; - private int metricId; - private Long developerId; - - @CheckForNull - public Double getValue() { - return value; - } - - public MeasureDto setValue(@Nullable Double value) { - this.value = value; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public MeasureDto setComponentUuid(String s) { - this.componentUuid = s; - return this; - } - - @CheckForNull - public String getData() { - if (dataValue != null) { - return new String(dataValue, StandardCharsets.UTF_8); - } - return textValue; - } - - public MeasureDto setData(@Nullable String data) { - if (data == null) { - this.textValue = null; - this.dataValue = null; - } else if (data.length() > MAX_TEXT_VALUE_LENGTH) { - this.textValue = null; - this.dataValue = data.getBytes(StandardCharsets.UTF_8); - } else { - this.textValue = data; - this.dataValue = null; - } - - return this; - } - - @CheckForNull - public Double getVariation() { - return variation; - } - - public MeasureDto setVariation(@Nullable Double d) { - variation = d; - return this; - } - - @CheckForNull - public String getAlertStatus() { - return alertStatus; - } - - public MeasureDto setAlertStatus(@Nullable String alertStatus) { - this.alertStatus = alertStatus; - return this; - } - - @CheckForNull - public String getAlertText() { - return alertText; - } - - public MeasureDto setAlertText(@Nullable String alertText) { - this.alertText = alertText; - return this; - } - - @CheckForNull - public String getDescription() { - return description; - } - - public MeasureDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - public int getMetricId() { - return metricId; - } - - public MeasureDto setMetricId(int metricId) { - this.metricId = metricId; - return this; - } - - public String getAnalysisUuid() { - return analysisUuid; - } - - public MeasureDto setAnalysisUuid(String s) { - this.analysisUuid = s; - return this; - } - - @CheckForNull - public Long getDeveloperId() { - return developerId; - } - - public MeasureDto setDeveloperId(@Nullable Long developerId) { - this.developerId = developerId; - return this; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("value", value) - .add("textValue", textValue) - .add("dataValue", dataValue) - .add("variation", variation) - .add("alertStatus", alertStatus) - .add("alertText", alertText) - .add("description", description) - .add("componentUuid", componentUuid) - .add("analysisUuid", analysisUuid) - .add("metricId", metricId) - .add("developerId", developerId) - .toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/MeasureMapper.java b/sonar-db/src/main/java/org/sonar/db/measure/MeasureMapper.java deleted file mode 100644 index dfa5ff75613..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/MeasureMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import java.util.Collection; -import java.util.List; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; - -public interface MeasureMapper { - - List<MeasureDto> selectByQueryOnProjects(@Param("query") MeasureQuery query); - - List<MeasureDto> selectByQueryOnComponents(@Param("query") MeasureQuery query); - - List<MeasureDto> selectByQueryOnSingleComponent(@Param("query") MeasureQuery query); - - void selectByQueryOnProjects(@Param("query") MeasureQuery query, ResultHandler resultHandler); - - void selectByQueryOnComponents(@Param("query") MeasureQuery query, ResultHandler resultHandler); - - void selectByQueryOnSingleComponent(@Param("query") MeasureQuery query, ResultHandler resultHandler); - - List<MeasureDto> selectTreeByQuery(@Param("query") MeasureTreeQuery measureQuery, @Param("baseUuid") String baseUuid, @Param("baseUuidPath") String baseUuidPath); - - List<PastMeasureDto> selectPastMeasuresOnSingleAnalysis(@Param("componentUuid") String componentUuid, @Param("analysisUuid") String analysisUuid, - @Param("metricIds") List<Integer> metricIds); - - List<MeasureDto> selectPastMeasuresOnSeveralAnalyses(@Param("query") PastMeasureQuery query); - - List<MeasureDto> selectProjectMeasuresOfDeveloper(@Param("developerId") long developerId, @Param("metricIds") Collection<Integer> metricIds); - - void insert(MeasureDto measureDto); -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/MeasureQuery.java b/sonar-db/src/main/java/org/sonar/db/measure/MeasureQuery.java deleted file mode 100644 index 0b2685ebbe5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/MeasureQuery.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import java.util.Collection; -import java.util.Objects; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Collections.singleton; -import static java.util.Objects.requireNonNull; - -public class MeasureQuery { - @CheckForNull - private final String analysisUuid; - - @CheckForNull - private final Collection<String> projectUuids; - - @CheckForNull - private final Collection<String> componentUuids; - - @CheckForNull - private final Collection<Integer> metricIds; - - @CheckForNull - private final Collection<String> metricKeys; - - @CheckForNull - private final Long personId; - - private MeasureQuery(Builder builder) { - this(builder.analysisUuid, builder.projectUuids, builder.componentUuids, builder.metricIds, builder.metricKeys, builder.personId); - } - - private MeasureQuery(@Nullable String analysisUuid, - @Nullable Collection<String> projectUuids, - @Nullable Collection<String> componentUuids, - @Nullable Collection<Integer> metricIds, - @Nullable Collection<String> metricKeys, - @Nullable Long personId) { - checkArgument(metricIds == null || metricKeys == null, "Metric IDs and keys must not be set both"); - checkArgument(projectUuids != null || componentUuids != null, "At least one filter on component UUID is expected"); - checkArgument(componentUuids == null || componentUuids.size() == 1 || (projectUuids != null && projectUuids.size() == 1), - "Component UUIDs can only be used when a single project UUID is set"); - - this.analysisUuid = analysisUuid; - this.projectUuids = projectUuids; - this.componentUuids = componentUuids; - this.metricIds = metricIds; - this.metricKeys = metricKeys; - this.personId = personId; - } - - public String getAnalysisUuid() { - return analysisUuid; - } - - @CheckForNull - public Collection<String> getProjectUuids() { - return projectUuids; - } - - @CheckForNull - public String getProjectUuid() { - return isOnComponents() ? projectUuids.iterator().next() : null; - } - - @CheckForNull - public Collection<String> getComponentUuids() { - return componentUuids; - } - - @CheckForNull - public String getComponentUuid() { - return isOnSingleComponent() ? componentUuids.iterator().next() : null; - } - - @CheckForNull - public Collection<Integer> getMetricIds() { - return metricIds; - } - - @CheckForNull - public Collection<String> getMetricKeys() { - return metricKeys; - } - - @CheckForNull - public Long getPersonId() { - return personId; - } - - public boolean returnsEmpty() { - return (projectUuids != null && projectUuids.isEmpty()) - || (componentUuids != null && componentUuids.isEmpty()) - || (metricIds != null && metricIds.isEmpty()) - || (metricKeys != null && metricKeys.isEmpty()); - } - - public boolean isOnProjects() { - return projectUuids != null && componentUuids == null; - } - - public boolean isOnComponents() { - return projectUuids != null && projectUuids.size() == 1 && componentUuids != null; - } - - public boolean isOnSingleComponent() { - return projectUuids == null && componentUuids != null && componentUuids.size() == 1; - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MeasureQuery that = (MeasureQuery) o; - return Objects.equals(analysisUuid, that.analysisUuid) && - Objects.equals(projectUuids, that.projectUuids) && - Objects.equals(componentUuids, that.componentUuids) && - Objects.equals(metricIds, that.metricIds) && - Objects.equals(metricKeys, that.metricKeys) && - Objects.equals(personId, that.personId); - } - - @Override - public int hashCode() { - return Objects.hash(analysisUuid, componentUuids, metricIds, metricKeys, personId); - } - - public static Builder builder() { - return new Builder(); - } - - static MeasureQuery copyWithSubsetOfProjectUuids(MeasureQuery query, Collection<String> projectUuids) { - return new MeasureQuery(query.analysisUuid, projectUuids, query.componentUuids, query.metricIds, query.metricKeys, query.personId); - } - - static MeasureQuery copyWithSubsetOfComponentUuids(MeasureQuery query, Collection<String> componentUuids) { - return new MeasureQuery(query.analysisUuid, query.projectUuids, componentUuids, query.metricIds, query.metricKeys, query.personId); - } - - public static final class Builder { - private String analysisUuid; - private Collection<String> projectUuids; - private Collection<String> componentUuids; - private Collection<Integer> metricIds; - private Collection<String> metricKeys; - private Long personId; - - private Builder() { - // see MeasureQuery#builder() - } - - public Builder setAnalysisUuid(String analysisUuid) { - this.analysisUuid = analysisUuid; - return this; - } - - /** - * List of projects - */ - public Builder setProjectUuids(@Nullable Collection<String> projectUuids) { - this.projectUuids = projectUuids; - return this; - } - - /** - * List of components of a project - */ - public Builder setComponentUuids(String projectUuid, Collection<String> componentUuids) { - setProjectUuids(singleton(requireNonNull(projectUuid))); - this.componentUuids = componentUuids; - return this; - } - - /** - * Single component - */ - public Builder setComponentUuid(String componentUuid) { - this.componentUuids = singleton(componentUuid); - return this; - } - - /** - * All the measures are returned if parameter is {@code null}. - */ - public Builder setMetricIds(@Nullable Collection<Integer> metricIds) { - this.metricIds = metricIds; - return this; - } - - public Builder setMetricId(int metricId) { - this.metricIds = singleton(metricId); - return this; - } - - /** - * All the measures are returned if parameter is {@code null}. - */ - public Builder setMetricKeys(@Nullable Collection<String> s) { - this.metricKeys = s; - return this; - } - - public Builder setMetricKey(String s) { - this.metricKeys = singleton(s); - return this; - } - - public Builder setPersonId(@Nullable Long l) { - this.personId = l; - return this; - } - - public MeasureQuery build() { - return new MeasureQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/MeasureTreeQuery.java b/sonar-db/src/main/java/org/sonar/db/measure/MeasureTreeQuery.java deleted file mode 100644 index 8d4eb1b2b36..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/MeasureTreeQuery.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import java.util.Collection; -import java.util.Locale; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.WildcardPosition; -import org.sonar.db.component.ComponentDto; - -import static com.google.common.collect.Lists.newArrayList; -import static java.util.Objects.requireNonNull; -import static org.sonar.db.DatabaseUtils.buildLikeValue; -import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; - -public class MeasureTreeQuery { - - public enum Strategy { - CHILDREN, LEAVES - } - - @CheckForNull - private final String nameOrKeyQuery; - // SONAR-7681 a public implementation of List must be used in MyBatis - potential concurrency exceptions otherwise - @CheckForNull - private final Collection<String> qualifiers; - private final Strategy strategy; - - @CheckForNull - private final Collection<Integer> metricIds; - - @CheckForNull - private final Long personId; - - private MeasureTreeQuery(Builder builder) { - this.nameOrKeyQuery = builder.nameOrKeyQuery; - this.qualifiers = builder.qualifiers == null ? null : newArrayList(builder.qualifiers); - this.strategy = requireNonNull(builder.strategy); - this.metricIds = builder.metricIds; - this.personId = builder.personId; - } - - @CheckForNull - public String getNameOrKeyQuery() { - return nameOrKeyQuery; - } - - /** - * Used by MyBatis mapper - */ - @CheckForNull - public String getNameOrKeyUpperLikeQuery() { - return nameOrKeyQuery == null ? null : buildLikeValue(nameOrKeyQuery, BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); - } - - @CheckForNull - public Collection<String> getQualifiers() { - return qualifiers; - } - - public Strategy getStrategy() { - return strategy; - } - - @CheckForNull - public Collection<Integer> getMetricIds() { - return metricIds; - } - - @CheckForNull - public Long getPersonId() { - return personId; - } - - public String getUuidPath(ComponentDto component) { - switch (strategy) { - case CHILDREN: - return component.getUuidPath() + component.uuid() + "."; - case LEAVES: - return buildLikeValue(component.getUuidPath() + component.uuid() + ".", WildcardPosition.AFTER); - default: - throw new IllegalArgumentException("Unknown strategy : " + strategy); - } - } - - public boolean returnsEmpty() { - return (metricIds != null && metricIds.isEmpty()) || (qualifiers != null && qualifiers.isEmpty()); - } - - public static Builder builder() { - return new Builder(); - } - - public static final class Builder { - - @CheckForNull - private String nameOrKeyQuery; - @CheckForNull - private Collection<String> qualifiers; - private Strategy strategy; - - @CheckForNull - private Collection<Integer> metricIds; - - @CheckForNull - private Long personId; - - private Builder() { - } - - public Builder setNameOrKeyQuery(@Nullable String nameOrKeyQuery) { - this.nameOrKeyQuery = nameOrKeyQuery; - return this; - } - - public Builder setQualifiers(Collection<String> qualifiers) { - this.qualifiers = qualifiers; - return this; - } - - public Builder setStrategy(Strategy strategy) { - this.strategy = requireNonNull(strategy); - return this; - } - - /** - * All the measures are returned if parameter is {@code null}. - */ - public Builder setMetricIds(@Nullable Collection<Integer> metricIds) { - this.metricIds = metricIds; - return this; - } - - public Builder setPersonId(@Nullable Long personId) { - this.personId = personId; - return this; - } - - public MeasureTreeQuery build() { - return new MeasureTreeQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureDto.java b/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureDto.java deleted file mode 100644 index 0e5ccfb91aa..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureDto.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static java.util.Objects.requireNonNull; - -public class PastMeasureDto { - - private int metricId; - - @CheckForNull - private Double value; - - @CheckForNull - private Long personId; - - public double getValue() { - requireNonNull(value); - return value; - } - - PastMeasureDto setValue(@Nullable Double value) { - this.value = value; - return this; - } - - public boolean hasValue() { - return value != null; - } - - public int getMetricId() { - return metricId; - } - - PastMeasureDto setMetricId(int i) { - this.metricId = i; - return this; - } - - @CheckForNull - public Long getPersonId() { - return personId; - } - - PastMeasureDto setPersonId(@Nullable Long l) { - this.personId = l; - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureQuery.java b/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureQuery.java deleted file mode 100644 index 1c26ccb28a5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/PastMeasureQuery.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.db.component.SnapshotDto; - -import static java.util.Objects.requireNonNull; - -public class PastMeasureQuery { - private final String componentUuid; - private final List<Integer> metricIds; - private final Long from; - private final Long to; - private final String status; - - public PastMeasureQuery(String componentUuid, List<Integer> metricIds, @Nullable Long from, @Nullable Long to) { - this.componentUuid = requireNonNull(componentUuid); - this.metricIds = requireNonNull(metricIds); - this.from = from; - this.to = to; - this.status = SnapshotDto.STATUS_PROCESSED; - } - - public String getComponentUuid() { - return componentUuid; - } - - public List<Integer> getMetricIds() { - return metricIds; - } - - @CheckForNull - public Long getFrom() { - return from; - } - - @CheckForNull - public Long getTo() { - return to; - } - - public String getStatus() { - return status; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/ProjectMeasuresIndexerIterator.java b/sonar-db/src/main/java/org/sonar/db/measure/ProjectMeasuresIndexerIterator.java deleted file mode 100644 index f91db430d4b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/ProjectMeasuresIndexerIterator.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableSet; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.Scopes; -import org.sonar.core.util.CloseableIterator; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; - -import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; -import static org.sonar.api.measures.Metric.ValueType.BOOL; -import static org.sonar.api.measures.Metric.ValueType.FLOAT; -import static org.sonar.api.measures.Metric.ValueType.INT; -import static org.sonar.api.measures.Metric.ValueType.LEVEL; -import static org.sonar.api.measures.Metric.ValueType.MILLISEC; -import static org.sonar.api.measures.Metric.ValueType.PERCENT; -import static org.sonar.api.measures.Metric.ValueType.RATING; -import static org.sonar.api.measures.Metric.ValueType.WORK_DUR; -import static org.sonar.db.DatabaseUtils.repeatCondition; - -public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMeasuresIndexerIterator.ProjectMeasures> { - - private static final Set<String> METRIC_TYPES = ImmutableSet.of(INT.name(), FLOAT.name(), PERCENT.name(), BOOL.name(), MILLISEC.name(), LEVEL.name(), RATING.name(), - WORK_DUR.name()); - - private static final Joiner METRICS_JOINER = Joiner.on("','"); - - private static final String SQL_PROJECTS = "SELECT p.organization_uuid, p.uuid, p.kee, p.name, s.uuid, s.created_at FROM projects p " + - "LEFT OUTER JOIN snapshots s ON s.component_uuid=p.uuid AND s.islast=? " + - "WHERE p.enabled=? AND p.scope=? AND p.qualifier=?"; - - private static final String DATE_FILTER = " AND s.created_at>?"; - - private static final String PROJECT_FILTER = " AND p.uuid=?"; - - private static final String SQL_METRICS = "SELECT m.id, m.name FROM metrics m " + - "WHERE m.val_type IN ('" + METRICS_JOINER.join(METRIC_TYPES) + "') " + - "AND m.enabled=?"; - - private static final String SQL_MEASURES = "SELECT pm.metric_id, pm.value, pm.variation_value_1, pm.text_value FROM project_measures pm " + - "WHERE pm.component_uuid = ? AND pm.analysis_uuid = ? " + - "AND pm.metric_id IN ({metricIds}) " + - "AND (pm.value IS NOT NULL OR pm.variation_value_1 IS NOT NULL OR pm.text_value IS NOT NULL) " + - "AND pm.person_id IS NULL "; - - private final PreparedStatement measuresStatement; - private final Map<Long, String> metricKeysByIds; - private final Iterator<Project> projects; - - private ProjectMeasuresIndexerIterator(PreparedStatement measuresStatement, Map<Long, String> metricKeysByIds, List<Project> projects) throws SQLException { - this.measuresStatement = measuresStatement; - this.metricKeysByIds = metricKeysByIds; - this.projects = projects.iterator(); - } - - public static ProjectMeasuresIndexerIterator create(DbSession session, long afterDate, @Nullable String projectUuid) { - try { - Map<Long, String> metrics = selectMetricKeysByIds(session); - List<Project> projects = selectProjects(session, afterDate, projectUuid); - PreparedStatement projectsStatement = createMeasuresStatement(session, metrics.keySet()); - return new ProjectMeasuresIndexerIterator(projectsStatement, metrics, projects); - } catch (SQLException e) { - throw new IllegalStateException("Fail to execute request to select all project measures", e); - } - } - - private static Map<Long, String> selectMetricKeysByIds(DbSession session) { - Map<Long, String> metrics = new HashMap<>(); - try (PreparedStatement stmt = createMetricsStatement(session); - ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - metrics.put(rs.getLong(1), rs.getString(2)); - } - return metrics; - } catch (SQLException e) { - throw new IllegalStateException("Fail to execute request to select all metrics", e); - } - } - - private static PreparedStatement createMetricsStatement(DbSession session) throws SQLException { - PreparedStatement stmt = session.getConnection().prepareStatement(SQL_METRICS); - stmt.setBoolean(1, true); - return stmt; - } - - private static List<Project> selectProjects(DbSession session, long afterDate, @Nullable String projectUuid) { - List<Project> projects = new ArrayList<>(); - try (PreparedStatement stmt = createProjectsStatement(session, afterDate, projectUuid); - ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - String orgUuid = rs.getString(1); - String uuid = rs.getString(2); - String key = rs.getString(3); - String name = rs.getString(4); - String analysisUuid = DatabaseUtils.getString(rs, 5); - Long analysisDate = DatabaseUtils.getLong(rs, 6); - Project project = new Project(orgUuid, uuid, key, name, analysisUuid, analysisDate); - projects.add(project); - } - return projects; - } catch (SQLException e) { - throw new IllegalStateException("Fail to execute request to select all projects", e); - } - } - - private static PreparedStatement createProjectsStatement(DbSession session, long afterDate, @Nullable String projectUuid) { - try { - String sql = SQL_PROJECTS; - sql += afterDate <= 0L ? "" : DATE_FILTER; - sql += projectUuid == null ? "" : PROJECT_FILTER; - PreparedStatement stmt = session.getConnection().prepareStatement(sql); - stmt.setBoolean(1, true); - stmt.setBoolean(2, true); - stmt.setString(3, Scopes.PROJECT); - stmt.setString(4, Qualifiers.PROJECT); - int index = 5; - if (afterDate > 0L) { - stmt.setLong(index, afterDate); - index++; - } - if (projectUuid != null) { - stmt.setString(index, projectUuid); - } - return stmt; - } catch (SQLException e) { - throw new IllegalStateException("Fail to prepare SQL request to select all project measures", e); - } - } - - private static PreparedStatement createMeasuresStatement(DbSession session, Set<Long> metricIds) throws SQLException { - try { - String sql = StringUtils.replace(SQL_MEASURES, "{metricIds}", repeatCondition("?", metricIds.size(), ",")); - PreparedStatement stmt = session.getConnection().prepareStatement(sql); - int index = 3; - for (Long metricId : metricIds) { - stmt.setLong(index, metricId); - index++; - } - return stmt; - } catch (SQLException e) { - throw new IllegalStateException("Fail to prepare SQL request to select measures", e); - } - } - - @Override - @CheckForNull - protected ProjectMeasures doNext() { - if (!projects.hasNext()) { - return null; - } - Project project = projects.next(); - Measures measures = selectMeasures(project.getUuid(), project.getAnalysisUuid()); - return new ProjectMeasures(project, measures); - } - - private Measures selectMeasures(String projectUuid, @Nullable String analysisUuid) { - Measures measures = new Measures(); - if (analysisUuid == null || metricKeysByIds.isEmpty()) { - return measures; - } - ResultSet rs = null; - try { - measuresStatement.setString(1, projectUuid); - measuresStatement.setString(2, analysisUuid); - rs = measuresStatement.executeQuery(); - while (rs.next()) { - readMeasure(rs, measures); - } - return measures; - } catch (Exception e) { - throw new IllegalStateException(String.format("Fail to execute request to select measures of project %s, analysis %s", projectUuid, analysisUuid), e); - } finally { - DatabaseUtils.closeQuietly(rs); - } - } - - private void readMeasure(ResultSet rs, Measures measures) throws SQLException { - String metricKey = metricKeysByIds.get(rs.getLong(1)); - Optional<Double> value = metricKey.startsWith("new_") ? getDouble(rs, 3) : getDouble(rs, 2); - if (value.isPresent()) { - measures.addNumericMeasure(metricKey, value.get()); - return; - } else if (ALERT_STATUS_KEY.equals(metricKey)) { - String textValue = rs.getString(4); - if (!rs.wasNull()) { - measures.setQualityGateStatus(textValue); - return; - } - } - throw new IllegalArgumentException("Measure has no value"); - } - - @Override - protected void doClose() throws Exception { - measuresStatement.close(); - } - - private static Optional<Double> getDouble(ResultSet rs, int index) { - try { - Double value = rs.getDouble(index); - if (!rs.wasNull()) { - return Optional.of(value); - } - return Optional.empty(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to get double value", e); - } - } - - public static class Project { - private final String organizationUuid; - private final String uuid; - private final String key; - private final String name; - private final String analysisUuid; - private final Long analysisDate; - - public Project(String organizationUuid, String uuid, String key, String name, @Nullable String analysisUuid, @Nullable Long analysisDate) { - this.organizationUuid = organizationUuid; - this.uuid = uuid; - this.key = key; - this.name = name; - this.analysisUuid = analysisUuid; - this.analysisDate = analysisDate; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - public String getUuid() { - return uuid; - } - - public String getKey() { - return key; - } - - public String getName() { - return name; - } - - @CheckForNull - public String getAnalysisUuid() { - return analysisUuid; - } - - @CheckForNull - public Long getAnalysisDate() { - return analysisDate; - } - } - - public static class Measures { - - private Map<String, Double> numericMeasures = new HashMap<>(); - private String qualityGateStatus; - - Measures addNumericMeasure(String metricKey, double value) { - numericMeasures.put(metricKey, value); - return this; - } - - public Map<String, Double> getNumericMeasures() { - return numericMeasures; - } - - Measures setQualityGateStatus(@Nullable String qualityGateStatus) { - this.qualityGateStatus = qualityGateStatus; - return this; - } - - @CheckForNull - public String getQualityGateStatus() { - return qualityGateStatus; - } - } - - public static class ProjectMeasures { - private Project project; - private Measures measures; - - public ProjectMeasures(Project project, Measures measures) { - this.project = project; - this.measures = measures; - } - - public Project getProject() { - return project; - } - - public Measures getMeasures() { - return measures; - } - - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDao.java b/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDao.java deleted file mode 100644 index 13832730a89..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDao.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure.custom; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.session.RowBounds; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -public class CustomMeasureDao implements Dao { - public void insert(DbSession session, CustomMeasureDto customMeasureDto) { - mapper(session).insert(customMeasureDto); - } - - public void update(DbSession session, CustomMeasureDto customMeasure) { - mapper(session).update(customMeasure); - } - - public void delete(DbSession session, long id) { - mapper(session).delete(id); - } - - public void deleteByMetricIds(DbSession session, List<Integer> metricIds) { - DatabaseUtils.executeLargeInputsWithoutOutput( - metricIds, - input -> { - mapper(session).deleteByMetricIds(metricIds); - return null; - }); - } - - @CheckForNull - public CustomMeasureDto selectById(DbSession session, long id) { - return mapper(session).selectById(id); - } - - public CustomMeasureDto selectOrFail(DbSession session, long id) { - CustomMeasureDto customMeasure = selectById(session, id); - if (customMeasure == null) { - throw new RowNotFoundException(String.format("Custom measure '%d' not found.", id)); - } - return customMeasure; - } - - public List<CustomMeasureDto> selectByMetricId(DbSession session, int metricId) { - return mapper(session).selectByMetricId(metricId); - } - - public int countByComponentIdAndMetricId(DbSession session, String componentUuid, int metricId) { - return mapper(session).countByComponentIdAndMetricId(componentUuid, metricId); - } - - public List<CustomMeasureDto> selectByComponentUuid(DbSession session, String componentUuid, int offset, int limit) { - return mapper(session).selectByComponentUuid(componentUuid, new RowBounds(offset, limit)); - } - - public List<CustomMeasureDto> selectByComponentUuid(DbSession session, String componentUuid) { - return mapper(session).selectByComponentUuid(componentUuid); - } - - /** - * Used by Views plugin - */ - public List<CustomMeasureDto> selectByMetricKeyAndTextValue(DbSession session, String metricKey, String textValue) { - return mapper(session).selectByMetricKeyAndTextValue(metricKey, textValue); - } - - private static CustomMeasureMapper mapper(DbSession session) { - return session.getMapper(CustomMeasureMapper.class); - } - - public int countByComponentUuid(DbSession dbSession, String uuid) { - return mapper(dbSession).countByComponentUuid(uuid); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDto.java b/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDto.java deleted file mode 100644 index 3aff53354cf..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureDto.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure.custom; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class CustomMeasureDto { - - private long id; - private int metricId; - private String componentUuid; - private double value; - private String textValue; - private String userLogin; - private String description; - private long createdAt; - private long updatedAt; - - public String getDescription() { - return description; - } - - public CustomMeasureDto setDescription(String description) { - this.description = description; - return this; - } - - public String getUserLogin() { - return userLogin; - } - - public CustomMeasureDto setUserLogin(String userLogin) { - this.userLogin = userLogin; - return this; - } - - @CheckForNull - public String getTextValue() { - return textValue; - } - - public CustomMeasureDto setTextValue(@Nullable String textValue) { - this.textValue = textValue; - return this; - } - - public double getValue() { - return value; - } - - public CustomMeasureDto setValue(double value) { - this.value = value; - return this; - } - - public int getMetricId() { - return metricId; - } - - public CustomMeasureDto setMetricId(int metricId) { - this.metricId = metricId; - return this; - } - - public long getId() { - return id; - } - - public CustomMeasureDto setId(long id) { - this.id = id; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public CustomMeasureDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public CustomMeasureDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public CustomMeasureDto setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureMapper.java b/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureMapper.java deleted file mode 100644 index 86be90423c6..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/custom/CustomMeasureMapper.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure.custom; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface CustomMeasureMapper { - void insert(CustomMeasureDto customMeasure); - - void update(CustomMeasureDto customMeasure); - - void delete(long id); - - void deleteByMetricIds(@Param("metricIds") List<Integer> metricIds); - - CustomMeasureDto selectById(long id); - - List<CustomMeasureDto> selectByMetricId(int id); - - List<CustomMeasureDto> selectByComponentUuid(String s); - - List<CustomMeasureDto> selectByComponentUuid(String s, RowBounds rowBounds); - - List<CustomMeasureDto> selectByMetricKeyAndTextValue(@Param("metricKey") String metricKey, @Param("textValue") String textValue); - - int countByComponentUuid(String componentUuid); - - int countByComponentIdAndMetricId(@Param("componentUuid") String componentUuid, @Param("metricId") int metricId); -} diff --git a/sonar-db/src/main/java/org/sonar/db/measure/custom/package-info.java b/sonar-db/src/main/java/org/sonar/db/measure/custom/package-info.java deleted file mode 100644 index ae3ac0e1d64..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/custom/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.measure.custom; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/measure/package-info.java b/sonar-db/src/main/java/org/sonar/db/measure/package-info.java deleted file mode 100644 index 913f21eec74..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/measure/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.measure; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/metric/MetricDao.java b/sonar-db/src/main/java/org/sonar/db/metric/MetricDao.java deleted file mode 100644 index 5bb743df095..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/metric/MetricDao.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.metric; - -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.apache.ibatis.session.RowBounds; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static com.google.common.collect.Lists.newArrayList; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; - -public class MetricDao implements Dao { - - @CheckForNull - public MetricDto selectByKey(DbSession session, String key) { - return mapper(session).selectByKey(key); - } - - public List<MetricDto> selectByKeys(final DbSession session, List<String> keys) { - return executeLargeInputs(keys, mapper(session)::selectByKeys); - } - - public MetricDto selectOrFailByKey(DbSession session, String key) { - MetricDto metric = selectByKey(session, key); - if (metric == null) { - throw new RowNotFoundException(String.format("Metric key '%s' not found", key)); - } - return metric; - } - - public List<MetricDto> selectAll(DbSession session) { - return mapper(session).selectAll(); - } - - public List<MetricDto> selectEnabled(DbSession session) { - return mapper(session).selectAllEnabled(); - } - - public List<MetricDto> selectEnabled(DbSession session, @Nullable Boolean isCustom, int offset, int limit) { - Map<String, Object> properties = Maps.newHashMapWithExpectedSize(1); - if (isCustom != null) { - properties.put("isCustom", isCustom); - } - - return mapper(session).selectAllEnabled(properties, new RowBounds(offset, limit)); - } - - public int countEnabled(DbSession session, @Nullable Boolean isCustom) { - return mapper(session).countEnabled(isCustom); - } - - public MetricDto insert(DbSession session, MetricDto dto) { - mapper(session).insert(dto); - - return dto; - } - - public void insert(DbSession session, Collection<MetricDto> items) { - for (MetricDto item : items) { - insert(session, item); - } - } - - public void insert(DbSession session, MetricDto item, MetricDto... others) { - insert(session, Lists.asList(item, others)); - } - - public List<String> selectEnabledDomains(DbSession session) { - return newArrayList(Collections2.filter(mapper(session).selectDomains(), new NotEmptyPredicate())); - } - - public List<MetricDto> selectAvailableCustomMetricsByComponentUuid(DbSession session, String projectUuid) { - return mapper(session).selectAvailableCustomMetricsByComponentUuid(projectUuid); - } - - public List<MetricDto> selectByIds(DbSession session, Set<Integer> idsSet) { - return executeLargeInputs(new ArrayList<>(idsSet), mapper(session)::selectByIds); - } - - private static class NotEmptyPredicate implements Predicate<String> { - - @Override - public boolean apply(@Nonnull String input) { - return !input.isEmpty(); - } - } - - private static MetricMapper mapper(DbSession session) { - return session.getMapper(MetricMapper.class); - } - - public void disableCustomByIds(final DbSession session, List<Integer> ids) { - executeLargeInputsWithoutOutput( - ids, - input -> { - mapper(session).disableByIds(input); - return null; - }); - } - - /** - * Disable a metric and return {@code false} if the metric does not exist - * or is already disabled. - */ - public boolean disableCustomByKey(DbSession session, String key) { - return mapper(session).disableByKey(key) == 1; - } - - public void update(DbSession session, MetricDto metric) { - mapper(session).update(metric); - } - - @CheckForNull - public MetricDto selectById(DbSession session, long id) { - return mapper(session).selectById(id); - } - - public MetricDto selectOrFailById(DbSession session, long id) { - MetricDto metric = mapper(session).selectById(id); - if (metric == null) { - throw new RowNotFoundException(String.format("Metric id '%d' not found", id)); - } - return metric; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/metric/MetricDto.java b/sonar-db/src/main/java/org/sonar/db/metric/MetricDto.java deleted file mode 100644 index 04f45f93cbf..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/metric/MetricDto.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.metric; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static org.sonar.api.measures.Metric.ValueType.DATA; -import static org.sonar.api.measures.Metric.ValueType.DISTRIB; -import static org.sonar.api.measures.Metric.ValueType.STRING; - -public class MetricDto { - - private Integer id; - - private String kee; - - private String shortName; - - private String valueType; - - private String description; - - private String domain; - - private int direction; - - private boolean qualitative; - - private boolean userManaged; - - private Double worstValue; - - private Double bestValue; - - private boolean optimizedBestValue; - - private boolean hidden; - - private boolean deleteHistoricalData; - - private boolean enabled; - - private Integer decimalScale; - - public Integer getId() { - return id; - } - - public MetricDto setId(Integer id) { - this.id = id; - return this; - } - - public String getKey() { - return kee; - } - - public MetricDto setKey(String name) { - this.kee = name; - return this; - } - - public String getShortName() { - return shortName; - } - - public MetricDto setShortName(String shortName) { - this.shortName = shortName; - return this; - } - - public String getValueType() { - return valueType; - } - - public MetricDto setValueType(String valueType) { - this.valueType = valueType; - return this; - } - - /** - * @return null for manual metrics - */ - @CheckForNull - public String getDescription() { - return description; - } - - public MetricDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - @CheckForNull - public String getDomain() { - return domain; - } - - public MetricDto setDomain(@Nullable String domain) { - this.domain = domain; - return this; - } - - public int getDirection() { - return direction; - } - - public MetricDto setDirection(int direction) { - this.direction = direction; - return this; - } - - public boolean isQualitative() { - return qualitative; - } - - public MetricDto setQualitative(boolean qualitative) { - this.qualitative = qualitative; - return this; - } - - public boolean isUserManaged() { - return userManaged; - } - - public MetricDto setUserManaged(boolean userManaged) { - this.userManaged = userManaged; - return this; - } - - @CheckForNull - public Double getWorstValue() { - return worstValue; - } - - public MetricDto setWorstValue(@Nullable Double worstValue) { - this.worstValue = worstValue; - return this; - } - - @CheckForNull - public Double getBestValue() { - return bestValue; - } - - public MetricDto setBestValue(@Nullable Double bestValue) { - this.bestValue = bestValue; - return this; - } - - public boolean isOptimizedBestValue() { - return optimizedBestValue; - } - - public MetricDto setOptimizedBestValue(boolean optimizedBestValue) { - this.optimizedBestValue = optimizedBestValue; - return this; - } - - public boolean isHidden() { - return hidden; - } - - public MetricDto setHidden(boolean hidden) { - this.hidden = hidden; - return this; - } - - public boolean isDeleteHistoricalData() { - return deleteHistoricalData; - } - - public MetricDto setDeleteHistoricalData(boolean deleteHistoricalData) { - this.deleteHistoricalData = deleteHistoricalData; - return this; - } - - public boolean isEnabled() { - return enabled; - } - - public MetricDto setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - - @CheckForNull - public Integer getDecimalScale() { - return decimalScale; - } - - public MetricDto setDecimalScale(@Nullable Integer i) { - this.decimalScale = i; - return this; - } - - public boolean isDataType() { - return DATA.name().equals(valueType) || DISTRIB.name().equals(valueType) || STRING.name().equals(valueType); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/metric/MetricDtoFunctions.java b/sonar-db/src/main/java/org/sonar/db/metric/MetricDtoFunctions.java deleted file mode 100644 index 34bda9c9c1b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/metric/MetricDtoFunctions.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.metric; - -import java.util.function.Predicate; - -/** - * Common functions on MetricDto - */ -public class MetricDtoFunctions { - private MetricDtoFunctions() { - // prevents instantiation - } - - - public static Predicate<MetricDto> isOptimizedForBestValue() { - return m -> m != null && m.isOptimizedBestValue() && m.getBestValue() != null; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/metric/MetricMapper.java b/sonar-db/src/main/java/org/sonar/db/metric/MetricMapper.java deleted file mode 100644 index 18f6bfcf1d6..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/metric/MetricMapper.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.metric; - -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface MetricMapper { - - MetricDto selectById(long id); - - List<MetricDto> selectByIds(@Param("ids") List<Integer> ids); - - MetricDto selectByKey(@Param("key") String key); - - List<MetricDto> selectByKeys(@Param("keys") List<String> keys); - - List<MetricDto> selectAll(); - - List<MetricDto> selectAllEnabled(); - - List<MetricDto> selectAllEnabled(Map<String, Object> properties, RowBounds rowBounds); - - void insert(MetricDto dto); - - List<String> selectDomains(); - - void disableByIds(@Param("ids") List<Integer> ids); - - int disableByKey(@Param("key") String key); - - int countEnabled(@Param("isCustom") @Nullable Boolean isCustom); - - void update(MetricDto metric); - - List<MetricDto> selectAvailableCustomMetricsByComponentUuid(String projectUuid); -} diff --git a/sonar-db/src/main/java/org/sonar/db/metric/package-info.java b/sonar-db/src/main/java/org/sonar/db/metric/package-info.java deleted file mode 100644 index e3af21d08d3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/metric/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.metric; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDao.java b/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDao.java deleted file mode 100644 index be390291444..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDao.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.notification; - -import java.util.Collections; -import java.util.List; -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -public class NotificationQueueDao implements Dao { - - private final MyBatis mybatis; - - public NotificationQueueDao(MyBatis mybatis) { - this.mybatis = mybatis; - } - - public void insert(List<NotificationQueueDto> dtos) { - DbSession session = mybatis.openSession(true); - NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class); - try { - for (NotificationQueueDto dto : dtos) { - mapper.insert(dto); - } - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void delete(List<NotificationQueueDto> dtos) { - DbSession session = mybatis.openSession(true); - NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class); - try { - for (NotificationQueueDto dto : dtos) { - mapper.delete(dto.getId()); - } - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public List<NotificationQueueDto> selectOldest(int count) { - if (count < 1) { - return Collections.emptyList(); - } - SqlSession session = mybatis.openSession(false); - try { - return session.getMapper(NotificationQueueMapper.class).findOldest(count); - } finally { - MyBatis.closeQuietly(session); - } - } - - public long count() { - SqlSession session = mybatis.openSession(false); - try { - return session.getMapper(NotificationQueueMapper.class).count(); - } finally { - MyBatis.closeQuietly(session); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDto.java b/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDto.java deleted file mode 100644 index ef1e1069c88..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueDto.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.notification; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.notifications.Notification; -import org.sonar.api.utils.SonarException; - -/** - * @since 3.7.1 - */ -public class NotificationQueueDto { - - private Long id; - private byte[] data; - - public Long getId() { - return id; - } - - public NotificationQueueDto setId(Long id) { - this.id = id; - return this; - } - - public byte[] getData() { - return data; - } - - public NotificationQueueDto setData(byte[] data) { - this.data = data; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - - public static NotificationQueueDto toNotificationQueueDto(Notification notification) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - try { - ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); - objectOutputStream.writeObject(notification); - objectOutputStream.close(); - return new NotificationQueueDto().setData(byteArrayOutputStream.toByteArray()); - - } catch (IOException e) { - throw new SonarException("Unable to write notification", e); - - } finally { - IOUtils.closeQuietly(byteArrayOutputStream); - } - } - - public Notification toNotification() throws IOException, ClassNotFoundException { - if (this.data == null) { - return null; - } - ByteArrayInputStream byteArrayInputStream = null; - try { - byteArrayInputStream = new ByteArrayInputStream(this.data); - ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); - Object result = objectInputStream.readObject(); - objectInputStream.close(); - return (Notification) result; - } finally { - IOUtils.closeQuietly(byteArrayInputStream); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueMapper.java b/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueMapper.java deleted file mode 100644 index 867ccdf88a2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/notification/NotificationQueueMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.notification; - -import java.util.List; - -/** - * @since 3.7.1 - */ -public interface NotificationQueueMapper { - - void insert(NotificationQueueDto actionPlanDto); - - void delete(long id); - - List<NotificationQueueDto> findOldest(int count); - - long count(); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/notification/package-info.java b/sonar-db/src/main/java/org/sonar/db/notification/package-info.java deleted file mode 100644 index b2d246490ce..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/notification/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.notification; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/organization/DefaultTemplates.java b/sonar-db/src/main/java/org/sonar/db/organization/DefaultTemplates.java deleted file mode 100644 index 24d2f6cbdee..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/DefaultTemplates.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static java.util.Objects.requireNonNull; - -public class DefaultTemplates { - private String projectUuid; - private String viewUuid; - - public String getProjectUuid() { - checkProjectNotNull(this.projectUuid); - return this.projectUuid; - } - - public DefaultTemplates setProjectUuid(String projectUuid) { - checkProjectNotNull(projectUuid); - this.projectUuid = projectUuid; - return this; - } - - private static void checkProjectNotNull(String project) { - requireNonNull(project, "defaultTemplates.project can't be null"); - } - - @CheckForNull - public String getViewUuid() { - return viewUuid; - } - - public DefaultTemplates setViewUuid(@Nullable String viewUuid) { - this.viewUuid = viewUuid; - return this; - } - - @Override - public String toString() { - return "DefaultTemplates{" + - "projectUuid='" + projectUuid + '\'' + - ", viewUuid='" + viewUuid + '\'' + - '}'; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDao.java b/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDao.java deleted file mode 100644 index d1ef05bd7e5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDao.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static java.util.Objects.requireNonNull; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class OrganizationDao implements Dao { - - private final System2 system2; - - public OrganizationDao(System2 system2) { - this.system2 = system2; - } - - public void insert(DbSession dbSession, OrganizationDto organization) { - checkDto(organization); - long now = system2.now(); - organization.setCreatedAt(now); - organization.setUpdatedAt(now); - getMapper(dbSession).insert(organization); - } - - public List<OrganizationDto> selectByQuery(DbSession dbSession, OrganizationQuery organizationQuery, int offset, int limit) { - requireNonNull(organizationQuery, "organizationQuery can't be null"); - return getMapper(dbSession).selectByQuery(organizationQuery, offset, limit); - } - - public Optional<OrganizationDto> selectByUuid(DbSession dbSession, String uuid) { - checkUuid(uuid); - return Optional.ofNullable(getMapper(dbSession).selectByUuid(uuid)); - } - - public Optional<OrganizationDto> selectByKey(DbSession dbSession, String key) { - requireNonNull(key, "key can't be null"); - return Optional.ofNullable(getMapper(dbSession).selectByKey(key)); - } - - public List<OrganizationDto> selectByUuids(DbSession dbSession, Set<String> organizationUuids) { - if (organizationUuids.size() == 1) { - return Collections.singletonList(getMapper(dbSession).selectByUuid(organizationUuids.iterator().next())); - } - return executeLargeInputs(organizationUuids, getMapper(dbSession)::selectByUuids); - } - - public List<OrganizationDto> selectByPermission(DbSession dbSession, Integer userId, String permission) { - return getMapper(dbSession).selectByPermission(userId, permission); - } - - /** - * Retrieve the default template of the specified organization if: - * <ol> - * <li>the specified organization exists</li> - * <li>the project default permission template is defined</li> - * </ol> - */ - public Optional<DefaultTemplates> getDefaultTemplates(DbSession dbSession, String organizationUuid) { - checkUuid(organizationUuid); - return Optional.ofNullable(getMapper(dbSession).selectDefaultTemplatesByUuid(organizationUuid)); - } - - public void setDefaultTemplates(DbSession dbSession, String uuid, DefaultTemplates defaultTemplates) { - checkUuid(uuid); - checkDefaultTemplates(defaultTemplates); - long now = system2.now(); - getMapper(dbSession).updateDefaultTemplates(uuid, defaultTemplates, now); - } - - public int update(DbSession dbSession, OrganizationDto organization) { - checkDto(organization); - organization.setUpdatedAt(system2.now()); - return getMapper(dbSession).update(organization); - } - - public int deleteByUuid(DbSession dbSession, String uuid) { - return getMapper(dbSession).deleteByUuid(uuid); - } - - public int deleteByKey(DbSession dbSession, String key) { - return getMapper(dbSession).deleteByKey(key); - } - - private static void checkDto(OrganizationDto organization) { - requireNonNull(organization, "OrganizationDto can't be null"); - } - - private static OrganizationMapper getMapper(DbSession dbSession) { - return dbSession.getMapper(OrganizationMapper.class); - } - - private static void checkUuid(String uuid) { - requireNonNull(uuid, "uuid can't be null"); - } - - private static void checkDefaultTemplates(DefaultTemplates defaultTemplates) { - requireNonNull(defaultTemplates, "defaultTemplates can't be null"); - requireNonNull(defaultTemplates.getProjectUuid()); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDto.java b/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDto.java deleted file mode 100644 index 7ba488b6c16..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationDto.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class OrganizationDto { - /** Technical unique identifier, can't be null */ - private String uuid; - /** Functional unique identifier, can't be null */ - private String key; - /** Name, can't be null */ - private String name; - /** description can be null */ - private String description; - /** url can be null */ - private String url; - /** avatar url can be null */ - private String avatarUrl; - /** - * Flag indicated whether being root is required to be able to delete this organization. - */ - private boolean guarded = false; - /** If of the user for whom the organization was created, can be null. */ - private Integer userId; - private long createdAt; - private long updatedAt; - - public String getUuid() { - return uuid; - } - - public OrganizationDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - public String getKey() { - return key; - } - - public OrganizationDto setKey(String key) { - this.key = key; - return this; - } - - public String getName() { - return name; - } - - public OrganizationDto setName(String name) { - this.name = name; - return this; - } - - public String getDescription() { - return description; - } - - public OrganizationDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - public String getUrl() { - return url; - } - - public OrganizationDto setUrl(@Nullable String url) { - this.url = url; - return this; - } - - public String getAvatarUrl() { - return avatarUrl; - } - - public OrganizationDto setAvatarUrl(@Nullable String avatarUrl) { - this.avatarUrl = avatarUrl; - return this; - } - - public boolean isGuarded() { - return guarded; - } - - public OrganizationDto setGuarded(boolean guarded) { - this.guarded = guarded; - return this; - } - - @CheckForNull - public Integer getUserId() { - return userId; - } - - public OrganizationDto setUserId(@Nullable Integer userId) { - this.userId = userId; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public OrganizationDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public OrganizationDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - @Override - public String toString() { - return "OrganizationDto{" + - "uuid='" + uuid + '\'' + - ", key='" + key + '\'' + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - ", url='" + url + '\'' + - ", avatarUrl='" + avatarUrl + '\'' + - ", guarded=" + guarded + - ", userId=" + userId + - ", createdAt=" + createdAt + - ", updatedAt=" + updatedAt + - '}'; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationMapper.java b/sonar-db/src/main/java/org/sonar/db/organization/OrganizationMapper.java deleted file mode 100644 index f26bfb0a954..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationMapper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface OrganizationMapper { - void insert(@Param("organization") OrganizationDto organization); - - List<OrganizationDto> selectByQuery(@Param("query") OrganizationQuery organizationQuery, - @Param("offset") int offset, @Param("pageSize") int pageSize); - - @CheckForNull - OrganizationDto selectByKey(@Param("key") String key); - - @CheckForNull - OrganizationDto selectByUuid(@Param("uuid") String uuid); - - List<OrganizationDto> selectByUuids(@Param("uuids") List<String> uuids); - - List<OrganizationDto> selectByPermission(@Param("userId") Integer userId, @Param("permission") String permission); - - DefaultTemplates selectDefaultTemplatesByUuid(@Param("uuid") String uuid); - - /** - * Update the organization with UUID specified by {@link OrganizationDto#getUuid()}. - * <p> - * This method ignores {@link OrganizationDto#getCreatedAt()} and {@link OrganizationDto#getKey()} - * (they are not updated). - * </p> - */ - int update(@Param("organization") OrganizationDto organization); - - void updateDefaultTemplates(@Param("organizationUuid") String organizationUuid, - @Param("defaultTemplates") DefaultTemplates defaultTemplates, @Param("now") long now); - - int deleteByUuid(@Param("uuid") String uuid); - - int deleteByKey(@Param("key") String key); -} diff --git a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationQuery.java b/sonar-db/src/main/java/org/sonar/db/organization/OrganizationQuery.java deleted file mode 100644 index 794c7ca8fcb..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/OrganizationQuery.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import java.util.Collection; -import java.util.Objects; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static org.sonar.core.util.stream.Collectors.toSet; - -public class OrganizationQuery { - private static final OrganizationQuery NO_QUERY = newOrganizationQueryBuilder().build(); - private final Set<String> keys; - - private OrganizationQuery(Builder builder) { - this.keys = builder.keys; - } - - public static OrganizationQuery returnAll() { - return NO_QUERY; - } - - public static Builder newOrganizationQueryBuilder() { - return new Builder(); - } - - @CheckForNull - public Set<String> getKeys() { - return keys; - } - - public static class Builder { - private Set<String> keys; - - private Builder() { - // use static factory method - } - - public Builder setKeys(@Nullable Collection<String> keys) { - if (keys != null && !keys.isEmpty()) { - this.keys = keys.stream() - .filter(Objects::nonNull) - .collect(toSet(keys.size())); - } - return this; - } - - public OrganizationQuery build() { - return new OrganizationQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/organization/package-info.java b/sonar-db/src/main/java/org/sonar/db/organization/package-info.java deleted file mode 100644 index 932f77f4b20..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/organization/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.organization; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/package-info.java b/sonar-db/src/main/java/org/sonar/db/package-info.java deleted file mode 100644 index 0fa491e02ec..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationDao.java b/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationDao.java deleted file mode 100644 index 6f843f537ed..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationDao.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nullable; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeInputsIntoSet; - -/** - * The SQL requests used to verify authorization (the permissions - * granted to users) - * - * @see GroupPermissionDao for CRUD of table group_roles - * @see UserPermissionDao for CRUD of table user_roles - */ -public class AuthorizationDao implements Dao { - - private static final String USER_ID_PARAM = "userId"; - - /** - * Loads all the permissions granted to logged-in user for the specified organization - */ - public Set<String> selectOrganizationPermissions(DbSession dbSession, String organizationUuid, int userId) { - return mapper(dbSession).selectOrganizationPermissions(organizationUuid, userId); - } - - /** - * Loads all the permissions granted to anonymous user for the specified organization - */ - public Set<String> selectOrganizationPermissionsOfAnonymous(DbSession dbSession, String organizationUuid) { - return mapper(dbSession).selectOrganizationPermissionsOfAnonymous(organizationUuid); - } - - /** - * The number of users who will still have the permission if the group {@code excludedGroupId} - * is deleted. The anyone virtual group is not taken into account. - */ - public int countUsersWithGlobalPermissionExcludingGroup(DbSession dbSession, String organizationUuid, - String permission, int excludedGroupId) { - return mapper(dbSession).countUsersWithGlobalPermissionExcludingGroup(organizationUuid, permission, excludedGroupId); - } - - /** - * The number of users who will still have the permission if the user {@code excludedUserId} - * is deleted. The anyone virtual group is not taken into account. - */ - public int countUsersWithGlobalPermissionExcludingUser(DbSession dbSession, String organizationUuid, - String permission, int excludedUserId) { - return mapper(dbSession).countUsersWithGlobalPermissionExcludingUser(organizationUuid, permission, excludedUserId); - } - - /** - * The number of users who will still have the permission if the user {@code userId} - * is removed from group {@code groupId}. The anyone virtual group is not taken into account. - * Contrary to {@link #countUsersWithGlobalPermissionExcludingUser(DbSession, String, String, int)}, user - * still exists and may have the permission directly or through other groups. - */ - public int countUsersWithGlobalPermissionExcludingGroupMember(DbSession dbSession, String organizationUuid, - String permission, int groupId, int userId) { - return mapper(dbSession).countUsersWithGlobalPermissionExcludingGroupMember(organizationUuid, permission, groupId, userId); - } - - /** - * The number of users who will still have the permission if the permission {@code permission} - * is removed from user {@code userId}. The anyone virtual group is not taken into account. - * Contrary to {@link #countUsersWithGlobalPermissionExcludingUser(DbSession, String, String, int)}, user - * still exists and may have the permission through groups. - */ - public int countUsersWithGlobalPermissionExcludingUserPermission(DbSession dbSession, String organizationUuid, - String permission, int userId) { - return mapper(dbSession).countUsersWithGlobalPermissionExcludingUserPermission(organizationUuid, permission, userId); - } - - /** - * The UUIDs of all the organizations in which the specified user has the specified global permission. An empty - * set is returned if user or permission do not exist. An empty set is also returned if the user is not involved - * in any organization. - * <br/> - * Group membership is taken into account. Anonymous privileges are ignored. - */ - public Set<String> selectOrganizationUuidsOfUserWithGlobalPermission(DbSession dbSession, int userId, String permission) { - return mapper(dbSession).selectOrganizationUuidsOfUserWithGlobalPermission(userId, permission); - } - - public Set<Long> keepAuthorizedProjectIds(DbSession dbSession, Collection<Long> componentIds, @Nullable Integer userId, String role) { - return executeLargeInputsIntoSet( - componentIds, - partition -> { - if (userId == null) { - return mapper(dbSession).keepAuthorizedProjectIdsForAnonymous(role, componentIds); - } - return mapper(dbSession).keepAuthorizedProjectIdsForUser(userId, role, componentIds); - }); - } - - public Collection<String> selectAuthorizedRootProjectsUuids(DbSession dbSession, @Nullable Integer userId, String role) { - String sql; - Map<String, Object> params = new HashMap<>(2); - sql = "selectAuthorizedRootProjectsUuids"; - params.put(USER_ID_PARAM, userId); - params.put("role", role); - - return dbSession.selectList(sql, params); - } - - /** - * Keep only authorized user that have the given permission on a given project. - * Please Note that if the permission is 'Anyone' is NOT taking into account by thie method. - */ - public Collection<Integer> keepAuthorizedUsersForRoleAndProject(DbSession dbSession, Collection<Integer> userIds, String role, long projectId) { - return executeLargeInputs( - userIds, - partitionOfIds -> mapper(dbSession).keepAuthorizedUsersForRoleAndProject(role, projectId, partitionOfIds)); - } - - private static AuthorizationMapper mapper(DbSession dbSession) { - return dbSession.getMapper(AuthorizationMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationMapper.java b/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationMapper.java deleted file mode 100644 index cc5f1f7f1fc..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/AuthorizationMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import org.apache.ibatis.annotations.Param; - -/** - * @see AuthorizationDao - */ -public interface AuthorizationMapper { - - Set<String> selectOrganizationPermissions(@Param("organizationUuid") String organizationUuid, @Param("userId") int userId); - - Set<String> selectOrganizationPermissionsOfAnonymous(@Param("organizationUuid") String organizationUuid); - - int countUsersWithGlobalPermissionExcludingGroup(@Param("organizationUuid") String organizationUuid, - @Param("permission") String permission, @Param("excludedGroupId") int excludedGroupId); - - int countUsersWithGlobalPermissionExcludingUser(@Param("organizationUuid") String organizationUuid, @Param("permission") String permission, - @Param("excludedUserId") int excludedUserId); - - int countUsersWithGlobalPermissionExcludingGroupMember(@Param("organizationUuid") String organizationUuid, - @Param("permission") String permission, @Param("groupId") int groupId, @Param("userId") int userId); - - int countUsersWithGlobalPermissionExcludingUserPermission(@Param("organizationUuid") String organizationUuid, - @Param("permission") String permission, @Param("userId") int userId); - - Set<String> selectOrganizationUuidsOfUserWithGlobalPermission(@Param("userId") int userId, @Param("permission") String permission); - - Set<Long> keepAuthorizedProjectIdsForAnonymous(@Param("role") String role, @Param("componentIds") Collection<Long> componentIds); - - Set<Long> keepAuthorizedProjectIdsForUser(@Param("userId") int userId, @Param("role") String role, @Param("componentIds") Collection<Long> componentIds); - - List<Integer> keepAuthorizedUsersForRoleAndProject(@Param("role") String role, @Param("componentId") long componentId, @Param("userIds") List<Integer> userIds); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/CountPerProjectPermission.java b/sonar-db/src/main/java/org/sonar/db/permission/CountPerProjectPermission.java deleted file mode 100644 index ca1bd228b50..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/CountPerProjectPermission.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Count the number of users or groups for a given project and permission - */ -public class CountPerProjectPermission { - private long componentId; - private String permission; - private int count; - - public CountPerProjectPermission() { - // used by MyBatis - } - - @VisibleForTesting - CountPerProjectPermission(long componentId, String permission, int count) { - this.componentId = componentId; - this.permission = permission; - this.count = count; - } - - public long getComponentId() { - return componentId; - } - - public String getPermission() { - return permission; - } - - public int getCount() { - return count; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDao.java b/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDao.java deleted file mode 100644 index c8fe45a4cd3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDao.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.sonar.api.security.DefaultGroups; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.component.ComponentMapper; -import org.sonar.db.user.GroupMapper; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; - -public class GroupPermissionDao implements Dao { - - private static final String ANYONE_GROUP_PARAMETER = "anyoneGroup"; - - /** - * Returns the names of the groups that match the given query, for the given organization. - * The virtual group "Anyone" may be returned as the value {@link DefaultGroups#ANYONE}. - * @return group names, sorted in alphabetical order - */ - public List<String> selectGroupNamesByQuery(DbSession dbSession, String organizationUuid, PermissionQuery query) { - return mapper(dbSession).selectGroupNamesByQuery(organizationUuid, query, new RowBounds(query.getPageOffset(), query.getPageSize())); - } - - /** - * Count the number of groups returned by {@link #selectGroupNamesByQuery(DbSession, String, PermissionQuery)}, - * without applying pagination. - */ - public int countGroupsByQuery(DbSession dbSession, String organizationUuid, PermissionQuery query) { - return mapper(dbSession).countGroupsByQuery(organizationUuid, query); - } - - /** - * Select global or project permission of given groups and organization. Anyone virtual group is supported - * through the value "zero" (0L) in {@code groupIds}. - */ - public List<GroupPermissionDto> selectByGroupIds(DbSession dbSession, String organizationUuid, List<Integer> groupIds, @Nullable Long projectId) { - return executeLargeInputs(groupIds, groups -> mapper(dbSession).selectByGroupIds(organizationUuid, groups, projectId)); - } - - /** - * Each row returns a {@link CountPerProjectPermission} - */ - public void groupsCountByComponentIdAndPermission(DbSession dbSession, List<Long> componentIds, ResultHandler resultHandler) { - Map<String, Object> parameters = new HashMap<>(2); - parameters.put(ANYONE_GROUP_PARAMETER, DefaultGroups.ANYONE); - - executeLargeInputsWithoutOutput( - componentIds, - partitionedComponentIds -> { - parameters.put("componentIds", partitionedComponentIds); - mapper(dbSession).groupsCountByProjectIdAndPermission(parameters, resultHandler); - return null; - }); - } - - /** - * Selects the global permissions granted to group. An empty list is returned if the - * group does not exist. - */ - public List<String> selectGlobalPermissionsOfGroup(DbSession session, String organizationUuid, @Nullable Integer groupId) { - return mapper(session).selectGlobalPermissionsOfGroup(organizationUuid, groupId); - } - - /** - * Selects the permissions granted to group and project. An empty list is returned if the - * group or project do not exist. - */ - public List<String> selectProjectPermissionsOfGroup(DbSession session, String organizationUuid, @Nullable Integer groupId, long projectId) { - return mapper(session).selectProjectPermissionsOfGroup(organizationUuid, groupId, projectId); - } - - public void insert(DbSession dbSession, GroupPermissionDto dto) { - ensureComponentPermissionConsistency(dbSession, dto); - ensureGroupPermissionConsistency(dbSession, dto); - mapper(dbSession).insert(dto); - } - - private static void ensureComponentPermissionConsistency(DbSession dbSession, GroupPermissionDto dto) { - if (dto.getResourceId() == null) { - return; - } - ComponentMapper componentMapper = dbSession.getMapper(ComponentMapper.class); - checkArgument( - componentMapper.countComponentByOrganizationAndId(dto.getOrganizationUuid(), dto.getResourceId()) == 1, - "Can't insert permission '%s' for component with id '%s' in organization with uuid '%s' because this component does not belong to organization with uuid '%s'", - dto.getRole(), dto.getResourceId(), dto.getOrganizationUuid(), dto.getOrganizationUuid()); - } - - private static void ensureGroupPermissionConsistency(DbSession dbSession, GroupPermissionDto dto) { - if (dto.getGroupId() == null) { - return; - } - GroupMapper groupMapper = dbSession.getMapper(GroupMapper.class); - checkArgument( - groupMapper.countGroupByOrganizationAndId(dto.getOrganizationUuid(), dto.getGroupId()) == 1, - "Can't insert permission '%s' for group with id '%s' in organization with uuid '%s' because this group does not belong to organization with uuid '%s'", - dto.getRole(), dto.getGroupId(), dto.getOrganizationUuid(), dto.getOrganizationUuid()); - } - - /** - * Delete all the permissions associated to a root component (project) - */ - public void deleteByRootComponentId(DbSession dbSession, long rootComponentId) { - mapper(dbSession).deleteByRootComponentId(rootComponentId); - } - - /** - * Delete a single permission. It can be: - * <ul> - * <li>a global permission granted to a group</li> - * <li>a global permission granted to anyone</li> - * <li>a permission granted to a group for a project</li> - * <li>a permission granted to anyone for a project</li> - * </ul> - * @param dbSession - * @param permission the kind of permission - * @param organizationUuid UUID of organization, even if parameter {@code groupId} is not null - * @param groupId if null, then anyone, else id of group - * @param rootComponentId if null, then global permission, else id of root component (project) - */ - public void delete(DbSession dbSession, String permission, String organizationUuid, @Nullable Integer groupId, @Nullable Long rootComponentId) { - mapper(dbSession).delete(permission, organizationUuid, groupId, rootComponentId); - } - - public void deleteByOrganization(DbSession dbSession, String organizationUuid) { - mapper(dbSession).deleteByOrganization(organizationUuid); - } - - private static GroupPermissionMapper mapper(DbSession session) { - return session.getMapper(GroupPermissionMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDto.java b/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDto.java deleted file mode 100644 index 2a1d166b67f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionDto.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import javax.annotation.Nullable; - -public class GroupPermissionDto { - - private String organizationUuid; - private Integer groupId; - private Long resourceId; - private String role; - - public Integer getGroupId() { - return groupId; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - public GroupPermissionDto setOrganizationUuid(String s) { - this.organizationUuid = s; - return this; - } - - /** - * Null when Anyone - */ - public GroupPermissionDto setGroupId(@Nullable Integer groupId) { - this.groupId = groupId; - return this; - } - - @Nullable - public Long getResourceId() { - return resourceId; - } - - public GroupPermissionDto setResourceId(@Nullable Long resourceId) { - this.resourceId = resourceId; - return this; - } - - public String getRole() { - return role; - } - - public GroupPermissionDto setRole(String role) { - this.role = role; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java b/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java deleted file mode 100644 index 10484b173d9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; - -public interface GroupPermissionMapper { - - List<String> selectGroupNamesByQuery(@Param("organizationUuid") String organizationUuid, - @Param("query") PermissionQuery query, RowBounds rowBounds); - - int countGroupsByQuery(@Param("organizationUuid") String organizationUuid, @Param("query") PermissionQuery query); - - List<GroupPermissionDto> selectByGroupIds(@Param("organizationUuid") String organizationUuid, - @Param("groupIds") List<Integer> groupIds, @Nullable @Param("projectId") Long projectId); - - void groupsCountByProjectIdAndPermission(Map<String, Object> parameters, ResultHandler resultHandler); - - void insert(GroupPermissionDto dto); - - void deleteByRootComponentId(@Param("rootComponentId") long componentId); - - void delete(@Param("permission") String permission, @Param("organizationUuid") String organizationUuid, - @Nullable @Param("groupId") Integer groupId, @Nullable @Param("rootComponentId") Long rootComponentId); - - List<String> selectGlobalPermissionsOfGroup(@Param("organizationUuid") String organizationUuid, - @Nullable @Param("groupId") Integer groupId); - - List<String> selectProjectPermissionsOfGroup(@Param("organizationUuid") String organizationUuid, - @Nullable @Param("groupId") Integer groupId, @Param("projectId") long projectId); - - void deleteByOrganization(@Param("organizationUuid") String organizationUuid); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/PermissionQuery.java b/sonar-db/src/main/java/org/sonar/db/permission/PermissionQuery.java deleted file mode 100644 index 678ff2da7cd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/PermissionQuery.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.Locale; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; -import org.sonar.db.WildcardPosition; - -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang.StringUtils.defaultIfBlank; -import static org.sonar.api.utils.Paging.offset; -import static org.sonar.db.DatabaseUtils.buildLikeValue; - -/** - * Query used to get users and groups permissions - */ -@Immutable -public class PermissionQuery { - public static final int RESULTS_MAX_SIZE = 100; - public static final int SEARCH_QUERY_MIN_LENGTH = 3; - public static final int DEFAULT_PAGE_SIZE = 20; - public static final int DEFAULT_PAGE_INDEX = 1; - - // filter: return only the users or groups who have this permission - private final String permission; - // filter on project, else filter global permissions - private final String componentUuid; - private final String template; - - // filter on login, email or name of users or groups - private final String searchQuery; - private final String searchQueryToSql; - private final String searchQueryToSqlLowercase; - - // filter users or groups who have at least one permission. It does make - // sense when the filter "permission" is set. - private final boolean withAtLeastOnePermission; - - private final int pageSize; - private final int pageOffset; - - private PermissionQuery(Builder builder) { - this.permission = builder.permission; - this.withAtLeastOnePermission = builder.withAtLeastOnePermission; - this.componentUuid = builder.componentUuid; - this.template = builder.template; - this.searchQuery = builder.searchQuery; - this.searchQueryToSql = builder.searchQuery == null ? null : buildLikeValue(builder.searchQuery, WildcardPosition.BEFORE_AND_AFTER); - this.searchQueryToSqlLowercase = builder.searchQuery == null ? null : searchQueryToSql.toLowerCase(Locale.ENGLISH); - this.pageSize = builder.pageSize; - this.pageOffset = offset(builder.pageIndex, builder.pageSize); - } - - @CheckForNull - public String getPermission() { - return permission; - } - - public boolean withAtLeastOnePermission() { - return withAtLeastOnePermission; - } - - // TODO remove it, it should not be in the query, but set as a separate parameter - @Deprecated - public String template() { - return template; - } - - @CheckForNull - public String getComponentUuid() { - return componentUuid; - } - - @CheckForNull - public String getSearchQuery() { - return searchQuery; - } - - @CheckForNull - public String getSearchQueryToSql() { - return searchQueryToSql; - } - - @CheckForNull - public String getSearchQueryToSqlLowercase() { - return searchQueryToSqlLowercase; - } - - public int getPageSize() { - return pageSize; - } - - public int getPageOffset() { - return pageOffset; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String permission; - private String componentUuid; - private String template; - private String searchQuery; - private boolean withAtLeastOnePermission; - - private Integer pageIndex = DEFAULT_PAGE_INDEX; - private Integer pageSize = DEFAULT_PAGE_SIZE; - - private Builder() { - // enforce method constructor - } - - public Builder setPermission(@Nullable String permission) { - this.withAtLeastOnePermission = permission != null; - this.permission = permission; - return this; - } - - public Builder setTemplate(@Nullable String template) { - this.template = template; - return this; - } - - public Builder setComponentUuid(@Nullable String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - - public Builder setSearchQuery(@Nullable String s) { - this.searchQuery = defaultIfBlank(s, null); - return this; - } - - public Builder setPageIndex(@Nullable Integer i) { - this.pageIndex = i; - return this; - } - - public Builder setPageSize(@Nullable Integer i) { - this.pageSize = i; - return this; - } - - public Builder withAtLeastOnePermission() { - this.withAtLeastOnePermission = true; - return this; - } - - public PermissionQuery build() { - this.pageIndex = firstNonNull(pageIndex, DEFAULT_PAGE_INDEX); - this.pageSize = firstNonNull(pageSize, DEFAULT_PAGE_SIZE); - checkArgument(searchQuery == null || searchQuery.length() >= SEARCH_QUERY_MIN_LENGTH, "Search query should contains at least %s characters", SEARCH_QUERY_MIN_LENGTH); - return new PermissionQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDao.java b/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDao.java deleted file mode 100644 index 6ae036500f2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDao.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.session.RowBounds; -import org.sonar.core.util.stream.Collectors; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; -import org.sonar.db.component.ComponentMapper; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Collections.emptyList; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class UserPermissionDao implements Dao { - - /** - * List of user permissions ordered by alphabetical order of user names - * - * @param query non-null query including optional filters. - * @param userLogins if null, then filter on all active users. If not null, then filter on logins, including disabled users. - * Must not be empty. If not null then maximum size is {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE}. - */ - public List<UserPermissionDto> select(DbSession dbSession, String organizationUuid, PermissionQuery query, @Nullable Collection<String> userLogins) { - if (userLogins != null) { - if (userLogins.isEmpty()) { - return emptyList(); - } - checkArgument(userLogins.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE, "Maximum 1'000 users are accepted"); - } - - RowBounds rowBounds = new RowBounds(query.getPageOffset(), query.getPageSize()); - return mapper(dbSession).selectByQuery(organizationUuid, query, userLogins, rowBounds); - } - - /** - * Shortcut over {@link #select(DbSession, String, PermissionQuery, Collection)} to return only distinct user - * ids, keeping the same order. - */ - public List<Integer> selectUserIds(DbSession dbSession, String organizationUuid, PermissionQuery query) { - List<UserPermissionDto> dtos = select(dbSession, organizationUuid, query, null); - return dtos.stream() - .map(UserPermissionDto::getUserId) - .distinct() - .collect(Collectors.toList(dtos.size())); - } - - /** - * @see UserPermissionMapper#countUsersByQuery(String, PermissionQuery, Collection) - */ - public int countUsers(DbSession dbSession, String organizationUuid, PermissionQuery query) { - return mapper(dbSession).countUsersByQuery(organizationUuid, query, null); - } - - /** - * Count the number of users per permission for a given list of projects - * - * @param projectIds a non-null list of project ids to filter on. If empty then an empty list is returned. - */ - public List<CountPerProjectPermission> countUsersByProjectPermission(DbSession dbSession, Collection<Long> projectIds) { - return executeLargeInputs(projectIds, mapper(dbSession)::countUsersByProjectPermission); - } - - /** - * Gets all the global permissions granted to user for the specified organization. - * - * @return the global permissions. An empty list is returned if user or organization do not exist. - */ - public List<String> selectGlobalPermissionsOfUser(DbSession dbSession, int userId, String organizationUuid) { - return mapper(dbSession).selectGlobalPermissionsOfUser(userId, organizationUuid); - } - - /** - * Gets all the project permissions granted to user for the specified project. - * - * @return the project permissions. An empty list is returned if project or user do not exist. - */ - public List<String> selectProjectPermissionsOfUser(DbSession dbSession, int userId, long projectId) { - return mapper(dbSession).selectProjectPermissionsOfUser(userId, projectId); - } - - public void insert(DbSession dbSession, UserPermissionDto dto) { - ensureComponentPermissionConsistency(dbSession, dto); - mapper(dbSession).insert(dto); - } - - private static void ensureComponentPermissionConsistency(DbSession dbSession, UserPermissionDto dto) { - if (dto.getComponentId() == null) { - return; - } - ComponentMapper componentMapper = dbSession.getMapper(ComponentMapper.class); - checkArgument( - componentMapper.countComponentByOrganizationAndId(dto.getOrganizationUuid(), dto.getComponentId()) == 1, - "Can't insert permission '%s' for component with id '%s' in organization with uuid '%s' because this component does not belong to organization with uuid '%s'", - dto.getPermission(), dto.getComponentId(), dto.getOrganizationUuid(), dto.getOrganizationUuid()); - } - - /** - * Removes a single global permission from user - */ - public void deleteGlobalPermission(DbSession dbSession, int userId, String permission, String organizationUuid) { - mapper(dbSession).deleteGlobalPermission(userId, permission, organizationUuid); - } - - /** - * Removes a single project permission from user - */ - public void deleteProjectPermission(DbSession dbSession, int userId, String permission, long projectId) { - mapper(dbSession).deleteProjectPermission(userId, permission, projectId); - } - - /** - * Deletes all the permissions defined on a project - */ - public void deleteProjectPermissions(DbSession dbSession, long projectId) { - mapper(dbSession).deleteProjectPermissions(projectId); - } - - public void deleteByOrganization(DbSession dbSession, String organizationUuid) { - mapper(dbSession).deleteByOrganization(organizationUuid); - } - - private static UserPermissionMapper mapper(DbSession dbSession) { - return dbSession.getMapper(UserPermissionMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDto.java b/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDto.java deleted file mode 100644 index 6638cd64d16..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionDto.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class UserPermissionDto { - - private String organizationUuid; - private String permission; - private int userId; - private Long componentId; - - public UserPermissionDto() { - // used by MyBatis - } - - public UserPermissionDto(String organizationUuid, String permission, int userId, @Nullable Long componentId) { - this.organizationUuid = organizationUuid; - this.permission = permission; - this.userId = userId; - this.componentId = componentId; - } - - public String getPermission() { - return permission; - } - - public int getUserId() { - return userId; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - /** - * @return {@code null} if it's a global permission, else return the project id. - */ - @CheckForNull - public Long getComponentId() { - return componentId; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("UserPermissionDto{"); - sb.append("permission='").append(permission).append('\''); - sb.append(", userId=").append(userId); - sb.append(", organizationUuid=").append(organizationUuid); - sb.append(", componentId=").append(componentId); - sb.append('}'); - return sb.toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionMapper.java b/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionMapper.java deleted file mode 100644 index 56209760616..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/UserPermissionMapper.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface UserPermissionMapper { - - List<UserPermissionDto> selectByQuery(@Param("organizationUuid") String organizationUuid, - @Param("query") PermissionQuery query, @Nullable @Param("userLogins") Collection<String> userLogins, RowBounds rowBounds); - - /** - * Count the number of distinct users returned by {@link #selectByQuery(String, PermissionQuery, Collection, RowBounds)} - * {@link PermissionQuery#getPageOffset()} and {@link PermissionQuery#getPageSize()} are ignored. - * - * @param useNull must always be null. It is needed for using the sql of - * {@link #selectByQuery(String, PermissionQuery, Collection, RowBounds)} - */ - int countUsersByQuery(@Param("organizationUuid") String organizationUuid, @Param("query") PermissionQuery query, - @Nullable @Param("userLogins") Collection<String> useNull); - - /** - * Count the number of users per permission for a given list of projects. - * @param projectIds a non-null and non-empty list of project ids - */ - List<CountPerProjectPermission> countUsersByProjectPermission(@Param("projectIds") List<Long> projectIds); - - void insert(UserPermissionDto dto); - - void deleteGlobalPermission(@Param("userId") int userId, @Param("permission") String permission, - @Param("organizationUuid") String organizationUuid); - - void deleteProjectPermission(@Param("userId") int userId, @Param("permission") String permission, - @Param("projectId") long projectId); - - void deleteProjectPermissions(@Param("projectId") long projectId); - - List<String> selectGlobalPermissionsOfUser(@Param("userId") int userId, @Param("organizationUuid") String organizationUuid); - - List<String> selectProjectPermissionsOfUser(@Param("userId") int userId, @Param("projectId") long projectId); - - void deleteByOrganization(@Param("organizationUuid") String organizationUuid); -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/package-info.java b/sonar-db/src/main/java/org/sonar/db/permission/package-info.java deleted file mode 100644 index 3f83de1ed59..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.permission; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/CountByTemplateAndPermissionDto.java b/sonar-db/src/main/java/org/sonar/db/permission/template/CountByTemplateAndPermissionDto.java deleted file mode 100644 index 1f3f1b38249..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/CountByTemplateAndPermissionDto.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -public class CountByTemplateAndPermissionDto { - private long templateId; - private String permission; - private int count; - - public long getTemplateId() { - return templateId; - } - - public void setTemplateId(long templateId) { - this.templateId = templateId; - } - - public String getPermission() { - return permission; - } - - public void setPermission(String permission) { - this.permission = permission; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDao.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDao.java deleted file mode 100644 index 01738bba6e8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDao.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.List; -import java.util.Optional; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Collections.emptyList; -import static java.util.Objects.requireNonNull; - -public class PermissionTemplateCharacteristicDao implements Dao { - - public List<PermissionTemplateCharacteristicDto> selectByTemplateIds(DbSession dbSession, List<Long> templateIds) { - return templateIds.isEmpty() ? emptyList() : mapper(dbSession).selectByTemplateIds(templateIds); - } - - public Optional<PermissionTemplateCharacteristicDto> selectByPermissionAndTemplateId(DbSession dbSession, String permission, long templateId) { - PermissionTemplateCharacteristicDto dto = mapper(dbSession).selectByPermissionAndTemplateId(permission, templateId); - return Optional.ofNullable(dto); - } - - public PermissionTemplateCharacteristicDto insert(DbSession dbSession, PermissionTemplateCharacteristicDto dto) { - checkArgument(dto.getCreatedAt() != 0L && dto.getUpdatedAt() != 0L); - mapper(dbSession).insert(dto); - return dto; - } - - public PermissionTemplateCharacteristicDto update(DbSession dbSession, PermissionTemplateCharacteristicDto templatePermissionDto) { - requireNonNull(templatePermissionDto.getId()); - mapper(dbSession).update(templatePermissionDto); - return templatePermissionDto; - } - - private static PermissionTemplateCharacteristicMapper mapper(DbSession dbSession) { - return dbSession.getMapper(PermissionTemplateCharacteristicMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDto.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDto.java deleted file mode 100644 index afbe25a3693..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDto.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import static com.google.common.base.Preconditions.checkArgument; - -public class PermissionTemplateCharacteristicDto { - - private static final int MAX_PERMISSION_KEY_LENGTH = 64; - - private Long id; - private long templateId; - private String permission; - private boolean withProjectCreator; - private long createdAt; - private long updatedAt; - - public Long getId() { - return id; - } - - public PermissionTemplateCharacteristicDto setId(Long id) { - this.id = id; - return this; - } - - public long getTemplateId() { - return templateId; - } - - public PermissionTemplateCharacteristicDto setTemplateId(long templateId) { - this.templateId = templateId; - return this; - } - - public String getPermission() { - return permission; - } - - public PermissionTemplateCharacteristicDto setPermission(String permission) { - checkArgument(permission.length() <= MAX_PERMISSION_KEY_LENGTH, "Permission key length (%s) is longer than the maximum authorized (%s). '%s' was provided.", - permission.length(), MAX_PERMISSION_KEY_LENGTH, permission); - this.permission = permission; - return this; - } - - public boolean getWithProjectCreator() { - return withProjectCreator; - } - - public PermissionTemplateCharacteristicDto setWithProjectCreator(boolean withProjectCreator) { - this.withProjectCreator = withProjectCreator; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public PermissionTemplateCharacteristicDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public PermissionTemplateCharacteristicDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.java deleted file mode 100644 index ed0a8d6688a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface PermissionTemplateCharacteristicMapper { - - PermissionTemplateCharacteristicDto selectById(@Param("id") long id); - - List<PermissionTemplateCharacteristicDto> selectByTemplateIds(@Param("templateIds") List<Long> templateId); - - PermissionTemplateCharacteristicDto selectByPermissionAndTemplateId(@Param("permission") String permission, @Param("templateId") long templateId); - - void insert(PermissionTemplateCharacteristicDto templatePermissionDto); - - void update(PermissionTemplateCharacteristicDto templatePermissionDto); - - void deleteByTemplateId(long id); - - void deleteByTemplateIds(@Param("templateIds") List<Long> subList); -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDao.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDao.java deleted file mode 100644 index a2aed9311f4..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDao.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.permission.CountPerProjectPermission; -import org.sonar.db.permission.PermissionQuery; - -import static java.lang.String.format; -import static org.sonar.api.security.DefaultGroups.ANYONE; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; -import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; - -public class PermissionTemplateDao implements Dao { - - private static final String ANYONE_GROUP_PARAMETER = "anyoneGroup"; - - private final System2 system; - - public PermissionTemplateDao(System2 system) { - this.system = system; - } - - /** - * @return a paginated list of user logins. - */ - public List<String> selectUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, long templateId) { - return mapper(session).selectUserLoginsByQueryAndTemplate(query, templateId, new RowBounds(query.getPageOffset(), query.getPageSize())); - } - - public int countUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, long templateId) { - return mapper(session).countUserLoginsByQueryAndTemplate(query, templateId); - } - - public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateIdAndUserLogins(DbSession dbSession, long templateId, List<String> logins) { - return executeLargeInputs(logins, l -> mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, l)); - } - - public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) { - return mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, Collections.emptyList()); - } - - public List<String> selectGroupNamesByQueryAndTemplate(DbSession session, PermissionQuery query, String organizationUuid, long templateId) { - return mapper(session).selectGroupNamesByQueryAndTemplate(organizationUuid, templateId, query, new RowBounds(query.getPageOffset(), query.getPageSize())); - } - - public int countGroupNamesByQueryAndTemplate(DbSession session, PermissionQuery query, String organizationUuid, long templateId) { - return mapper(session).countGroupNamesByQueryAndTemplate(organizationUuid, query, templateId); - } - - public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateIdAndGroupNames(DbSession dbSession, long templateId, List<String> groups) { - return executeLargeInputs(groups, g -> mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, g)); - } - - public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(DbSession dbSession, long templateId) { - return mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, Collections.emptyList()); - } - - /** - * @return {@code true} if template contains groups that are granted with {@code permission}, else {@code false} - */ - public boolean hasGroupsWithPermission(DbSession dbSession, long templateId, String permission, @Nullable Integer groupId) { - return mapper(dbSession).countGroupsWithPermission(templateId, permission, groupId) > 0; - } - - @CheckForNull - public PermissionTemplateDto selectByUuid(DbSession session, String templateUuid) { - return mapper(session).selectByUuid(templateUuid); - } - - public List<PermissionTemplateDto> selectAll(DbSession session, String organizationUuid, @Nullable String nameMatch) { - String upperCaseNameLikeSql = nameMatch != null ? toUppercaseSqlQuery(nameMatch) : null; - return mapper(session).selectAll(organizationUuid, upperCaseNameLikeSql); - } - - private static String toUppercaseSqlQuery(String nameMatch) { - String wildcard = "%"; - return format("%s%s%s", wildcard, nameMatch.toUpperCase(Locale.ENGLISH), wildcard); - - } - - public PermissionTemplateDto insert(DbSession session, PermissionTemplateDto dto) { - mapper(session).insert(dto); - return dto; - } - - /** - * Each row returns a #{@link CountPerProjectPermission} - */ - public void usersCountByTemplateIdAndPermission(DbSession dbSession, List<Long> templateIds, ResultHandler resultHandler) { - Map<String, Object> parameters = new HashMap<>(1); - - executeLargeInputsWithoutOutput( - templateIds, - partitionedTemplateIds -> { - parameters.put("templateIds", partitionedTemplateIds); - mapper(dbSession).usersCountByTemplateIdAndPermission(parameters, resultHandler); - return null; - }); - } - - /** - * Each row returns a #{@link CountPerProjectPermission} - */ - public void groupsCountByTemplateIdAndPermission(DbSession dbSession, List<Long> templateIds, ResultHandler resultHandler) { - Map<String, Object> parameters = new HashMap<>(2); - parameters.put(ANYONE_GROUP_PARAMETER, ANYONE); - - executeLargeInputsWithoutOutput( - templateIds, - partitionedTemplateIds -> { - parameters.put("templateIds", partitionedTemplateIds); - mapper(dbSession).groupsCountByTemplateIdAndPermission(parameters, resultHandler); - return null; - }); - } - - public void deleteById(DbSession session, long templateId) { - PermissionTemplateMapper mapper = mapper(session); - mapper.deleteUserPermissionsByTemplateId(templateId); - mapper.deleteGroupPermissionsByTemplateId(templateId); - session.getMapper(PermissionTemplateCharacteristicMapper.class).deleteByTemplateId(templateId); - mapper.deleteById(templateId); - } - - public PermissionTemplateDto update(DbSession session, PermissionTemplateDto permissionTemplate) { - mapper(session).update(permissionTemplate); - return permissionTemplate; - } - - public void insertUserPermission(DbSession session, Long templateId, Integer userId, String permission) { - PermissionTemplateUserDto permissionTemplateUser = new PermissionTemplateUserDto() - .setTemplateId(templateId) - .setUserId(userId) - .setPermission(permission) - .setCreatedAt(now()) - .setUpdatedAt(now()); - - mapper(session).insertUserPermission(permissionTemplateUser); - session.commit(); - } - - public void deleteUserPermission(DbSession session, Long templateId, Integer userId, String permission) { - PermissionTemplateUserDto permissionTemplateUser = new PermissionTemplateUserDto() - .setTemplateId(templateId) - .setPermission(permission) - .setUserId(userId); - mapper(session).deleteUserPermission(permissionTemplateUser); - session.commit(); - } - - public void insertGroupPermission(DbSession session, long templateId, @Nullable Integer groupId, String permission) { - PermissionTemplateGroupDto permissionTemplateGroup = new PermissionTemplateGroupDto() - .setTemplateId(templateId) - .setPermission(permission) - .setGroupId(groupId) - .setCreatedAt(now()) - .setUpdatedAt(now()); - mapper(session).insertGroupPermission(permissionTemplateGroup); - } - - public void insertGroupPermission(DbSession session, PermissionTemplateGroupDto permissionTemplateGroup) { - mapper(session).insertGroupPermission(permissionTemplateGroup); - } - - public void deleteGroupPermission(DbSession session, Long templateId, @Nullable Integer groupId, String permission) { - PermissionTemplateGroupDto permissionTemplateGroup = new PermissionTemplateGroupDto() - .setTemplateId(templateId) - .setPermission(permission) - .setGroupId(groupId); - mapper(session).deleteGroupPermission(permissionTemplateGroup); - session.commit(); - } - - public PermissionTemplateDto selectByName(DbSession dbSession, String organizationUuid, String name) { - return mapper(dbSession).selectByName(organizationUuid, name.toUpperCase(Locale.ENGLISH)); - } - - public List<String> selectPotentialPermissionsByUserIdAndTemplateId(DbSession dbSession, @Nullable Integer currentUserId, long templateId) { - return mapper(dbSession).selectPotentialPermissionsByUserIdAndTemplateId(currentUserId, templateId); - } - - /** - * Remove a group from all templates (used when removing a group) - */ - public void deleteByGroup(DbSession session, int groupId) { - session.getMapper(PermissionTemplateMapper.class).deleteByGroupId(groupId); - } - - private Date now() { - return new Date(system.now()); - } - - private static PermissionTemplateMapper mapper(DbSession session) { - return session.getMapper(PermissionTemplateMapper.class); - } - - public void deleteByOrganization(DbSession dbSession, String organizationUuid) { - PermissionTemplateMapper templateMapper = mapper(dbSession); - PermissionTemplateCharacteristicMapper templateCharacteristicMapper = dbSession.getMapper(PermissionTemplateCharacteristicMapper.class); - List<Long> templateIds = templateMapper.selectTemplateIdsByOrganization(organizationUuid); - executeLargeInputsWithoutOutput(templateIds, subList -> { - templateCharacteristicMapper.deleteByTemplateIds(subList); - templateMapper.deleteGroupPermissionsByTemplateIds(subList); - templateMapper.deleteUserPermissionsByTemplateIds(subList); - templateMapper.deleteByIds(subList); - return null; - }); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDto.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDto.java deleted file mode 100644 index a3b3275c39b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDto.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class PermissionTemplateDto { - - private Long id; - private String name; - private String organizationUuid; - private String uuid; - private String description; - private String keyPattern; - private Date createdAt; - private Date updatedAt; - - public Long getId() { - return id; - } - - public PermissionTemplateDto setId(Long id) { - this.id = id; - return this; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - public PermissionTemplateDto setOrganizationUuid(String s) { - this.organizationUuid = s; - return this; - } - - public String getName() { - return name; - } - - public PermissionTemplateDto setName(String name) { - this.name = name; - return this; - } - - /** - * @deprecated since 5.2 use {@link #getUuid()} - */ - @Deprecated - public String getKee() { - return uuid; - } - - /** - * @deprecated since 5.2 use {@link #setUuid(String)} - */ - @Deprecated - public PermissionTemplateDto setKee(String kee) { - this.uuid = kee; - return this; - } - - /** - * @since 5.2 the kee column is a proper uuid. Before that it was build on the name + timestamp - */ - public String getUuid() { - return uuid; - } - - /** - * @since 5.2 the kee column is a proper uuid. Before it was build on the name + timestamp - */ - public PermissionTemplateDto setUuid(String uuid) { - this.uuid = uuid; - return this; - } - - @CheckForNull - public String getDescription() { - return description; - } - - public PermissionTemplateDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - @CheckForNull - public String getKeyPattern() { - return keyPattern; - } - - public PermissionTemplateDto setKeyPattern(@Nullable String regexp) { - this.keyPattern = regexp; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public PermissionTemplateDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public PermissionTemplateDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateGroupDto.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateGroupDto.java deleted file mode 100644 index d37b2a4ebf7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateGroupDto.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.Date; -import javax.annotation.Nullable; - -public class PermissionTemplateGroupDto { - private Long id; - private Long templateId; - private Integer groupId; - private String permission; - private String groupName; - private Date createdAt; - private Date updatedAt; - - public Long getId() { - return id; - } - - public PermissionTemplateGroupDto setId(Long id) { - this.id = id; - return this; - } - - public Long getTemplateId() { - return templateId; - } - - public PermissionTemplateGroupDto setTemplateId(Long templateId) { - this.templateId = templateId; - return this; - } - - public Integer getGroupId() { - return groupId; - } - - public PermissionTemplateGroupDto setGroupId(@Nullable Integer groupId) { - this.groupId = groupId; - return this; - } - - public String getPermission() { - return permission; - } - - public PermissionTemplateGroupDto setPermission(String permission) { - this.permission = permission; - return this; - } - - public String getGroupName() { - return groupName; - } - - public PermissionTemplateGroupDto setGroupName(String groupName) { - this.groupName = groupName; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public PermissionTemplateGroupDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public PermissionTemplateGroupDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateMapper.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateMapper.java deleted file mode 100644 index ddf2c0a4c0d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateMapper.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; -import org.apache.ibatis.session.RowBounds; -import org.sonar.db.permission.PermissionQuery; - -/** - * @since 3.7 - */ -public interface PermissionTemplateMapper { - - void insert(PermissionTemplateDto permissionTemplate); - - void update(PermissionTemplateDto permissionTemplate); - - void deleteById(long templateId); - - void deleteByIds(@Param("templateIds") List<Long> templateIds); - - void deleteUserPermissionsByTemplateId(long templateId); - - void deleteUserPermissionsByTemplateIds(@Param("templateIds") List<Long> templateIds); - - void deleteUserPermission(PermissionTemplateUserDto permissionTemplateUser); - - void deleteGroupPermissionsByTemplateId(long templateId); - - void deleteGroupPermissionsByTemplateIds(@Param("templateIds") List<Long> templateIds); - - void deleteGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup); - - PermissionTemplateDto selectByUuid(String templateUuid); - - List<PermissionTemplateUserDto> selectUserPermissionsByTemplateIdAndUserLogins(@Param("templateId") long templateId, @Param("logins") List<String> logins); - - List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateIdAndGroupNames(@Param("templateId") long templateId, @Param("groups") List<String> groups); - - void insertUserPermission(PermissionTemplateUserDto permissionTemplateUser); - - void insertGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup); - - void deleteByGroupId(int groupId); - - PermissionTemplateDto selectByName(@Param("organizationUuid") String organizationUuid, @Param("name") String name); - - List<String> selectUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId, RowBounds rowBounds); - - int countUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId); - - List<String> selectGroupNamesByQueryAndTemplate(@Param("organizationUuid") String organizationUuid, - @Param("templateId") long templateId, @Param("query") PermissionQuery query, RowBounds rowBounds); - - int countGroupNamesByQueryAndTemplate(@Param("organizationUuid") String organizationUuid, @Param("query") PermissionQuery query, @Param("templateId") long templateId); - - List<PermissionTemplateDto> selectAll(@Param("organizationUuid") String organizationUuid, @Nullable @Param("upperCaseNameLikeSql") String upperCaseNameLikeSql); - - void usersCountByTemplateIdAndPermission(Map<String, Object> parameters, ResultHandler resultHandler); - - void groupsCountByTemplateIdAndPermission(Map<String, Object> parameters, ResultHandler resultHandler); - - List<String> selectPotentialPermissionsByUserIdAndTemplateId(@Param("userId") @Nullable Integer currentUserId, @Param("templateId") long templateId); - - int countGroupsWithPermission(@Param("templateId") long templateId, @Param("permission") String permission, @Nullable @Param("groupId") Integer groupId); - - List<Long> selectTemplateIdsByOrganization(@Param("organizationUuid") String organizationUuid); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateUserDto.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateUserDto.java deleted file mode 100644 index 3db22ae1560..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateUserDto.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.Date; - -public class PermissionTemplateUserDto { - private Long id; - private Long templateId; - private Integer userId; - private String permission; - private String userName; - private String userLogin; - private Date createdAt; - private Date updatedAt; - - public Long getId() { - return id; - } - - public PermissionTemplateUserDto setId(Long id) { - this.id = id; - return this; - } - - public Long getTemplateId() { - return templateId; - } - - public PermissionTemplateUserDto setTemplateId(Long templateId) { - this.templateId = templateId; - return this; - } - - public Integer getUserId() { - return userId; - } - - public PermissionTemplateUserDto setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public String getUserName() { - return userName; - } - - public PermissionTemplateUserDto setUserName(String userName) { - this.userName = userName; - return this; - } - - public String getUserLogin() { - return userLogin; - } - - public PermissionTemplateUserDto setUserLogin(String userLogin) { - this.userLogin = userLogin; - return this; - } - - public String getPermission() { - return permission; - } - - public PermissionTemplateUserDto setPermission(String permission) { - this.permission = permission; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public PermissionTemplateUserDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public PermissionTemplateUserDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/package-info.java b/sonar-db/src/main/java/org/sonar/db/permission/template/package-info.java deleted file mode 100644 index 2bce88123f4..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/permission/template/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.permission.template; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ConnectionInterceptor.java b/sonar-db/src/main/java/org/sonar/db/profiling/ConnectionInterceptor.java deleted file mode 100644 index b3912651c85..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ConnectionInterceptor.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp.BasicDataSource; - -public interface ConnectionInterceptor { - - Connection getConnection(BasicDataSource dataSource) throws SQLException; - - Connection getConnection(BasicDataSource dataSource, String login, String password) throws SQLException; - -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/InvocationUtils.java b/sonar-db/src/main/java/org/sonar/db/profiling/InvocationUtils.java deleted file mode 100644 index ad36c802e3f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/InvocationUtils.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -class InvocationUtils { - - private InvocationUtils() { - // Only private stuff - } - - static Object invokeQuietly(Object target, Method method, Object[] params) throws Throwable { - Object result = null; - try { - result = method.invoke(target, params); - } catch (InvocationTargetException invocationException) { - for (Class<?> exceptionClass : method.getExceptionTypes()) { - if (exceptionClass.isInstance(invocationException.getCause())) { - throw invocationException.getCause(); - } - throw new IllegalStateException(invocationException.getCause()); - } - } - return result; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/NullConnectionInterceptor.java b/sonar-db/src/main/java/org/sonar/db/profiling/NullConnectionInterceptor.java deleted file mode 100644 index c4d83f456b0..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/NullConnectionInterceptor.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp.BasicDataSource; - -public enum NullConnectionInterceptor implements ConnectionInterceptor { - INSTANCE; - - @Override - public Connection getConnection(BasicDataSource dataSource) throws SQLException { - return dataSource.getConnection(); - } - - @Override - public Connection getConnection(BasicDataSource dataSource, String user, String password) throws SQLException { - return dataSource.getConnection(user, password); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledConnectionInterceptor.java b/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledConnectionInterceptor.java deleted file mode 100644 index ffc74810e73..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledConnectionInterceptor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.lang.reflect.Proxy; -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp.BasicDataSource; - -public enum ProfiledConnectionInterceptor implements ConnectionInterceptor { - INSTANCE; - - @Override - public Connection getConnection(BasicDataSource dataSource) throws SQLException { - return buildConnectionProxy(new ProfilingConnectionHandler(dataSource.getConnection())); - } - - @Override - public Connection getConnection(BasicDataSource dataSource, String login, String password) throws SQLException { - return buildConnectionProxy(new ProfilingConnectionHandler(dataSource.getConnection(login, password))); - } - - private static Connection buildConnectionProxy(ProfilingConnectionHandler connectionHandler) { - ClassLoader classloader = ProfiledConnectionInterceptor.class.getClassLoader(); - return (Connection) Proxy.newProxyInstance(classloader, new Class[] {Connection.class}, connectionHandler); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledDataSource.java b/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledDataSource.java deleted file mode 100644 index ee831a9d95a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ProfiledDataSource.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.Collection; -import org.apache.commons.dbcp.BasicDataSource; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -public class ProfiledDataSource extends BasicDataSource { - - static final Logger SQL_LOGGER = Loggers.get("sql"); - - private final BasicDataSource delegate; - private ConnectionInterceptor connectionInterceptor; - - public ProfiledDataSource(BasicDataSource delegate, ConnectionInterceptor connectionInterceptor) { - this.delegate = delegate; - this.connectionInterceptor = connectionInterceptor; - } - - public BasicDataSource getDelegate() { - return delegate; - } - - public synchronized void setConnectionInterceptor(ConnectionInterceptor ci) { - this.connectionInterceptor = ci; - } - - @Override - public boolean getDefaultAutoCommit() { - return delegate.getDefaultAutoCommit(); - } - - @Override - public void setDefaultAutoCommit(boolean defaultAutoCommit) { - delegate.setDefaultAutoCommit(defaultAutoCommit); - } - - @Override - public boolean getDefaultReadOnly() { - return delegate.getDefaultReadOnly(); - } - - @Override - public void setDefaultReadOnly(boolean defaultReadOnly) { - delegate.setDefaultReadOnly(defaultReadOnly); - } - - @Override - public int getDefaultTransactionIsolation() { - return delegate.getDefaultTransactionIsolation(); - } - - @Override - public void setDefaultTransactionIsolation(int defaultTransactionIsolation) { - delegate.setDefaultTransactionIsolation(defaultTransactionIsolation); - } - - @Override - public String getDefaultCatalog() { - return delegate.getDefaultCatalog(); - } - - @Override - public void setDefaultCatalog(String defaultCatalog) { - delegate.setDefaultCatalog(defaultCatalog); - } - - @Override - public synchronized String getDriverClassName() { - return delegate.getDriverClassName(); - } - - @Override - public synchronized void setDriverClassName(String driverClassName) { - delegate.setDriverClassName(driverClassName); - } - - @Override - public synchronized ClassLoader getDriverClassLoader() { - return delegate.getDriverClassLoader(); - } - - @Override - public synchronized void setDriverClassLoader(ClassLoader driverClassLoader) { - delegate.setDriverClassLoader(driverClassLoader); - } - - @Override - public synchronized int getMaxActive() { - return delegate.getMaxActive(); - } - - @Override - public synchronized void setMaxActive(int maxActive) { - delegate.setMaxActive(maxActive); - } - - @Override - public synchronized int getMaxIdle() { - return delegate.getMaxIdle(); - } - - @Override - public synchronized void setMaxIdle(int maxIdle) { - delegate.setMaxIdle(maxIdle); - } - - @Override - public synchronized int getMinIdle() { - return delegate.getMinIdle(); - } - - @Override - public synchronized void setMinIdle(int minIdle) { - delegate.setMinIdle(minIdle); - } - - @Override - public synchronized int getInitialSize() { - return delegate.getInitialSize(); - } - - @Override - public synchronized void setInitialSize(int initialSize) { - delegate.setInitialSize(initialSize); - } - - @Override - public synchronized long getMaxWait() { - return delegate.getMaxWait(); - } - - @Override - public synchronized void setMaxWait(long maxWait) { - delegate.setMaxWait(maxWait); - } - - @Override - public synchronized boolean isPoolPreparedStatements() { - return delegate.isPoolPreparedStatements(); - } - - @Override - public synchronized void setPoolPreparedStatements(boolean poolingStatements) { - delegate.setPoolPreparedStatements(poolingStatements); - } - - @Override - public synchronized int getMaxOpenPreparedStatements() { - return delegate.getMaxOpenPreparedStatements(); - } - - @Override - public synchronized void setMaxOpenPreparedStatements(int maxOpenStatements) { - delegate.setMaxOpenPreparedStatements(maxOpenStatements); - } - - @Override - public synchronized boolean getTestOnBorrow() { - return delegate.getTestOnBorrow(); - } - - @Override - public synchronized void setTestOnBorrow(boolean testOnBorrow) { - delegate.setTestOnBorrow(testOnBorrow); - } - - @Override - public synchronized boolean getTestOnReturn() { - return delegate.getTestOnReturn(); - } - - @Override - public synchronized void setTestOnReturn(boolean testOnReturn) { - delegate.setTestOnReturn(testOnReturn); - } - - @Override - public synchronized long getTimeBetweenEvictionRunsMillis() { - return delegate.getTimeBetweenEvictionRunsMillis(); - } - - @Override - public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { - delegate.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); - } - - @Override - public synchronized int getNumTestsPerEvictionRun() { - return delegate.getNumTestsPerEvictionRun(); - } - - @Override - public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { - delegate.setNumTestsPerEvictionRun(numTestsPerEvictionRun); - } - - @Override - public synchronized long getMinEvictableIdleTimeMillis() { - return delegate.getMinEvictableIdleTimeMillis(); - } - - @Override - public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { - delegate.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); - } - - @Override - public synchronized boolean getTestWhileIdle() { - return delegate.getTestWhileIdle(); - } - - @Override - public synchronized void setTestWhileIdle(boolean testWhileIdle) { - delegate.setTestWhileIdle(testWhileIdle); - } - - @Override - public synchronized int getNumActive() { - return delegate.getNumActive(); - } - - @Override - public synchronized int getNumIdle() { - return delegate.getNumIdle(); - } - - @Override - public String getPassword() { - return delegate.getPassword(); - } - - @Override - public void setPassword(String password) { - delegate.setPassword(password); - } - - @Override - public synchronized String getUrl() { - return delegate.getUrl(); - } - - @Override - public synchronized void setUrl(String url) { - delegate.setUrl(url); - } - - @Override - public String getUsername() { - return delegate.getUsername(); - } - - @Override - public void setUsername(String username) { - delegate.setUsername(username); - } - - @Override - public String getValidationQuery() { - return delegate.getValidationQuery(); - } - - @Override - public void setValidationQuery(String validationQuery) { - delegate.setValidationQuery(validationQuery); - } - - @Override - public int getValidationQueryTimeout() { - return delegate.getValidationQueryTimeout(); - } - - @Override - public void setValidationQueryTimeout(int timeout) { - delegate.setValidationQueryTimeout(timeout); - } - - @Override - public Collection getConnectionInitSqls() { - return delegate.getConnectionInitSqls(); - } - - @Override - public void setConnectionInitSqls(Collection connectionInitSqls) { - delegate.setConnectionInitSqls(connectionInitSqls); - } - - @Override - public synchronized boolean isAccessToUnderlyingConnectionAllowed() { - return delegate.isAccessToUnderlyingConnectionAllowed(); - } - - @Override - public synchronized void setAccessToUnderlyingConnectionAllowed(boolean allow) { - delegate.setAccessToUnderlyingConnectionAllowed(allow); - } - - @Override - public Connection getConnection() throws SQLException { - return connectionInterceptor.getConnection(delegate); - } - - @Override - public Connection getConnection(String login, String password) throws SQLException { - return connectionInterceptor.getConnection(this, login, password); - } - - @Override - public int getLoginTimeout() throws SQLException { - return delegate.getLoginTimeout(); - } - - @Override - public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { - return java.util.logging.Logger.getLogger(getClass().getName()); - } - - @Override - public PrintWriter getLogWriter() throws SQLException { - return delegate.getLogWriter(); - } - - @Override - public void setLoginTimeout(int loginTimeout) throws SQLException { - delegate.setLoginTimeout(loginTimeout); - } - - @Override - public void setLogWriter(PrintWriter logWriter) throws SQLException { - delegate.setLogWriter(logWriter); - } - - @Override - public boolean getRemoveAbandoned() { - return delegate.getRemoveAbandoned(); - } - - @Override - public void setRemoveAbandoned(boolean removeAbandoned) { - delegate.setRemoveAbandoned(removeAbandoned); - } - - @Override - public int getRemoveAbandonedTimeout() { - return delegate.getRemoveAbandonedTimeout(); - } - - @Override - public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) { - delegate.setRemoveAbandonedTimeout(removeAbandonedTimeout); - } - - @Override - public boolean getLogAbandoned() { - return delegate.getLogAbandoned(); - } - - @Override - public void setLogAbandoned(boolean logAbandoned) { - delegate.setLogAbandoned(logAbandoned); - } - - @Override - public void addConnectionProperty(String name, String value) { - delegate.addConnectionProperty(name, value); - } - - @Override - public void removeConnectionProperty(String name) { - delegate.removeConnectionProperty(name); - } - - @Override - public void setConnectionProperties(String connectionProperties) { - delegate.setConnectionProperties(connectionProperties); - } - - @Override - public synchronized void close() throws SQLException { - delegate.close(); - } - - @Override - public synchronized boolean isClosed() { - return delegate.isClosed(); - } - - @Override - public boolean isWrapperFor(Class<?> iface) throws SQLException { - return delegate.isWrapperFor(iface); - } - - @Override - public <T> T unwrap(Class<T> iface) throws SQLException { - return delegate.unwrap(iface); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingConnectionHandler.java b/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingConnectionHandler.java deleted file mode 100644 index d6e63e21dbd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingConnectionHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.Statement; - -class ProfilingConnectionHandler implements InvocationHandler { - - private final Connection connection; - - ProfilingConnectionHandler(Connection connection) { - this.connection = connection; - } - - @Override - public Object invoke(Object target, Method method, Object[] args) throws Throwable { - Object result = InvocationUtils.invokeQuietly(connection, method, args); - if ("prepareStatement".equals(method.getName())) { - PreparedStatement statement = (PreparedStatement) result; - String sql = (String) args[0]; - return buildStatementProxy(PreparedStatement.class, new ProfilingPreparedStatementHandler(statement, sql)); - } - if ("createStatement".equals(method.getName())) { - Statement statement = (Statement) result; - return buildStatementProxy(Statement.class, new ProfilingStatementHandler(statement)); - } - return result; - } - - private static Object buildStatementProxy(Class<? extends Statement> stmtClass, InvocationHandler handler) { - return Proxy.newProxyInstance(ProfilingConnectionHandler.class.getClassLoader(), new Class[] {stmtClass}, handler); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingPreparedStatementHandler.java b/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingPreparedStatementHandler.java deleted file mode 100644 index 1c9bd8f3868..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingPreparedStatementHandler.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.sql.PreparedStatement; -import org.sonar.api.utils.log.Profiler; - -class ProfilingPreparedStatementHandler implements InvocationHandler { - - private final PreparedStatement statement; - private final String sql; - private final Object[] sqlParams; - - ProfilingPreparedStatementHandler(PreparedStatement statement, String sql) { - this.statement = statement; - this.sql = sql; - sqlParams = new Object[SqlLogFormatter.countArguments(sql)]; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (method.getName().startsWith("execute")) { - Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); - Object result = null; - try { - result = InvocationUtils.invokeQuietly(statement, method, args); - } finally { - profiler.addContext("sql", SqlLogFormatter.formatSql(sql)); - if (sqlParams.length > 0) { - profiler.addContext("params", SqlLogFormatter.formatParams(sqlParams)); - } - profiler.stopTrace(""); - } - return result; - } else if (method.getName().startsWith("set") && args.length > 1) { - sqlParams[(int) args[0] - 1] = args[1]; - return InvocationUtils.invokeQuietly(statement, method, args); - } else { - return InvocationUtils.invokeQuietly(statement, method, args); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingStatementHandler.java b/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingStatementHandler.java deleted file mode 100644 index 4a8c1ef6053..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/ProfilingStatementHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.sql.Statement; -import org.sonar.api.utils.log.Profiler; - -class ProfilingStatementHandler implements InvocationHandler { - - private final Statement statement; - - ProfilingStatementHandler(Statement statement) { - this.statement = statement; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (method.getName().startsWith("execute")) { - Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); - Object result = null; - try { - result = InvocationUtils.invokeQuietly(statement, method, args); - } finally { - String sql = (String) args[0]; - profiler.addContext("sql", SqlLogFormatter.formatSql(sql)); - profiler.stopTrace(""); - } - return result; - } else { - return InvocationUtils.invokeQuietly(statement, method, args); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/SqlLogFormatter.java b/sonar-db/src/main/java/org/sonar/db/profiling/SqlLogFormatter.java deleted file mode 100644 index fafc22ca46f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/SqlLogFormatter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.profiling; - -import java.util.regex.Pattern; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; - -import static org.apache.commons.lang.StringUtils.abbreviate; - -public class SqlLogFormatter { - - public static final int PARAM_MAX_WIDTH = 500; - private static final String PARAM_NULL = "[null]"; - private static final Pattern NEWLINE_PATTERN = Pattern.compile("\\n"); - - private SqlLogFormatter() { - // only statics - } - - public static String formatSql(String sql) { - return StringUtils.replaceChars(sql, '\n', ' '); - } - - public static String formatParam(@Nullable Object param) { - if (param == null) { - return PARAM_NULL; - } - String abbreviated = abbreviate(param.toString(), PARAM_MAX_WIDTH); - return NEWLINE_PATTERN.matcher(abbreviated).replaceAll("\\\\n"); - } - - public static String formatParams(Object[] params) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - sb.append(", "); - } - sb.append(formatParam(params[i])); - } - return sb.toString(); - } - - public static int countArguments(String sql) { - int argCount = 0; - for (int i = 0; i < sql.length(); i++) { - if (sql.charAt(i) == '?') { - argCount++; - } - } - return argCount; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/profiling/package-info.java b/sonar-db/src/main/java/org/sonar/db/profiling/package-info.java deleted file mode 100644 index 43c7f272860..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/profiling/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.profiling; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesDao.java b/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesDao.java deleted file mode 100644 index e9e500bc3e5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesDao.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import java.util.Optional; -import javax.annotation.Nullable; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; - -public class InternalPropertiesDao implements Dao { - - private static final int TEXT_VALUE_MAX_LENGTH = 4000; - private static final Optional<String> OPTIONAL_OF_EMPTY_STRING = Optional.of(""); - - private final System2 system2; - - public InternalPropertiesDao(System2 system2) { - this.system2 = system2; - } - - /** - * Save a property which value is not empty. - * <p>Value can't be {@code null} but can have any size except 0.</p> - * - * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null} or empty. - * - * @see #saveAsEmpty(DbSession, String) - */ - public void save(DbSession dbSession, String key, String value) { - checkKey(key); - checkArgument(value != null && !value.isEmpty(), "value can't be null nor empty"); - - InternalPropertiesMapper mapper = getMapper(dbSession); - mapper.deleteByKey(key); - long now = system2.now(); - if (mustsBeStoredInClob(value)) { - mapper.insertAsClob(key, value, now); - } else { - mapper.insertAsText(key, value, now); - } - } - - private static boolean mustsBeStoredInClob(String value) { - return value.length() > TEXT_VALUE_MAX_LENGTH; - } - - /** - * Save a property which value is empty. - */ - public void saveAsEmpty(DbSession dbSession, String key) { - checkKey(key); - - InternalPropertiesMapper mapper = getMapper(dbSession); - mapper.deleteByKey(key); - mapper.insertAsEmpty(key, system2.now()); - } - - /** - * No streaming of value - */ - public Optional<String> selectByKey(DbSession dbSession, String key) { - checkKey(key); - - InternalPropertiesMapper mapper = getMapper(dbSession); - InternalPropertyDto res = mapper.selectAsText(key); - if (res == null) { - return Optional.empty(); - } - if (res.isEmpty()) { - return OPTIONAL_OF_EMPTY_STRING; - } - if (res.getValue() != null) { - return Optional.of(res.getValue()); - } - res = mapper.selectAsClob(key); - if (res == null) { - Loggers.get(InternalPropertiesDao.class) - .debug("Internal property {} has been found in db but has neither text value nor is empty. " + - "Still we couldn't be retrieved with clob value. Ignoring the property.", key); - return Optional.empty(); - } - return Optional.of(res.getValue()); - } - - private static void checkKey(@Nullable String key) { - checkArgument(key != null && !key.isEmpty(), "key can't be null nor empty"); - } - - private static InternalPropertiesMapper getMapper(DbSession dbSession) { - return dbSession.getMapper(InternalPropertiesMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesMapper.java b/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesMapper.java deleted file mode 100644 index be1e5b122b4..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertiesMapper.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import org.apache.ibatis.annotations.Param; - -public interface InternalPropertiesMapper { - InternalPropertyDto selectAsText(@Param("key") String key); - - InternalPropertyDto selectAsClob(@Param("key") String key); - - void insertAsEmpty(@Param("key") String key, @Param("createdAt") long createdAt); - - void insertAsText(@Param("key") String key, @Param("value") String value, @Param("createdAt") long createdAt); - - void insertAsClob(@Param("key") String key, @Param("value") String value, @Param("createdAt") long createdAt); - - void deleteByKey(@Param("key") String key); -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertyDto.java b/sonar-db/src/main/java/org/sonar/db/property/InternalPropertyDto.java deleted file mode 100644 index 17de71479c8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/InternalPropertyDto.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -public final class InternalPropertyDto { - private String key; - private boolean empty; - private String value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public boolean isEmpty() { - return empty; - } - - public void setEmpty(boolean empty) { - this.empty = empty; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/PropertiesDao.java b/sonar-db/src/main/java/org/sonar/db/property/PropertiesDao.java deleted file mode 100644 index df0d6a383be..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/PropertiesDao.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import com.google.common.base.Strings; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.resources.Scopes; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class PropertiesDao implements Dao { - - private static final String NOTIFICATION_PREFIX = "notification."; - private static final int VARCHAR_MAXSIZE = 4000; - - private final MyBatis mybatis; - private final System2 system2; - - public PropertiesDao(MyBatis mybatis, System2 system2) { - this.mybatis = mybatis; - this.system2 = system2; - } - - /** - * Returns the logins of users who have subscribed to the given notification dispatcher with the given notification channel. - * If a resource ID is passed, the search is made on users who have specifically subscribed for the given resource. - * - * @return the list of logins (maybe be empty - obviously) - */ - public List<String> selectUsersForNotification(String notificationDispatcherKey, String notificationChannelKey, @Nullable String projectUuid) { - try (DbSession session = mybatis.openSession(false)) { - return getMapper(session).findUsersForNotification(NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey, projectUuid); - } - } - - public List<String> selectNotificationSubscribers(String notificationDispatcherKey, String notificationChannelKey, @Nullable String componentKey) { - try (DbSession session = mybatis.openSession(false)) { - return getMapper(session).findNotificationSubscribers(NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey, componentKey); - } - } - - public boolean hasProjectNotificationSubscribersForDispatchers(String projectUuid, Collection<String> dispatcherKeys) { - try (DbSession session = mybatis.openSession(false); - Connection connection = session.getConnection(); - PreparedStatement pstmt = createStatement(projectUuid, dispatcherKeys, connection); - ResultSet rs = pstmt.executeQuery()) { - return rs.next() && rs.getInt(1) > 0; - } catch (SQLException e) { - throw new IllegalStateException("Fail to execute SQL for hasProjectNotificationSubscribersForDispatchers", e); - } - } - - private static PreparedStatement createStatement(String projectUuid, Collection<String> dispatcherKeys, Connection connection) throws SQLException { - String sql = "SELECT count(1) FROM properties pp " + - "left outer join projects pj on pp.resource_id = pj.id " + - "where pp.user_id is not null and (pp.resource_id is null or pj.uuid=?) " + - "and (" + DatabaseUtils.repeatCondition("pp.prop_key like ?", dispatcherKeys.size(), "or") + ")"; - PreparedStatement res = connection.prepareStatement(sql); - res.setString(1, projectUuid); - int index = 2; - for (String dispatcherKey : dispatcherKeys) { - res.setString(index, "notification." + dispatcherKey + ".%"); - index++; - } - return res; - } - - public List<PropertyDto> selectGlobalProperties() { - try (DbSession session = mybatis.openSession(false)) { - return selectGlobalProperties(session); - } - } - - public List<PropertyDto> selectGlobalProperties(DbSession session) { - return getMapper(session).selectGlobalProperties(); - } - - @CheckForNull - public PropertyDto selectGlobalProperty(DbSession session, String propertyKey) { - return getMapper(session).selectByKey(new PropertyDto().setKey(propertyKey)); - } - - @CheckForNull - public PropertyDto selectGlobalProperty(String propertyKey) { - try (DbSession session = mybatis.openSession(false)) { - return selectGlobalProperty(session, propertyKey); - } - } - - public List<PropertyDto> selectProjectProperties(DbSession session, String projectKey) { - return getMapper(session).selectProjectProperties(projectKey); - } - - public List<PropertyDto> selectProjectProperties(String resourceKey) { - try (DbSession session = mybatis.openSession(false)) { - return selectProjectProperties(session, resourceKey); - } - } - - public List<PropertyDto> selectEnabledDescendantModuleProperties(String moduleUuid, DbSession session) { - return getMapper(session).selectDescendantModuleProperties(moduleUuid, Scopes.PROJECT, true); - } - - @CheckForNull - public PropertyDto selectProjectProperty(long componentId, String propertyKey) { - try (DbSession session = mybatis.openSession(false)) { - return selectProjectProperty(session, componentId, propertyKey); - } - } - - @CheckForNull - public PropertyDto selectProjectProperty(DbSession dbSession, long componentId, String propertyKey) { - return getMapper(dbSession).selectByKey(new PropertyDto().setKey(propertyKey).setResourceId(componentId)); - } - - public List<PropertyDto> selectByQuery(PropertyQuery query, DbSession session) { - return getMapper(session).selectByQuery(query); - } - - public List<PropertyDto> selectGlobalPropertiesByKeys(DbSession session, Set<String> keys) { - return selectByKeys(session, keys, null); - } - - public List<PropertyDto> selectPropertiesByKeysAndComponentId(DbSession session, Set<String> keys, long componentId) { - return selectByKeys(session, keys, componentId); - } - - public List<PropertyDto> selectPropertiesByKeysAndComponentIds(DbSession session, Set<String> keys, Set<Long> componentIds) { - return executeLargeInputs(keys, partitionKeys -> executeLargeInputs(componentIds, - partitionComponentIds -> getMapper(session).selectByKeysAndComponentIds(partitionKeys, partitionComponentIds))); - } - - public List<PropertyDto> selectPropertiesByComponentIds(DbSession session, Set<Long> componentIds) { - return executeLargeInputs(componentIds, getMapper(session)::selectByComponentIds); - } - - private List<PropertyDto> selectByKeys(DbSession session, Set<String> keys, @Nullable Long componentId) { - return executeLargeInputs(keys, partitionKeys -> getMapper(session).selectByKeys(partitionKeys, componentId)); - } - - /** - * Saves the specified property and its value. - * <p> - * If {@link PropertyDto#getValue()} is {@code null} or empty, the properties is persisted as empty. - * </p> - * - * @throws IllegalArgumentException if {@link PropertyDto#getKey()} is {@code null} or empty - */ - public void saveProperty(DbSession session, PropertyDto property) { - save(getMapper(session), property.getKey(), property.getUserId(), property.getResourceId(), property.getValue()); - } - - private void save(PropertiesMapper mapper, - String key, @Nullable Integer userId, @Nullable Long componentId, - @Nullable String value) { - checkKey(key); - - long now = system2.now(); - mapper.delete(key, userId, componentId); - if (isEmpty(value)) { - mapper.insertAsEmpty(key, userId, componentId, now); - } else if (mustBeStoredInClob(value)) { - mapper.insertAsClob(key, userId, componentId, value, now); - } else { - mapper.insertAsText(key, userId, componentId, value, now); - } - } - - private static boolean mustBeStoredInClob(String value) { - return value.length() > VARCHAR_MAXSIZE; - } - - private static void checkKey(@Nullable String key) { - checkArgument(!isEmpty(key), "key can't be null nor empty"); - } - - private static boolean isEmpty(@Nullable String str) { - return str == null || str.isEmpty(); - } - - public void saveProperty(PropertyDto property) { - try (DbSession session = mybatis.openSession(false)) { - saveProperty(session, property); - session.commit(); - } - } - - /** - * Delete either global, user, component or component per user properties. - * <p>Behaves in exactly the same way as {@link #selectByQuery(PropertyQuery, DbSession)} but deletes rather than - * selects</p> - * - * Used by Governance. - */ - public int deleteByQuery(DbSession dbSession, PropertyQuery query) { - return getMapper(dbSession).deleteByQuery(query); - } - - public int delete(DbSession dbSession, PropertyDto dto) { - return getMapper(dbSession).delete(dto.getKey(), dto.getUserId(), dto.getResourceId()); - } - - public void deleteProjectProperty(String key, Long projectId) { - try (DbSession session = mybatis.openSession(false)) { - deleteProjectProperty(key, projectId, session); - session.commit(); - } - } - - public void deleteProjectProperty(String key, Long projectId, DbSession session) { - getMapper(session).deleteProjectProperty(key, projectId); - } - - public void deleteProjectProperties(String key, String value, DbSession session) { - getMapper(session).deleteProjectProperties(key, value); - } - - public void deleteProjectProperties(String key, String value) { - try (DbSession session = mybatis.openSession(false)) { - deleteProjectProperties(key, value, session); - session.commit(); - } - } - - public void deleteGlobalProperty(String key, DbSession session) { - getMapper(session).deleteGlobalProperty(key); - } - - public void deleteGlobalProperty(String key) { - try (DbSession session = mybatis.openSession(false)) { - deleteGlobalProperty(key, session); - session.commit(); - } - } - - public void saveGlobalProperties(Map<String, String> properties) { - try (DbSession session = mybatis.openSession(false)) { - PropertiesMapper mapper = getMapper(session); - properties.entrySet().forEach(entry -> { - mapper.deleteGlobalProperty(entry.getKey()); - save(mapper, entry.getKey(), null, null, entry.getValue()); - }); - session.commit(); - } - } - - public void renamePropertyKey(String oldKey, String newKey) { - checkArgument(!Strings.isNullOrEmpty(oldKey), "Old property key must not be empty"); - checkArgument(!Strings.isNullOrEmpty(newKey), "New property key must not be empty"); - - if (!newKey.equals(oldKey)) { - try (DbSession session = mybatis.openSession(false)) { - getMapper(session).renamePropertyKey(oldKey, newKey); - session.commit(); - } - } - } - - private static PropertiesMapper getMapper(DbSession session) { - return session.getMapper(PropertiesMapper.class); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/PropertiesMapper.java b/sonar-db/src/main/java/org/sonar/db/property/PropertiesMapper.java deleted file mode 100644 index dd8f6c562b8..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/PropertiesMapper.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; - -public interface PropertiesMapper { - - List<String> findUsersForNotification(@Param("notifKey") String notificationKey, @Nullable @Param("projectUuid") String projectUuid); - - List<String> findNotificationSubscribers(@Param("propKey") String propertyKey, @Nullable @Param("componentKey") String componentKey); - - List<PropertyDto> selectGlobalProperties(); - - List<PropertyDto> selectProjectProperties(String resourceKey); - - PropertyDto selectByKey(PropertyDto key); - - List<PropertyDto> selectByKeys(@Param("keys") List<String> keys, @Nullable @Param("componentId") Long componentId); - - List<PropertyDto> selectByKeysAndComponentIds(@Param("keys") List<String> keys, @Param("componentIds") List<Long> componentIds); - - List<PropertyDto> selectByComponentIds(@Param("componentIds") List<Long> componentIds); - - List<PropertyDto> selectByQuery(@Param("query") PropertyQuery query); - - List<PropertyDto> selectDescendantModuleProperties(@Param("moduleUuid") String moduleUuid, @Param(value = "scope") String scope, - @Param(value = "excludeDisabled") boolean excludeDisabled); - - void insertAsEmpty(@Param("key") String key, @Nullable @Param("userId") Integer userId, @Nullable @Param("componentId") Long componentId, - @Param("now") long now); - - void insertAsText(@Param("key") String key, @Nullable @Param("userId") Integer userId, @Nullable @Param("componentId") Long componentId, - @Param("value") String value, @Param("now") long now); - - void insertAsClob(@Param("key") String key, @Nullable @Param("userId") Integer userId, @Nullable @Param("componentId") Long componentId, - @Param("value") String value, @Param("now") long now); - - int delete(@Param("key") String key, @Nullable @Param("userId") Integer userId, @Nullable @Param("componentId") Long componentId); - - int deleteById(long id); - - int deleteProjectProperty(@Param("key") String key, @Param("rId") Long componentId); - - int deleteProjectProperties(@Param("key") String key, @Param("value") String value); - - int deleteGlobalProperty(@Param("key") String key); - - int deleteByQuery(@Param("query") PropertyQuery query); - - int renamePropertyKey(@Param("oldKey") String oldKey, @Param("newKey") String newKey); -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/PropertyDto.java b/sonar-db/src/main/java/org/sonar/db/property/PropertyDto.java deleted file mode 100644 index f9cabe4c6e7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/PropertyDto.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import com.google.common.base.MoreObjects; -import java.util.Objects; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkArgument; - -public class PropertyDto { - private static final int MAX_KEY_LENGTH = 512; - - private String key; - private String value; - private Long resourceId; - private Integer userId; - - public String getKey() { - return key; - } - - public PropertyDto setKey(String key) { - checkArgument(key.length() <= MAX_KEY_LENGTH, "Setting key length (%s) is longer than the maximum authorized (%s). '%s' was provided", key.length(), MAX_KEY_LENGTH, key); - this.key = key; - return this; - } - - public String getValue() { - return value; - } - - public PropertyDto setValue(@Nullable String value) { - this.value = value; - return this; - } - - @CheckForNull - public Long getResourceId() { - return resourceId; - } - - public PropertyDto setResourceId(@Nullable Long resourceId) { - this.resourceId = resourceId; - return this; - } - - @CheckForNull - public Integer getUserId() { - return userId; - } - - public PropertyDto setUserId(@Nullable Integer userId) { - this.userId = userId; - return this; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PropertyDto other = (PropertyDto) obj; - return Objects.equals(this.key, other.key) - && Objects.equals(this.userId, other.userId) - && Objects.equals(this.resourceId, other.resourceId) - && Objects.equals(this.value, other.value); - } - - @Override - public int hashCode() { - return Objects.hash(this.key, this.value, this.resourceId, this.userId); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .addValue(this.key) - .addValue(this.value) - .addValue(this.resourceId) - .addValue(this.userId) - .toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/PropertyQuery.java b/sonar-db/src/main/java/org/sonar/db/property/PropertyQuery.java deleted file mode 100644 index a89927d8b5c..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/PropertyQuery.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import javax.annotation.Nullable; - -public class PropertyQuery { - - private final String key; - private final Long componentId; - private final Integer userId; - - private PropertyQuery(Builder builder) { - this.key = builder.key; - this.componentId = builder.componentId; - this.userId = builder.userId; - } - - public String key() { - return key; - } - - public Long componentId() { - return componentId; - } - - public Integer userId() { - return userId; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String key; - private Long componentId; - private Integer userId; - - public Builder setKey(String key) { - this.key = key; - return this; - } - - public Builder setComponentId(@Nullable Long componentId) { - this.componentId = componentId; - return this; - } - - public Builder setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public PropertyQuery build() { - return new PropertyQuery(this); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/PropertyTesting.java b/sonar-db/src/main/java/org/sonar/db/property/PropertyTesting.java deleted file mode 100644 index 79d4d6fd7d1..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/PropertyTesting.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import javax.annotation.Nullable; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.user.UserDto; - -import static com.google.common.base.Preconditions.checkNotNull; - -public class PropertyTesting { - - private static int cursor = RandomUtils.nextInt(100); - - private PropertyTesting() { - // static methods only - } - - public static PropertyDto newGlobalPropertyDto(String key, String value) { - return newPropertyDto(key, value, (Long) null, null); - } - - public static PropertyDto newGlobalPropertyDto() { - return newPropertyDto((Long) null, null); - } - - public static PropertyDto newComponentPropertyDto(String key, String value, ComponentDto component) { - checkNotNull(component.getId()); - return newPropertyDto(key, value, component.getId(), null); - } - - public static PropertyDto newComponentPropertyDto(ComponentDto component) { - checkNotNull(component.getId()); - return newPropertyDto(component.getId(), null); - } - - public static PropertyDto newUserPropertyDto(String key, String value, UserDto user) { - checkNotNull(user.getId()); - return newPropertyDto(key, value, null, user.getId()); - } - - public static PropertyDto newUserPropertyDto(UserDto user) { - checkNotNull(user.getId()); - return newPropertyDto(null, user.getId()); - } - - public static PropertyDto newPropertyDto(String key, String value, ComponentDto component, UserDto user) { - checkNotNull(component.getId()); - checkNotNull(user.getId()); - return newPropertyDto(key, value, component.getId(), user.getId()); - } - - public static PropertyDto newPropertyDto(ComponentDto component, UserDto user) { - checkNotNull(component.getId()); - checkNotNull(user.getId()); - return newPropertyDto(component.getId(), user.getId()); - } - - private static PropertyDto newPropertyDto(@Nullable Long componentId, @Nullable Integer userId) { - String key = String.valueOf(cursor); - cursor++; - String value = String.valueOf(cursor); - cursor++; - return newPropertyDto(key, value, componentId, userId); - } - - private static PropertyDto newPropertyDto(String key, String value, @Nullable Long componentId, @Nullable Integer userId) { - PropertyDto propertyDto = new PropertyDto() - .setKey(key) - .setValue(value); - if (componentId != null) { - propertyDto.setResourceId(componentId); - } - if (userId != null) { - propertyDto.setUserId(userId); - } - return propertyDto; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/ScrapPropertyDto.java b/sonar-db/src/main/java/org/sonar/db/property/ScrapPropertyDto.java deleted file mode 100644 index 887de847259..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/ScrapPropertyDto.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import javax.annotation.Nullable; - -public class ScrapPropertyDto extends PropertyDto { - public void setEmpty(boolean flag) { - if (flag) { - setValue(""); - } - } - - public void setTextValue(@Nullable String value) { - if (value != null) { - setValue(value); - } - } - - public void setClobValue(@Nullable String value) { - if (value != null) { - setValue(value); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/property/package-info.java b/sonar-db/src/main/java/org/sonar/db/property/package-info.java deleted file mode 100644 index c073920afae..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/property/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.property; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPair.java b/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPair.java deleted file mode 100644 index 29a24908f8d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPair.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import java.util.Objects; -import javax.annotation.Nullable; - -public class IdUuidPair { - private Long id; - private String uuid; - - public IdUuidPair() { - } - - public IdUuidPair(long id, String uuid) { - this.id = id; - this.uuid = uuid; - } - - public Long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - @Override - public String toString() { - return "IdUuidPair{" + - "id=" + id + - ", uuid='" + uuid + '\'' + - '}'; - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - IdUuidPair that = (IdUuidPair) o; - return Objects.equals(id, that.id) && Objects.equals(uuid, that.uuid); - } - - @Override - public int hashCode() { - return Objects.hash(id, uuid); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPairs.java b/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPairs.java deleted file mode 100644 index 551f93ff126..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/IdUuidPairs.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -class IdUuidPairs { - private IdUuidPairs() { - // prevents instantiation - } - - public static List<Long> ids(List<IdUuidPair> pairs) { - return pairs.stream().map(IdUuidPair::getId).collect(Collectors.toCollection(() -> new ArrayList<>(pairs.size()))); - } - - public static List<String> uuids(List<IdUuidPair> pairs) { - return pairs.stream().map(IdUuidPair::getUuid).collect(Collectors.toCollection(() -> new ArrayList<>(pairs.size()))); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeCommands.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeCommands.java deleted file mode 100644 index 86b00635d84..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeCommands.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Lists; -import java.util.List; -import java.util.stream.Collectors; -import org.apache.ibatis.session.SqlSession; - -import static com.google.common.collect.FluentIterable.from; -import static java.util.Arrays.asList; - -class PurgeCommands { - - private static final int MAX_SNAPSHOTS_PER_QUERY = 1000; - private static final int MAX_RESOURCES_PER_QUERY = 1000; - - private final SqlSession session; - private final PurgeMapper purgeMapper; - private final PurgeProfiler profiler; - - PurgeCommands(SqlSession session, PurgeMapper purgeMapper, PurgeProfiler profiler) { - this.session = session; - this.purgeMapper = purgeMapper; - this.profiler = profiler; - } - - @VisibleForTesting - PurgeCommands(SqlSession session, PurgeProfiler profiler) { - this(session, session.getMapper(PurgeMapper.class), profiler); - } - - List<String> selectSnapshotUuids(PurgeSnapshotQuery query) { - return purgeMapper.selectAnalysisIdsAndUuids(query).stream().map(IdUuidPair::getUuid).collect(Collectors.toList()); - } - - List<IdUuidPair> selectSnapshotIdUuids(PurgeSnapshotQuery query) { - return purgeMapper.selectAnalysisIdsAndUuids(query); - } - - void deleteAnalyses(String rootUuid) { - deleteAnalyses(purgeMapper.selectAnalysisIdsAndUuids(new PurgeSnapshotQuery().setComponentUuid(rootUuid))); - } - - void deleteComponents(List<IdUuidPair> componentIdUuids) { - List<List<Long>> componentIdPartitions = Lists.partition(IdUuidPairs.ids(componentIdUuids), MAX_RESOURCES_PER_QUERY); - List<List<String>> componentUuidsPartitions = Lists.partition(IdUuidPairs.uuids(componentIdUuids), MAX_RESOURCES_PER_QUERY); - // Note : do not merge the delete statements into a single loop of resource ids. It's - // voluntarily grouped by tables in order to benefit from JDBC batch mode. - // Batch requests can only relate to the same PreparedStatement. - - // possible missing optimization: filter requests according to resource scope - - profiler.start("deleteResourceLinks (project_links)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponentLinks); - session.commit(); - profiler.stop(); - - profiler.start("deleteResourceProperties (properties)"); - componentIdPartitions.forEach(purgeMapper::deleteComponentProperties); - session.commit(); - profiler.stop(); - - profiler.start("deleteResourceGroupRoles (group_roles)"); - componentIdPartitions.forEach(purgeMapper::deleteComponentGroupRoles); - session.commit(); - profiler.stop(); - - profiler.start("deleteResourceUserRoles (user_roles)"); - componentIdPartitions.forEach(purgeMapper::deleteComponentUserRoles); - session.commit(); - profiler.stop(); - - profiler.start("deleteResourceManualMeasures (manual_measures)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponentManualMeasures); - session.commit(); - profiler.stop(); - - profiler.start("deleteComponentIssueChanges (issue_changes)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponentIssueChanges); - session.commit(); - profiler.stop(); - - profiler.start("deleteComponentIssues (issues)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponentIssues); - session.commit(); - profiler.stop(); - - profiler.start("deleteComponentEvents (events)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponentEvents); - session.commit(); - profiler.stop(); - - profiler.start("deleteResource (projects)"); - componentUuidsPartitions.forEach(purgeMapper::deleteComponents); - session.commit(); - profiler.stop(); - - profiler.start("deleteAuthors (authors)"); - componentIdPartitions.forEach(purgeMapper::deleteAuthors); - session.commit(); - profiler.stop(); - } - - public void deleteComponentMeasures(List<String> analysisUuids, List<String> componentUuids) { - if (analysisUuids.isEmpty() || componentUuids.isEmpty()) { - return; - } - - List<List<String>> analysisUuidsPartitions = Lists.partition(analysisUuids, MAX_SNAPSHOTS_PER_QUERY); - List<List<String>> componentUuidsPartitions = Lists.partition(componentUuids, MAX_RESOURCES_PER_QUERY); - - profiler.start("deleteComponentMeasures"); - for (List<String> analysisUuidsPartition : analysisUuidsPartitions) { - for (List<String> componentUuidsPartition : componentUuidsPartitions) { - purgeMapper.deleteComponentMeasures(analysisUuidsPartition, componentUuidsPartition); - } - } - session.commit(); - profiler.stop(); - } - - void deleteAnalyses(PurgeSnapshotQuery... queries) { - List<IdUuidPair> snapshotIds = from(asList(queries)) - .transformAndConcat(purgeMapper::selectAnalysisIdsAndUuids) - .toList(); - deleteAnalyses(snapshotIds); - } - - @VisibleForTesting - protected void deleteAnalyses(List<IdUuidPair> analysisIdUuids) { - List<List<String>> analysisUuidsPartitions = Lists.partition(IdUuidPairs.uuids(analysisIdUuids), MAX_SNAPSHOTS_PER_QUERY); - - deleteAnalysisDuplications(analysisUuidsPartitions); - - profiler.start("deleteAnalyses (events)"); - analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisEvents); - session.commit(); - profiler.stop(); - - profiler.start("deleteAnalyses (project_measures)"); - analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisMeasures); - session.commit(); - profiler.stop(); - - profiler.start("deleteAnalyses (snapshots)"); - analysisUuidsPartitions.forEach(purgeMapper::deleteAnalyses); - session.commit(); - profiler.stop(); - } - - public void purgeAnalyses(List<IdUuidPair> analysisUuids) { - List<List<String>> analysisUuidsPartitions = Lists.partition(IdUuidPairs.uuids(analysisUuids), MAX_SNAPSHOTS_PER_QUERY); - - deleteAnalysisDuplications(analysisUuidsPartitions); - - profiler.start("deleteSnapshotWastedMeasures (project_measures)"); - List<Long> metricIdsWithoutHistoricalData = purgeMapper.selectMetricIdsWithoutHistoricalData(); - analysisUuidsPartitions.stream() - .forEach(analysisUuidsPartition -> purgeMapper.deleteAnalysisWastedMeasures(analysisUuidsPartition, metricIdsWithoutHistoricalData)); - session.commit(); - profiler.stop(); - - profiler.start("updatePurgeStatusToOne (snapshots)"); - analysisUuidsPartitions.forEach(purgeMapper::updatePurgeStatusToOne); - session.commit(); - profiler.stop(); - } - - private void deleteAnalysisDuplications(List<List<String>> snapshotUuidsPartitions) { - profiler.start("deleteAnalysisDuplications (duplications_index)"); - snapshotUuidsPartitions.forEach(purgeMapper::deleteAnalysisDuplications); - session.commit(); - profiler.stop(); - } - - public void deleteFileSources(String rootUuid) { - profiler.start("deleteFileSources (file_sources)"); - purgeMapper.deleteFileSourcesByProjectUuid(rootUuid); - session.commit(); - profiler.stop(); - } - - public void deleteCeActivity(String rootUuid) { - profiler.start("deleteCeActivity (ce_activity)"); - purgeMapper.deleteCeActivityByProjectUuid(rootUuid); - session.commit(); - profiler.stop(); - } - - public void deleteWebhookDeliveries(String rootUuid) { - profiler.start("deleteWebhookDeliveries (webhook_deliveries)"); - purgeMapper.deleteWebhookDeliveriesByProjectUuid(rootUuid); - session.commit(); - profiler.stop(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeConfiguration.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeConfiguration.java deleted file mode 100644 index cc6fb0dbe18..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeConfiguration.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import com.google.common.annotations.VisibleForTesting; -import java.util.Collection; -import java.util.Date; -import javax.annotation.CheckForNull; -import org.apache.commons.lang.time.DateUtils; -import org.sonar.api.config.Settings; -import org.sonar.api.resources.Scopes; -import org.sonar.api.utils.System2; -import org.sonar.core.config.PurgeConstants; - -public class PurgeConfiguration { - - private final IdUuidPair rootProjectIdUuid; - private final String[] scopesWithoutHistoricalData; - private final int maxAgeInDaysOfClosedIssues; - private final System2 system2; - private final Collection<String> disabledComponentUuids; - - public PurgeConfiguration(IdUuidPair rootProjectId, String[] scopesWithoutHistoricalData, int maxAgeInDaysOfClosedIssues, - System2 system2, Collection<String> disabledComponentUuids) { - this.rootProjectIdUuid = rootProjectId; - this.scopesWithoutHistoricalData = scopesWithoutHistoricalData; - this.maxAgeInDaysOfClosedIssues = maxAgeInDaysOfClosedIssues; - this.system2 = system2; - this.disabledComponentUuids = disabledComponentUuids; - } - - public static PurgeConfiguration newDefaultPurgeConfiguration(Settings settings, IdUuidPair idUuidPair, Collection<String> disabledComponentUuids) { - String[] scopes = new String[] {Scopes.FILE}; - if (settings.getBoolean(PurgeConstants.PROPERTY_CLEAN_DIRECTORY)) { - scopes = new String[] {Scopes.DIRECTORY, Scopes.FILE}; - } - return new PurgeConfiguration(idUuidPair, scopes, settings.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES), System2.INSTANCE, disabledComponentUuids); - } - - public IdUuidPair rootProjectIdUuid() { - return rootProjectIdUuid; - } - - public String[] scopesWithoutHistoricalData() { - return scopesWithoutHistoricalData; - } - - public Collection<String> getDisabledComponentUuids() { - return disabledComponentUuids; - } - - @CheckForNull - public Date maxLiveDateOfClosedIssues() { - return maxLiveDateOfClosedIssues(new Date(system2.now())); - } - - @VisibleForTesting - @CheckForNull - Date maxLiveDateOfClosedIssues(Date now) { - if (maxAgeInDaysOfClosedIssues > 0) { - return DateUtils.addDays(now, -maxAgeInDaysOfClosedIssues); - } - - // delete all closed issues - return null; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeDao.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeDao.java deleted file mode 100644 index f8d4d6117ec..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeDao.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import com.google.common.collect.Lists; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.core.util.stream.Collectors; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.component.ComponentDao; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.ComponentTreeQuery; -import org.sonar.db.component.ComponentTreeQuery.Strategy; - -import static java.util.Collections.emptyList; -import static org.sonar.api.utils.DateUtils.dateToLong; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -/** - * @since 2.14 - */ -public class PurgeDao implements Dao { - private static final Logger LOG = Loggers.get(PurgeDao.class); - private static final String[] UNPROCESSED_STATUS = new String[] {"U"}; - - private final ComponentDao componentDao; - private final System2 system2; - - public PurgeDao(ComponentDao componentDao, System2 system2) { - this.componentDao = componentDao; - this.system2 = system2; - } - - public void purge(DbSession session, PurgeConfiguration conf, PurgeListener listener, PurgeProfiler profiler) { - PurgeMapper mapper = session.getMapper(PurgeMapper.class); - PurgeCommands commands = new PurgeCommands(session, mapper, profiler); - String rootUuid = conf.rootProjectIdUuid().getUuid(); - deleteAbortedAnalyses(rootUuid, commands); - deleteDataOfComponentsWithoutHistoricalData(session, rootUuid, conf.scopesWithoutHistoricalData(), commands); - purgeAnalyses(commands, rootUuid); - purgeDisabledComponents(session, conf.getDisabledComponentUuids(), listener); - deleteOldClosedIssues(conf, mapper, listener); - } - - private static void purgeAnalyses(PurgeCommands commands, String rootUuid) { - List<IdUuidPair> analysisUuids = commands.selectSnapshotIdUuids( - new PurgeSnapshotQuery() - .setComponentUuid(rootUuid) - .setIslast(false) - .setNotPurged(true)); - commands.purgeAnalyses(analysisUuids); - } - - private static void deleteOldClosedIssues(PurgeConfiguration conf, PurgeMapper mapper, PurgeListener listener) { - Date toDate = conf.maxLiveDateOfClosedIssues(); - String rootUuid = conf.rootProjectIdUuid().getUuid(); - List<String> issueKeys = mapper.selectOldClosedIssueKeys(rootUuid, dateToLong(toDate)); - executeLargeInputs(issueKeys, input -> { - mapper.deleteIssueChangesFromIssueKeys(input); - return emptyList(); - }); - executeLargeInputs(issueKeys, input -> { - mapper.deleteIssuesFromKeys(input); - return emptyList(); - }); - listener.onIssuesRemoval(rootUuid, issueKeys); - } - - private static void deleteAbortedAnalyses(String rootUuid, PurgeCommands commands) { - LOG.debug("<- Delete aborted builds"); - PurgeSnapshotQuery query = new PurgeSnapshotQuery() - .setIslast(false) - .setStatus(UNPROCESSED_STATUS) - .setComponentUuid(rootUuid); - commands.deleteAnalyses(query); - } - - private void deleteDataOfComponentsWithoutHistoricalData(DbSession dbSession, String rootUuid, String[] scopesWithoutHistoricalData, PurgeCommands purgeCommands) { - if (scopesWithoutHistoricalData.length == 0) { - return; - } - - List<String> analysisUuids = purgeCommands.selectSnapshotUuids( - new PurgeSnapshotQuery() - .setComponentUuid(rootUuid) - .setIslast(false) - .setNotPurged(true)); - List<String> componentWithoutHistoricalDataUuids = componentDao - .selectDescendants( - dbSession, - ComponentTreeQuery.builder() - .setBaseUuid(rootUuid) - .setQualifiers(Arrays.asList(scopesWithoutHistoricalData)) - .setStrategy(Strategy.LEAVES) - .build()) - .stream().map(ComponentDto::uuid) - .collect(Collectors.toList()); - - purgeCommands.deleteComponentMeasures(analysisUuids, componentWithoutHistoricalDataUuids); - } - - private void purgeDisabledComponents(DbSession session, Collection<String> uuids, PurgeListener listener) { - PurgeMapper mapper = mapper(session); - executeLargeInputs(uuids, - input -> { - mapper.deleteFileSourcesByUuid(input); - mapper.resolveComponentIssuesNotAlreadyResolved(input, system2.now()); - return emptyList(); - }); - - for (String componentUuid : uuids) { - listener.onComponentDisabling(componentUuid); - } - - session.commit(); - } - - public List<PurgeableAnalysisDto> selectPurgeableAnalyses(String componentUuid, DbSession session) { - List<PurgeableAnalysisDto> result = Lists.newArrayList(); - result.addAll(mapper(session).selectPurgeableAnalysesWithEvents(componentUuid)); - result.addAll(mapper(session).selectPurgeableAnalysesWithoutEvents(componentUuid)); - // sort by date - Collections.sort(result); - return result; - } - - public PurgeDao deleteProject(DbSession session, String uuid) { - PurgeProfiler profiler = new PurgeProfiler(); - PurgeCommands purgeCommands = new PurgeCommands(session, profiler); - deleteProject(uuid, mapper(session), purgeCommands); - return this; - } - - private static void deleteProject(String rootUuid, PurgeMapper mapper, PurgeCommands commands) { - List<IdUuidPair> childrenIds = mapper.selectComponentsByProjectUuid(rootUuid); - commands.deleteAnalyses(rootUuid); - commands.deleteComponents(childrenIds); - commands.deleteFileSources(rootUuid); - commands.deleteCeActivity(rootUuid); - commands.deleteWebhookDeliveries(rootUuid); - } - - public void deleteAnalyses(DbSession session, PurgeProfiler profiler, List<IdUuidPair> analysisIdUuids) { - new PurgeCommands(session, profiler).deleteAnalyses(analysisIdUuids); - } - - private static PurgeMapper mapper(DbSession session) { - return session.getMapper(PurgeMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeListener.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeListener.java deleted file mode 100644 index 4d5617fe102..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeListener.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import java.util.List; - -public interface PurgeListener { - - PurgeListener EMPTY = new PurgeListener() { - @Override - public void onComponentDisabling(String uuid) { - // do nothing - } - - @Override - public void onIssuesRemoval(String projectUuid, List<String> issueKeys) { - // do nothing - } - }; - - void onComponentDisabling(String uuid); - - void onIssuesRemoval(String projectUuid, List<String> issueKeys); -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeMapper.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeMapper.java deleted file mode 100644 index 71776d55c8d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeMapper.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import java.util.List; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; - -public interface PurgeMapper { - - List<IdUuidPair> selectAnalysisIdsAndUuids(PurgeSnapshotQuery query); - - /** - * Returns the list of components of a project from a project_uuid. The project itself is also returned. - */ - List<IdUuidPair> selectComponentsByProjectUuid(String projectUuid); - - void deleteAnalyses(@Param("analysisUuids") List<String> analysisUuids); - - void deleteAnalysisDuplications(@Param("analysisUuids") List<String> analysisUuids); - - void deleteAnalysisEvents(@Param("analysisUuids") List<String> analysisUuids); - - void deleteAnalysisMeasures(@Param("analysisUuids") List<String> analysisUuids); - - void deleteComponentMeasures(@Param("analysisUuids") List<String> analysisUuids, @Param("componentUuids") List<String> componentUuids); - - List<Long> selectMetricIdsWithoutHistoricalData(); - - void deleteAnalysisWastedMeasures(@Param("analysisUuids") List<String> analysisUuids, @Param("metricIds") List<Long> metricIds); - - void updatePurgeStatusToOne(@Param("analysisUuids") List<String> analysisUuid); - - void resolveComponentIssuesNotAlreadyResolved(@Param("componentUuids") List<String> componentUuids, @Param("dateAsLong") Long dateAsLong); - - void deleteComponentLinks(@Param("componentUuids") List<String> componentUuids); - - void deleteComponentProperties(@Param("componentIds") List<Long> componentIds); - - void deleteComponents(@Param("componentUuids") List<String> componentUuids); - - void deleteComponentGroupRoles(@Param("componentIds") List<Long> componentIds); - - void deleteComponentUserRoles(@Param("componentIds") List<Long> componentIds); - - void deleteComponentManualMeasures(@Param("componentUuids") List<String> componentUuids); - - void deleteComponentEvents(@Param("componentUuids") List<String> componentUuids); - - void deleteAuthors(@Param("resourceIds") List<Long> resourceIds); - - List<PurgeableAnalysisDto> selectPurgeableAnalysesWithEvents(@Param("componentUuid") String componentUuid); - - List<PurgeableAnalysisDto> selectPurgeableAnalysesWithoutEvents(@Param("componentUuid") String componentUuid); - - void deleteComponentIssueChanges(@Param("componentUuids") List<String> componentUuids); - - void deleteComponentIssues(@Param("componentUuids") List<String> componentUuids); - - List<String> selectOldClosedIssueKeys(@Param("projectUuid") String projectUuid, @Nullable @Param("toDate") Long toDate); - - void deleteIssuesFromKeys(@Param("keys") List<String> keys); - - void deleteIssueChangesFromIssueKeys(@Param("issueKeys") List<String> issueKeys); - - void deleteFileSourcesByProjectUuid(String rootProjectUuid); - - void deleteFileSourcesByUuid(@Param("fileUuids") List<String> fileUuids); - - void deleteCeActivityByProjectUuid(String projectUuid); - - void deleteWebhookDeliveriesByProjectUuid(@Param("projectUuid") String projectUuid); -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeProfiler.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeProfiler.java deleted file mode 100644 index 8c5c0541964..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeProfiler.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import com.google.common.annotations.VisibleForTesting; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.sonar.api.utils.TimeUtils; -import org.sonar.api.utils.log.Logger; - -public class PurgeProfiler { - - private Map<String, Long> durations = new HashMap<>(); - private long startTime; - private String currentTable; - private final Clock clock; - - public PurgeProfiler() { - this(new Clock()); - } - - @VisibleForTesting - PurgeProfiler(Clock clock) { - this.clock = clock; - } - - public void reset() { - durations.clear(); - } - - void start(String table) { - this.startTime = clock.now(); - this.currentTable = table; - } - - void stop() { - final Long cumulatedDuration; - if (durations.containsKey(currentTable)) { - cumulatedDuration = durations.get(currentTable); - } else { - cumulatedDuration = 0L; - } - durations.put(currentTable, cumulatedDuration + (clock.now() - startTime)); - } - - public void dump(long totalTime, Logger logger) { - List<Entry<String, Long>> data = new ArrayList<>(durations.entrySet()); - Collections.sort(data, (o1, o2) -> o2.getValue().compareTo(o1.getValue())); - double percent = totalTime / 100.0; - for (Entry<String, Long> entry : truncateList(data)) { - StringBuilder sb = new StringBuilder(); - sb.append(" o ").append(entry.getKey()).append(": ").append(TimeUtils.formatDuration(entry.getValue())) - .append(" (").append((int) (entry.getValue() / percent)).append("%)"); - logger.info(sb.toString()); - } - } - - private static List<Entry<String, Long>> truncateList(List<Entry<String, Long>> sortedFullList) { - int maxSize = 10; - List<Entry<String, Long>> result = new ArrayList<>(maxSize); - int i = 0; - for (Entry<String, Long> item : sortedFullList) { - if (i++ >= maxSize || item.getValue() == 0) { - return result; - } - result.add(item); - } - return result; - } - - static class Clock { - public long now() { - return System.currentTimeMillis(); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeSnapshotQuery.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeSnapshotQuery.java deleted file mode 100644 index 46bfecacbac..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeSnapshotQuery.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -public final class PurgeSnapshotQuery { - private String componentUuid; - private String[] status; - private Boolean islast; - private Boolean notPurged; - - public String[] getStatus() { - return status; - } - - public PurgeSnapshotQuery setStatus(String[] status) { - this.status = status; - return this; - } - - public Boolean getIslast() { - return islast; - } - - public PurgeSnapshotQuery setIslast(Boolean islast) { - this.islast = islast; - return this; - } - - public Boolean getNotPurged() { - return notPurged; - } - - public PurgeSnapshotQuery setNotPurged(Boolean notPurged) { - this.notPurged = notPurged; - return this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public PurgeSnapshotQuery setComponentUuid(String componentUuid) { - this.componentUuid = componentUuid; - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/PurgeableAnalysisDto.java b/sonar-db/src/main/java/org/sonar/db/purge/PurgeableAnalysisDto.java deleted file mode 100644 index 1d91f886174..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/PurgeableAnalysisDto.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge; - -import java.util.Date; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -/** - * Represents an analysis, aka. root snapshot, aka. snapshot of a project, developer or view - */ -public class PurgeableAnalysisDto implements Comparable<PurgeableAnalysisDto> { - private Date date; - private long analysisId; - private String analysisUuid; - private boolean hasEvents; - private boolean isLast; - - public Date getDate() { - return date; - } - - public PurgeableAnalysisDto setDate(Long aLong) { - this.date = new Date(aLong); - return this; - } - - public long getAnalysisId() { - return analysisId; - } - - public PurgeableAnalysisDto setAnalysisId(long analysisId) { - this.analysisId = analysisId; - return this; - } - - public String getAnalysisUuid() { - return analysisUuid; - } - - public PurgeableAnalysisDto setAnalysisUuid(String analysisUuid) { - this.analysisUuid = analysisUuid; - return this; - } - - public boolean hasEvents() { - return hasEvents; - } - - public PurgeableAnalysisDto setHasEvents(boolean b) { - this.hasEvents = b; - return this; - } - - public boolean isLast() { - return isLast; - } - - public PurgeableAnalysisDto setLast(boolean last) { - isLast = last; - return this; - } - - @Override - public int compareTo(PurgeableAnalysisDto other) { - return date.compareTo(other.date); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - PurgeableAnalysisDto that = (PurgeableAnalysisDto) o; - return analysisUuid.equals(that.analysisUuid); - } - - @Override - public int hashCode() { - return analysisUuid.hashCode(); - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/package-info.java b/sonar-db/src/main/java/org/sonar/db/purge/package-info.java deleted file mode 100644 index 3790dc89681..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.purge; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/DefaultPeriodCleaner.java b/sonar-db/src/main/java/org/sonar/db/purge/period/DefaultPeriodCleaner.java deleted file mode 100644 index 97f35d5958e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/DefaultPeriodCleaner.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Joiner; -import java.util.ArrayList; -import java.util.List; -import org.sonar.api.config.Settings; -import org.sonar.api.utils.DateUtils; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.core.util.stream.Collectors; -import org.sonar.db.DbSession; -import org.sonar.db.purge.IdUuidPair; -import org.sonar.db.purge.PurgeDao; -import org.sonar.db.purge.PurgeProfiler; -import org.sonar.db.purge.PurgeableAnalysisDto; - -import static org.sonar.core.util.stream.Collectors.toList; - -public class DefaultPeriodCleaner { - - private static final Logger LOG = Loggers.get(DefaultPeriodCleaner.class); - private final PurgeDao purgeDao; - private final PurgeProfiler profiler; - - public DefaultPeriodCleaner(PurgeDao purgeDao, PurgeProfiler profiler) { - this.purgeDao = purgeDao; - this.profiler = profiler; - } - - public void clean(DbSession session, String rootUuid, Settings settings) { - doClean(rootUuid, new Filters(settings).all(), session); - } - - @VisibleForTesting - void doClean(String rootUuid, List<Filter> filters, DbSession session) { - List<PurgeableAnalysisDto> history = new ArrayList<>(selectAnalysesOfComponent(rootUuid, session)); - for (Filter filter : filters) { - filter.log(); - history.removeAll(delete(rootUuid, filter.filter(history), session)); - } - } - - private List<PurgeableAnalysisDto> delete(String rootUuid, List<PurgeableAnalysisDto> snapshots, DbSession session) { - if (LOG.isDebugEnabled()) { - LOG.debug("<- Delete analyses of component {}: {}", - rootUuid, - Joiner.on(", ").join( - snapshots.stream() - .map(snapshot -> snapshot.getAnalysisUuid() + "@" + DateUtils.formatDateTime(snapshot.getDate())) - .collect(Collectors.toArrayList(snapshots.size())))); - } - purgeDao.deleteAnalyses( - session, profiler, - snapshots.stream().map(DefaultPeriodCleaner::toIdUuidPair).collect(Collectors.toList(snapshots.size()))); - return snapshots; - } - - private static IdUuidPair toIdUuidPair(PurgeableAnalysisDto snapshot) { - return new IdUuidPair(snapshot.getAnalysisId(), snapshot.getAnalysisUuid()); - } - - private List<PurgeableAnalysisDto> selectAnalysesOfComponent(String componentUuid, DbSession session) { - return purgeDao.selectPurgeableAnalyses(componentUuid, session); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/DeleteAllFilter.java b/sonar-db/src/main/java/org/sonar/db/purge/period/DeleteAllFilter.java deleted file mode 100644 index 8667bb8d3d1..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/DeleteAllFilter.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import com.google.common.collect.Lists; -import java.util.Date; -import java.util.List; -import org.sonar.api.utils.DateUtils; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.purge.PurgeableAnalysisDto; - -class DeleteAllFilter implements Filter { - private final Date before; - - public DeleteAllFilter(Date before) { - this.before = before; - } - - @Override - public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { - List<PurgeableAnalysisDto> result = Lists.newArrayList(); - for (PurgeableAnalysisDto snapshot : history) { - if (snapshot.getDate().before(before)) { - result.add(snapshot); - } - } - return result; - } - - @Override - public void log() { - Loggers.get(getClass()).debug("-> Delete data prior to: {}", DateUtils.formatDate(before)); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/Filter.java b/sonar-db/src/main/java/org/sonar/db/purge/period/Filter.java deleted file mode 100644 index f501ade118e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/Filter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import java.util.List; -import org.sonar.db.purge.PurgeableAnalysisDto; - -interface Filter { - List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> snapshots); - - void log(); -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/Filters.java b/sonar-db/src/main/java/org/sonar/db/purge/period/Filters.java deleted file mode 100644 index fab44eaa2cc..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/Filters.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import com.google.common.collect.Lists; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import org.apache.commons.lang.time.DateUtils; -import org.sonar.api.config.Settings; -import org.sonar.core.config.PurgeConstants; - -class Filters { - private final List<Filter> all = Lists.newArrayList(); - - Filters(Settings settings) { - Date dateToStartKeepingOneSnapshotByDay = getDateFromHours(settings, PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY); - Date dateToStartKeepingOneSnapshotByWeek = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK); - Date dateToStartKeepingOneSnapshotByMonth = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH); - Date dateToStartDeletingAllSnapshots = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS); - - all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByWeek, dateToStartKeepingOneSnapshotByDay, Calendar.DAY_OF_YEAR, "day")); - all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByMonth, dateToStartKeepingOneSnapshotByWeek, Calendar.WEEK_OF_YEAR, "week")); - all.add(new KeepOneFilter(dateToStartDeletingAllSnapshots, dateToStartKeepingOneSnapshotByMonth, Calendar.MONTH, "month")); - all.add(new DeleteAllFilter(dateToStartDeletingAllSnapshots)); - } - - static Date getDateFromWeeks(Settings settings, String propertyKey) { - int weeks = settings.getInt(propertyKey); - return DateUtils.addWeeks(new Date(), -weeks); - } - - static Date getDateFromHours(Settings settings, String propertyKey) { - int hours = settings.getInt(propertyKey); - return DateUtils.addHours(new Date(), -hours); - } - - List<Filter> all() { - return all; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/Interval.java b/sonar-db/src/main/java/org/sonar/db/purge/period/Interval.java deleted file mode 100644 index fab5a86f90b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/Interval.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import com.google.common.collect.Lists; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import org.apache.commons.lang.time.DateUtils; -import org.sonar.db.purge.PurgeableAnalysisDto; - -final class Interval { - List<PurgeableAnalysisDto> snapshots = Lists.newArrayList(); - - void add(PurgeableAnalysisDto snapshot) { - snapshots.add(snapshot); - } - - List<PurgeableAnalysisDto> get() { - return snapshots; - } - - int count() { - return snapshots.size(); - } - - static List<Interval> group(List<PurgeableAnalysisDto> snapshots, Date start, Date end, int calendarField) { - List<Interval> intervals = Lists.newArrayList(); - - GregorianCalendar calendar = new GregorianCalendar(); - int lastYear = -1; - int lastFieldValue = -1; - Interval currentInterval = null; - - for (PurgeableAnalysisDto snapshot : snapshots) { - if (!DateUtils.isSameDay(start, snapshot.getDate()) && snapshot.getDate().after(start) && - (snapshot.getDate().before(end) || DateUtils.isSameDay(end, snapshot.getDate()))) { - calendar.setTime(snapshot.getDate()); - int currentFieldValue = calendar.get(calendarField); - int currentYear = calendar.get(Calendar.YEAR); - if (lastYear != currentYear || lastFieldValue != currentFieldValue) { - currentInterval = new Interval(); - intervals.add(currentInterval); - } - lastFieldValue = currentFieldValue; - lastYear = currentYear; - if (currentInterval != null) { - currentInterval.add(snapshot); - } - } - } - return intervals; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/KeepOneFilter.java b/sonar-db/src/main/java/org/sonar/db/purge/period/KeepOneFilter.java deleted file mode 100644 index e67a4c9657a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/KeepOneFilter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.purge.period; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Lists; -import java.util.Date; -import java.util.List; -import org.sonar.api.utils.DateUtils; -import org.sonar.api.utils.log.Loggers; -import org.sonar.db.purge.PurgeableAnalysisDto; - -class KeepOneFilter implements Filter { - - private final Date start; - private final Date end; - private final int dateField; - private final String label; - - KeepOneFilter(Date start, Date end, int calendarField, String label) { - this.start = start; - this.end = end; - this.dateField = calendarField; - this.label = label; - } - - @Override - public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { - List<Interval> intervals = Interval.group(history, start, end, dateField); - List<PurgeableAnalysisDto> result = Lists.newArrayList(); - for (Interval interval : intervals) { - appendSnapshotsToDelete(interval, result); - } - - return result; - } - - @Override - public void log() { - Loggers.get(getClass()).debug("-> Keep one snapshot per {} between {} and {}", label, DateUtils.formatDate(start), DateUtils.formatDate(end)); - } - - private void appendSnapshotsToDelete(Interval interval, List<PurgeableAnalysisDto> toDelete) { - if (interval.count() > 1) { - List<PurgeableAnalysisDto> deletables = Lists.newArrayList(); - List<PurgeableAnalysisDto> toKeep = Lists.newArrayList(); - for (PurgeableAnalysisDto snapshot : interval.get()) { - if (isDeletable(snapshot)) { - deletables.add(snapshot); - } else { - toKeep.add(snapshot); - } - } - - if (!toKeep.isEmpty()) { - toDelete.addAll(deletables); - - } else if (deletables.size() > 1) { - // keep last snapshot - toDelete.addAll(deletables.subList(0, deletables.size() - 1)); - } - } - } - - @VisibleForTesting - static boolean isDeletable(PurgeableAnalysisDto snapshot) { - return !snapshot.isLast() && !snapshot.hasEvents(); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/purge/period/package-info.java b/sonar-db/src/main/java/org/sonar/db/purge/period/package-info.java deleted file mode 100644 index 47e3bd1ca34..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/purge/period/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.purge.period; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociation.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociation.java deleted file mode 100644 index 9237523a6f7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociation.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -public class ProjectQgateAssociation { - - private Long id; - private String name; - private boolean isMember; - - public Long id() { - return id; - } - - public ProjectQgateAssociation setId(Long id) { - this.id = id; - return this; - } - - public String name() { - return name; - } - - public ProjectQgateAssociation setName(String name) { - this.name = name; - return this; - } - - public boolean isMember() { - return isMember; - } - - public ProjectQgateAssociation setMember(boolean isMember) { - this.isMember = isMember; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ProjectQgateAssociation that = (ProjectQgateAssociation) o; - return name.equals(that.name); - } - - @Override - public int hashCode() { - return name.hashCode(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDao.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDao.java deleted file mode 100644 index a45e4ebba52..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDao.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.List; -import java.util.Optional; -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -public class ProjectQgateAssociationDao implements Dao { - - public List<ProjectQgateAssociationDto> selectProjects(DbSession dbSession, ProjectQgateAssociationQuery query) { - return mapper(dbSession).selectProjects(query); - } - - /** - * @return quality gate id if a specific Quality Gate has been defined for the given component id. <br> - * Returns <code>{@link Optional#empty()}</code> otherwise (ex: default quality gate applies) - */ - public Optional<Long> selectQGateIdByComponentId(DbSession dbSession, long componentId) { - String id = mapper(dbSession).selectQGateIdByComponentId(componentId); - - return id == null ? Optional.empty() : Optional.of(Long.valueOf(id)); - } - - private static ProjectQgateAssociationMapper mapper(SqlSession session) { - return session.getMapper(ProjectQgateAssociationMapper.class); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDto.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDto.java deleted file mode 100644 index e016353090c..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDto.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -/** - * @since 4.3 - */ -public class ProjectQgateAssociationDto { - - private Long id; - private String name; - private String gateId; - - public Long getId() { - return id; - } - - public ProjectQgateAssociationDto setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public ProjectQgateAssociationDto setName(String name) { - this.name = name; - return this; - } - - @CheckForNull - public String getGateId() { - return gateId; - } - - public ProjectQgateAssociationDto setGateId(@Nullable String gateId) { - this.gateId = gateId; - return this; - } - - public ProjectQgateAssociation toQgateAssociation() { - return new ProjectQgateAssociation() - .setId(id) - .setName(name) - .setMember(gateId != null); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationMapper.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationMapper.java deleted file mode 100644 index 3abffca0e40..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface ProjectQgateAssociationMapper { - - List<ProjectQgateAssociationDto> selectProjects(@Param("query") ProjectQgateAssociationQuery query); - - @CheckForNull - String selectQGateIdByComponentId(long componentId); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationQuery.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationQuery.java deleted file mode 100644 index d60d7bb9a11..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationQuery.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import java.util.Locale; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.WildcardPosition; - -public class ProjectQgateAssociationQuery { - - public static final int DEFAULT_PAGE_INDEX = 1; - public static final int DEFAULT_PAGE_SIZE = 100; - - public static final String ANY = "all"; - public static final String IN = "selected"; - public static final String OUT = "deselected"; - public static final Set<String> AVAILABLE_MEMBERSHIP = ImmutableSet.of(ANY, IN, OUT); - - private final String gateId; - private final String membership; - - private final String projectSearch; - - // for internal use in MyBatis - private final String projectSearchUpperLikeSql; - - // max results per page - private final int pageSize; - - // index of selected page. Start with 1. - private final int pageIndex; - - private ProjectQgateAssociationQuery(Builder builder) { - this.gateId = builder.gateId; - this.membership = builder.membership; - this.projectSearch = builder.projectSearch; - if (this.projectSearch == null) { - this.projectSearchUpperLikeSql = null; - } else { - this.projectSearchUpperLikeSql = DatabaseUtils.buildLikeValue(projectSearch.toUpperCase(Locale.ENGLISH), WildcardPosition.BEFORE_AND_AFTER); - } - - this.pageSize = builder.pageSize; - this.pageIndex = builder.pageIndex; - } - - public String gateId() { - return gateId; - } - - @CheckForNull - public String membership() { - return membership; - } - - /** - * Search for projects containing a given string - */ - @CheckForNull - public String projectSearch() { - return projectSearch; - } - - public int pageSize() { - return pageSize; - } - - public int pageIndex() { - return pageIndex; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String gateId; - private String membership; - private String projectSearch; - - private Integer pageIndex = DEFAULT_PAGE_INDEX; - private Integer pageSize = DEFAULT_PAGE_SIZE; - - private Builder() { - } - - public Builder gateId(String gateId) { - this.gateId = gateId; - return this; - } - - public Builder membership(@Nullable String membership) { - this.membership = membership; - return this; - } - - public Builder projectSearch(@Nullable String s) { - this.projectSearch = StringUtils.defaultIfBlank(s, null); - return this; - } - - public Builder pageSize(@Nullable Integer i) { - this.pageSize = i; - return this; - } - - public Builder pageIndex(@Nullable Integer i) { - this.pageIndex = i; - return this; - } - - private void initMembership() { - if (membership == null) { - membership = ProjectQgateAssociationQuery.ANY; - } else { - Preconditions.checkArgument(AVAILABLE_MEMBERSHIP.contains(membership), - "Membership is not valid (got " + membership + "). Available values are " + AVAILABLE_MEMBERSHIP); - } - } - - private void initPageSize() { - if (pageSize == null) { - pageSize = DEFAULT_PAGE_SIZE; - } - } - - private void initPageIndex() { - if (pageIndex == null) { - pageIndex = DEFAULT_PAGE_INDEX; - } - Preconditions.checkArgument(pageIndex > 0, "Page index must be greater than 0 (got " + pageIndex + ")"); - } - - public ProjectQgateAssociationQuery build() { - Preconditions.checkNotNull(gateId, "Gate ID cannot be null."); - initMembership(); - initPageIndex(); - initPageSize(); - return new ProjectQgateAssociationQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDao.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDao.java deleted file mode 100644 index 249d726cc92..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDao.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.Collection; -import java.util.Date; -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.MyBatis; - -/** - * @since 4.3 - */ -public class QualityGateConditionDao implements Dao { - - private final MyBatis myBatis; - - public QualityGateConditionDao(MyBatis myBatis) { - this.myBatis = myBatis; - } - - public void insert(QualityGateConditionDto newQualityGate) { - SqlSession session = myBatis.openSession(false); - try { - insert(newQualityGate, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void insert(QualityGateConditionDto newQualityGate, SqlSession session) { - mapper(session).insert(newQualityGate.setCreatedAt(new Date())); - } - - public Collection<QualityGateConditionDto> selectForQualityGate(long qGateId) { - SqlSession session = myBatis.openSession(false); - try { - return selectForQualityGate(qGateId, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public Collection<QualityGateConditionDto> selectForQualityGate(long qGateId, SqlSession session) { - return mapper(session).selectForQualityGate(qGateId); - } - - public QualityGateConditionDto selectById(long id) { - SqlSession session = myBatis.openSession(false); - try { - return selectById(id, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public QualityGateConditionDto selectById(long id, SqlSession session) { - return mapper(session).selectById(id); - } - - public void delete(QualityGateConditionDto qGate) { - SqlSession session = myBatis.openSession(false); - try { - delete(qGate, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void delete(QualityGateConditionDto qGate, SqlSession session) { - mapper(session).delete(qGate.getId()); - } - - public void update(QualityGateConditionDto qGate) { - SqlSession session = myBatis.openSession(false); - try { - update(qGate, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void update(QualityGateConditionDto qGate, SqlSession session) { - mapper(session).update(qGate.setUpdatedAt(new Date())); - } - - public void deleteConditionsWithInvalidMetrics() { - SqlSession session = myBatis.openSession(false); - try { - deleteConditionsWithInvalidMetrics(session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void deleteConditionsWithInvalidMetrics(SqlSession session) { - mapper(session).deleteConditionsWithInvalidMetrics(); - } - - private static QualityGateConditionMapper mapper(SqlSession session) { - return session.getMapper(QualityGateConditionMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDto.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDto.java deleted file mode 100644 index d3d0bbe5bac..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDto.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.measures.Metric.ValueType; - -/** - * @since 4.3 - */ -public class QualityGateConditionDto { - - public static final String OPERATOR_EQUALS = "EQ"; - - public static final String OPERATOR_NOT_EQUALS = "NE"; - - public static final String OPERATOR_GREATER_THAN = "GT"; - - public static final String OPERATOR_LESS_THAN = "LT"; - - public static final List<String> ALL_OPERATORS = ImmutableList.of( - OPERATOR_LESS_THAN, - OPERATOR_GREATER_THAN, - OPERATOR_EQUALS, - OPERATOR_NOT_EQUALS); - - private static final List<String> NUMERIC_OPERATORS = ImmutableList.of( - OPERATOR_LESS_THAN, - OPERATOR_GREATER_THAN, - OPERATOR_EQUALS, - OPERATOR_NOT_EQUALS); - - private static final List<String> STRING_OPERATORS = ImmutableList.of( - OPERATOR_EQUALS, - OPERATOR_NOT_EQUALS, - OPERATOR_LESS_THAN, - OPERATOR_GREATER_THAN); - - private static final List<String> LEVEL_OPERATORS = ImmutableList.of( - OPERATOR_EQUALS, - OPERATOR_NOT_EQUALS); - - private static final List<String> BOOLEAN_OPERATORS = ImmutableList.of( - OPERATOR_EQUALS); - - private static final List<String> RATING_OPERATORS = ImmutableList.of( - OPERATOR_GREATER_THAN); - - private static final Map<ValueType, List<String>> OPERATORS_BY_TYPE = ImmutableMap.<ValueType, List<String>>builder() - .put(ValueType.BOOL, BOOLEAN_OPERATORS) - .put(ValueType.LEVEL, LEVEL_OPERATORS) - .put(ValueType.STRING, STRING_OPERATORS) - .put(ValueType.INT, NUMERIC_OPERATORS) - .put(ValueType.FLOAT, NUMERIC_OPERATORS) - .put(ValueType.PERCENT, NUMERIC_OPERATORS) - .put(ValueType.MILLISEC, NUMERIC_OPERATORS) - .put(ValueType.RATING, RATING_OPERATORS) - .put(ValueType.WORK_DUR, NUMERIC_OPERATORS) - .build(); - - private long id; - - private long qualityGateId; - - private long metricId; - - private String metricKey; - - private Integer period; - - private String operator; - - private String warningThreshold; - - private String errorThreshold; - - private Date createdAt; - - private Date updatedAt; - - public long getId() { - return id; - } - - public QualityGateConditionDto setId(long id) { - this.id = id; - return this; - } - - public long getQualityGateId() { - return qualityGateId; - } - - public QualityGateConditionDto setQualityGateId(long qualityGateId) { - this.qualityGateId = qualityGateId; - return this; - } - - public long getMetricId() { - return metricId; - } - - public QualityGateConditionDto setMetricId(long metricId) { - this.metricId = metricId; - return this; - } - - @CheckForNull - public String getMetricKey() { - return metricKey; - } - - public QualityGateConditionDto setMetricKey(String metricKey) { - this.metricKey = metricKey; - return this; - } - - @CheckForNull - public Integer getPeriod() { - return period; - } - - public QualityGateConditionDto setPeriod(@Nullable Integer period) { - this.period = period; - return this; - } - - public String getOperator() { - return operator; - } - - public QualityGateConditionDto setOperator(String operator) { - this.operator = operator; - return this; - } - - public String getWarningThreshold() { - return warningThreshold; - } - - public QualityGateConditionDto setWarningThreshold(@Nullable String warningThreshold) { - this.warningThreshold = warningThreshold; - return this; - } - - public String getErrorThreshold() { - return errorThreshold; - } - - public QualityGateConditionDto setErrorThreshold(@Nullable String errorThreshold) { - this.errorThreshold = errorThreshold; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public QualityGateConditionDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public QualityGateConditionDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public static boolean isOperatorAllowed(String operator, ValueType metricType) { - return getOperatorsForType(metricType).contains(operator); - } - - public static Collection<String> getOperatorsForType(ValueType metricType) { - if (OPERATORS_BY_TYPE.containsKey(metricType)) { - return OPERATORS_BY_TYPE.get(metricType); - } else { - return Collections.emptySet(); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionMapper.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionMapper.java deleted file mode 100644 index 2a11deb70a1..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateConditionMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.List; - -public interface QualityGateConditionMapper { - - void insert(QualityGateConditionDto newCondition); - - List<QualityGateConditionDto> selectForQualityGate(long qGateId); - - void update(QualityGateConditionDto newCondition); - - QualityGateConditionDto selectById(long id); - - void delete(long id); - - void deleteConditionsWithInvalidMetrics(); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDao.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDao.java deleted file mode 100644 index a7d0a409b88..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDao.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.Collection; -import java.util.Date; -import javax.annotation.CheckForNull; -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; - -public class QualityGateDao implements Dao{ - - private final MyBatis myBatis; - - public QualityGateDao(MyBatis myBatis) { - this.myBatis = myBatis; - } - - public void insert(QualityGateDto newQualityGate) { - DbSession session = myBatis.openSession(false); - try { - insert(session, newQualityGate); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public QualityGateDto insert(DbSession session, QualityGateDto newQualityGate) { - mapper(session).insert(newQualityGate.setCreatedAt(new Date())); - - return newQualityGate; - } - - public Collection<QualityGateDto> selectAll() { - SqlSession session = myBatis.openSession(false); - try { - return selectAll(session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public Collection<QualityGateDto> selectAll(SqlSession session) { - return mapper(session).selectAll(); - } - - @CheckForNull - public QualityGateDto selectByName(String name) { - SqlSession session = myBatis.openSession(false); - try { - return selectByName(session, name); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityGateDto selectByName(SqlSession session, String name) { - return mapper(session).selectByName(name); - } - - @CheckForNull - public QualityGateDto selectById(long id) { - SqlSession session = myBatis.openSession(false); - try { - return selectById(session, id); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityGateDto selectById(SqlSession session, long id) { - return mapper(session).selectById(id); - } - - public void delete(QualityGateDto qGate) { - SqlSession session = myBatis.openSession(false); - try { - delete(qGate, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void delete(QualityGateDto qGate, SqlSession session) { - mapper(session).delete(qGate.getId()); - } - - public void update(QualityGateDto qGate) { - SqlSession session = myBatis.openSession(false); - try { - update(qGate, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void update(QualityGateDto qGate, SqlSession session) { - mapper(session).update(qGate.setUpdatedAt(new Date())); - } - - private static QualityGateMapper mapper(SqlSession session) { - return session.getMapper(QualityGateMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDto.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDto.java deleted file mode 100644 index 98832bbfaae..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateDto.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.Date; - -/** - * @since 4.3 - */ -public class QualityGateDto { - - private Long id; - - private String name; - - private Date createdAt; - - private Date updatedAt; - - public Long getId() { - return id; - } - - public QualityGateDto setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public QualityGateDto setName(String name) { - this.name = name; - return this; - } - - public Date getCreatedAt() { - return createdAt; - } - - public QualityGateDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - return this; - } - - public Date getUpdatedAt() { - return updatedAt; - } - - public QualityGateDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateMapper.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateMapper.java deleted file mode 100644 index 77548197d02..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/QualityGateMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.List; - -public interface QualityGateMapper { - - void insert(QualityGateDto qualityGate); - - List<QualityGateDto> selectAll(); - - QualityGateDto selectByName(String name); - - QualityGateDto selectById(long id); - - void delete(long id); - - void update(QualityGateDto qGate); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualitygate/package-info.java b/sonar-db/src/main/java/org/sonar/db/qualitygate/package-info.java deleted file mode 100644 index dccff66979b..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualitygate/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.qualitygate; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDao.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDao.java deleted file mode 100644 index 903221521ce..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDao.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import java.util.List; -import javax.annotation.CheckForNull; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class ActiveRuleDao implements Dao { - - private static final String QUALITY_PROFILE_IS_NOT_PERSISTED = "Quality profile is not persisted (missing id)"; - private static final String RULE_IS_NOT_PERSISTED = "Rule is not persisted"; - private static final String RULE_PARAM_IS_NOT_PERSISTED = "Rule param is not persisted"; - private static final String ACTIVE_RULE_KEY_CANNOT_BE_NULL = "ActiveRuleKey cannot be null"; - private static final String ACTIVE_RULE_IS_NOT_PERSISTED = "ActiveRule is not persisted"; - private static final String ACTIVE_RULE_IS_ALREADY_PERSISTED = "ActiveRule is already persisted"; - private static final String ACTIVE_RULE_PARAM_IS_NOT_PERSISTED = "ActiveRuleParam is not persisted"; - private static final String ACTIVE_RULE_PARAM_IS_ALREADY_PERSISTED = "ActiveRuleParam is already persisted"; - private static final String PARAMETER_NAME_CANNOT_BE_NULL = "ParameterName cannot be null"; - - public Optional<ActiveRuleDto> selectByKey(DbSession session, ActiveRuleKey key) { - return Optional.fromNullable(mapper(session).selectByKey(key.qProfile(), key.ruleKey().repository(), key.ruleKey().rule())); - } - - public ActiveRuleDto selectOrFailByKey(DbSession session, ActiveRuleKey key) { - Optional<ActiveRuleDto> activeRule = selectByKey(session, key); - if (activeRule.isPresent()) { - return activeRule.get(); - } - throw new RowNotFoundException(String.format("Active rule with key '%s' does not exist", key)); - } - - public List<ActiveRuleDto> selectByKeys(DbSession dbSession, List<ActiveRuleKey> keys) { - return executeLargeInputs(keys, mapper(dbSession)::selectByKeys); - } - - public List<ActiveRuleDto> selectByRuleId(DbSession dbSession, int ruleId) { - return mapper(dbSession).selectByRuleId(ruleId); - } - - public List<ActiveRuleDto> selectByRuleIds(DbSession dbSession, List<Integer> ids) { - return executeLargeInputs(ids, mapper(dbSession)::selectByRuleIds); - } - - // TODO As it's only used by MediumTest, it should be replaced by DbTester.countRowsOfTable() - public List<ActiveRuleDto> selectAll(DbSession dbSession) { - return mapper(dbSession).selectAll(); - } - - /** - * Active rule on removed rule are NOT returned - */ - public List<ActiveRuleDto> selectByProfileKey(DbSession session, String profileKey) { - return mapper(session).selectByProfileKey(profileKey); - } - - public ActiveRuleDto insert(DbSession session, ActiveRuleDto item) { - Preconditions.checkArgument(item.getProfileId() != null, QUALITY_PROFILE_IS_NOT_PERSISTED); - Preconditions.checkArgument(item.getRuleId() != null, RULE_IS_NOT_PERSISTED); - Preconditions.checkArgument(item.getId() == null, ACTIVE_RULE_IS_ALREADY_PERSISTED); - mapper(session).insert(item); - return item; - } - - public ActiveRuleDto update(DbSession session, ActiveRuleDto item) { - Preconditions.checkArgument(item.getProfileId() != null, QUALITY_PROFILE_IS_NOT_PERSISTED); - Preconditions.checkArgument(item.getRuleId() != null, ActiveRuleDao.RULE_IS_NOT_PERSISTED); - Preconditions.checkArgument(item.getId() != null, ACTIVE_RULE_IS_NOT_PERSISTED); - mapper(session).update(item); - return item; - } - - public void delete(DbSession session, ActiveRuleKey key) { - Optional<ActiveRuleDto> activeRule = selectByKey(session, key); - if (activeRule.isPresent()) { - mapper(session).deleteParameters(activeRule.get().getId()); - mapper(session).delete(activeRule.get().getId()); - } - } - - /** - * Nested DTO ActiveRuleParams - */ - - public List<ActiveRuleParamDto> selectParamsByActiveRuleId(DbSession dbSession, Integer activeRuleId) { - return mapper(dbSession).selectParamsByActiveRuleId(activeRuleId); - } - - public List<ActiveRuleParamDto> selectParamsByActiveRuleIds(final DbSession dbSession, List<Integer> activeRuleIds) { - return executeLargeInputs(activeRuleIds, mapper(dbSession)::selectParamsByActiveRuleIds); - } - - @CheckForNull - public ActiveRuleParamDto selectParamByKeyAndName(ActiveRuleKey key, String name, DbSession session) { - Preconditions.checkNotNull(key, ACTIVE_RULE_KEY_CANNOT_BE_NULL); - Preconditions.checkNotNull(name, PARAMETER_NAME_CANNOT_BE_NULL); - Optional<ActiveRuleDto> activeRule = selectByKey(session, key); - if (activeRule.isPresent()) { - return mapper(session).selectParamByActiveRuleAndKey(activeRule.get().getId(), name); - } - return null; - } - - public List<ActiveRuleParamDto> selectAllParams(DbSession dbSession) { - return mapper(dbSession).selectAllParams(); - } - - public ActiveRuleParamDto insertParam(DbSession session, ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam) { - Preconditions.checkArgument(activeRule.getId() != null, ACTIVE_RULE_IS_NOT_PERSISTED); - Preconditions.checkArgument(activeRuleParam.getId() == null, ACTIVE_RULE_PARAM_IS_ALREADY_PERSISTED); - Preconditions.checkNotNull(activeRuleParam.getRulesParameterId(), RULE_PARAM_IS_NOT_PERSISTED); - - activeRuleParam.setActiveRuleId(activeRule.getId()); - mapper(session).insertParameter(activeRuleParam); - return activeRuleParam; - } - - public void updateParam(DbSession session, ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam) { - Preconditions.checkNotNull(activeRule.getId(), ACTIVE_RULE_IS_NOT_PERSISTED); - Preconditions.checkNotNull(activeRuleParam.getId(), ACTIVE_RULE_PARAM_IS_NOT_PERSISTED); - mapper(session).updateParameter(activeRuleParam); - } - - public void deleteParam(DbSession session, ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam) { - Preconditions.checkNotNull(activeRule.getId(), ACTIVE_RULE_IS_NOT_PERSISTED); - Preconditions.checkNotNull(activeRuleParam.getId(), ACTIVE_RULE_PARAM_IS_NOT_PERSISTED); - deleteParamById(session, activeRuleParam.getId()); - } - - public void deleteParamById(DbSession session, int id){ - mapper(session).deleteParameter(id); - } - - public void deleteParamByKeyAndName(DbSession session, ActiveRuleKey key, String param) { - // TODO SQL rewrite to delete by key - Optional<ActiveRuleDto> activeRule = selectByKey(session, key); - if (activeRule.isPresent()) { - ActiveRuleParamDto activeRuleParam = mapper(session).selectParamByActiveRuleAndKey(activeRule.get().getId(), param); - if (activeRuleParam != null) { - mapper(session).deleteParameter(activeRuleParam.getId()); - } - } - } - - public void deleteParamsByRuleParam(DbSession dbSession, int ruleId, String paramKey) { - List<ActiveRuleDto> activeRules = selectByRuleId(dbSession, ruleId); - for (ActiveRuleDto activeRule : activeRules) { - for (ActiveRuleParamDto activeParam : selectParamsByActiveRuleId(dbSession, activeRule.getId())) { - if (activeParam.getKey().equals(paramKey)) { - deleteParam(dbSession, activeRule, activeParam); - } - } - } - } - - private static ActiveRuleMapper mapper(DbSession session) { - return session.getMapper(ActiveRuleMapper.class); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDto.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDto.java deleted file mode 100644 index c52a599a84d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDto.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.ActiveRule; -import org.sonar.db.rule.RuleDto; -import org.sonar.db.rule.SeverityUtil; - -import static java.util.Objects.requireNonNull; - -public class ActiveRuleDto { - - public static final String INHERITED = ActiveRule.INHERITED; - public static final String OVERRIDES = ActiveRule.OVERRIDES; - - private Integer id; - private Integer profileId; - private Integer ruleId; - private Integer severity; - private String inheritance; - - private long createdAt; - private long updatedAt; - - // These fields do not exists in db, it's only retrieve by joins - private String repository; - private String ruleField; - private String profileKey; - - public ActiveRuleDto setKey(ActiveRuleKey key) { - this.repository = key.ruleKey().repository(); - this.ruleField = key.ruleKey().rule(); - this.profileKey = key.qProfile(); - return this; - } - - public ActiveRuleKey getKey() { - return ActiveRuleKey.of(profileKey, RuleKey.of(repository, ruleField)); - } - - public Integer getId() { - return id; - } - - public ActiveRuleDto setId(Integer id) { - this.id = id; - return this; - } - - public Integer getProfileId() { - return profileId; - } - - public ActiveRuleDto setProfileId(Integer profileId) { - this.profileId = profileId; - return this; - } - - public Integer getRuleId() { - return ruleId; - } - - public ActiveRuleDto setRuleId(Integer ruleId) { - this.ruleId = ruleId; - return this; - } - - public Integer getSeverity() { - return severity; - } - - public String getSeverityString() { - return SeverityUtil.getSeverityFromOrdinal(severity); - } - - public ActiveRuleDto setSeverity(Integer severity) { - this.severity = severity; - return this; - } - - public ActiveRuleDto setSeverity(String severity) { - this.severity = SeverityUtil.getOrdinalFromSeverity(severity); - return this; - } - - @CheckForNull - public String getInheritance() { - return inheritance; - } - - public ActiveRuleDto setInheritance(@Nullable String inheritance) { - this.inheritance = inheritance; - return this; - } - - public boolean isInherited() { - return StringUtils.equals(INHERITED, inheritance); - } - - public boolean doesOverride() { - return StringUtils.equals(OVERRIDES, inheritance); - } - - public long getUpdatedAt() { - return updatedAt; - } - - public ActiveRuleDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public ActiveRuleDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public static ActiveRuleDto createFor(QualityProfileDto profileDto, RuleDto ruleDto) { - requireNonNull(profileDto.getId(), "Profile is not persisted"); - requireNonNull(ruleDto.getId(), "Rule is not persisted"); - ActiveRuleDto dto = new ActiveRuleDto(); - dto.setProfileId(profileDto.getId()); - dto.setRuleId(ruleDto.getId()); - dto.setKey(ActiveRuleKey.of(profileDto.getKee(), ruleDto.getKey())); - return dto; - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleKey.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleKey.java deleted file mode 100644 index 299493bd9f6..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleKey.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import com.google.common.base.Preconditions; -import java.io.Serializable; -import org.sonar.api.rule.RuleKey; - -/** - * - * @since 4.4 - */ -public class ActiveRuleKey implements Serializable, Comparable<ActiveRuleKey> { - - private final String qualityProfileKey; - private final RuleKey ruleKey; - - protected ActiveRuleKey(String qualityProfileKey, RuleKey ruleKey) { - this.qualityProfileKey = qualityProfileKey; - this.ruleKey = ruleKey; - } - - /** - * Create a key. Parameters are NOT null. - */ - public static ActiveRuleKey of(String qualityProfileKey, RuleKey ruleKey) { - Preconditions.checkNotNull(qualityProfileKey, "QProfile is missing"); - Preconditions.checkNotNull(ruleKey, "RuleKey is missing"); - return new ActiveRuleKey(qualityProfileKey, ruleKey); - } - - /** - * Create a key from a string representation (see {@link #toString()}. An {@link IllegalArgumentException} is raised - * if the format is not valid. - */ - public static ActiveRuleKey parse(String s) { - Preconditions.checkArgument(s.split(":").length >= 3, "Bad format of activeRule key: " + s); - int semiColonPos = s.indexOf(':'); - String key = s.substring(0, semiColonPos); - String ruleKey = s.substring(semiColonPos + 1); - return ActiveRuleKey.of(key, RuleKey.parse(ruleKey)); - } - - /** - * Never null - */ - public RuleKey ruleKey() { - return ruleKey; - } - - /** - * Never null - */ - public String qProfile() { - return qualityProfileKey; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ActiveRuleKey activeRuleKey = (ActiveRuleKey) o; - if (!qualityProfileKey.equals(activeRuleKey.qualityProfileKey)) { - return false; - } - if (!ruleKey.equals(activeRuleKey.ruleKey)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - int result = qualityProfileKey.hashCode(); - result = 31 * result + ruleKey.hashCode(); - return result; - } - - /** - * Format is "qprofile:rule", for example "12345:squid:AvoidCycle" - */ - @Override - public String toString() { - return String.format("%s:%s", qualityProfileKey, ruleKey.toString()); - } - - @Override - public int compareTo(ActiveRuleKey o) { - int compareQualityProfileKey = this.qualityProfileKey.compareTo(o.qualityProfileKey); - if (compareQualityProfileKey == 0) { - return this.ruleKey.compareTo(o.ruleKey); - } - return compareQualityProfileKey; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleMapper.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleMapper.java deleted file mode 100644 index b094385df2e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface ActiveRuleMapper { - - void insert(ActiveRuleDto dto); - - void update(ActiveRuleDto dto); - - void delete(int activeRuleId); - - ActiveRuleDto selectByKey(@Param("profileKey") String profileKey, @Param("repository") String repository, @Param("rule") String rule); - - List<ActiveRuleDto> selectByKeys(@Param("keys") List<ActiveRuleKey> keys); - - List<ActiveRuleDto> selectByRuleId(int ruleId); - - List<ActiveRuleDto> selectByRuleIds(@Param("ruleIds") List<Integer> partitionOfRuleIds); - - List<ActiveRuleDto> selectByProfileKey(String key); - - List<ActiveRuleDto> selectAll(); - - void insertParameter(ActiveRuleParamDto dto); - - void updateParameter(ActiveRuleParamDto dto); - - void deleteParameters(int activeRuleId); - - void deleteParameter(int activeRuleParamId); - - @CheckForNull - ActiveRuleParamDto selectParamByActiveRuleAndKey(@Param("activeRuleId") int activeRuleId, @Param("key") String key); - - List<ActiveRuleParamDto> selectParamsByActiveRuleId(int activeRuleId); - - List<ActiveRuleParamDto> selectParamsByActiveRuleIds(@Param("ids") List<Integer> ids); - - List<ActiveRuleParamDto> selectAllParams(); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleParamDto.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleParamDto.java deleted file mode 100644 index 06eca371834..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ActiveRuleParamDto.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import com.google.common.base.Preconditions; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.db.rule.RuleParamDto; - -public class ActiveRuleParamDto { - - private Integer id; - private Integer activeRuleId; - private Integer rulesParameterId; - private String kee; - private String value; - - public Integer getId() { - return id; - } - - public ActiveRuleParamDto setId(Integer id) { - this.id = id; - return this; - } - - public Integer getActiveRuleId() { - return activeRuleId; - } - - public ActiveRuleParamDto setActiveRuleId(Integer activeRuleId) { - this.activeRuleId = activeRuleId; - return this; - } - - public Integer getRulesParameterId() { - return rulesParameterId; - } - - // TODO set private or drop - public ActiveRuleParamDto setRulesParameterId(Integer rulesParameterId) { - this.rulesParameterId = rulesParameterId; - return this; - } - - public String getKey() { - return kee; - } - - public ActiveRuleParamDto setKey(String key) { - this.kee = key; - return this; - } - - public String getValue() { - return value; - } - - public ActiveRuleParamDto setValue(String value) { - this.value = value; - return this; - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); - } - - public static ActiveRuleParamDto createFor(RuleParamDto param) { - Preconditions.checkArgument(param.getId() != null, "Parameter is not persisted"); - return new ActiveRuleParamDto() - .setKey(param.getName()) - .setRulesParameterId(param.getId()); - } - - public static Map<String, ActiveRuleParamDto> groupByKey(Collection<ActiveRuleParamDto> params) { - Map<String, ActiveRuleParamDto> result = new HashMap<>(); - for (ActiveRuleParamDto param : params) { - result.put(param.getKey(), param); - } - return result; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ProjectQprofileAssociationDto.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/ProjectQprofileAssociationDto.java deleted file mode 100644 index a4c0281b035..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/ProjectQprofileAssociationDto.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import javax.annotation.CheckForNull; - -public class ProjectQprofileAssociationDto { - - private Long projectId; - private String projectUuid; - private String projectKey; - private String projectName; - private String profileKey; - - public Long getProjectId() { - return projectId; - } - - public String getProjectUuid() { - return projectUuid; - } - - public String getProjectKey() { - return projectKey; - } - - public String getProjectName() { - return projectName; - } - - @CheckForNull - public String getProfileKey() { - return profileKey; - } - - public boolean isAssociated() { - return profileKey != null; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDao.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDao.java deleted file mode 100644 index ca6febec239..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDao.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.List; -import org.sonar.api.utils.System2; -import org.sonar.core.util.UuidFactory; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkState; - -public class QProfileChangeDao implements Dao { - - private final System2 system2; - private final UuidFactory uuidFactory; - - public QProfileChangeDao(System2 system2, UuidFactory uuidFactory) { - this.system2 = system2; - this.uuidFactory = uuidFactory; - } - - public void insert(DbSession dbSession, QProfileChangeDto dto) { - checkState(dto.getKey() == null, "Key of QProfileChangeDto must be set by DAO only. Got %s.", dto.getKey()); - checkState(dto.getCreatedAt() == 0L, "Date of QProfileChangeDto must be set by DAO only. Got %s.", dto.getCreatedAt()); - - dto.setKey(uuidFactory.create()); - dto.setCreatedAt(system2.now()); - dbSession.getMapper(QProfileChangeMapper.class).insert(dto); - } - - public List<QProfileChangeDto> selectByQuery(DbSession dbSession, QProfileChangeQuery query) { - return dbSession.getMapper(QProfileChangeMapper.class).selectByQuery(query); - } - - public int countForProfileKey(DbSession dbSession, String profileKey) { - return dbSession.getMapper(QProfileChangeMapper.class).countForProfileKey(profileKey); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDto.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDto.java deleted file mode 100644 index 82a1e5142a2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDto.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.Collections; -import java.util.Map; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.utils.KeyValueFormat; - -public class QProfileChangeDto { - - private String key; - private String profileKey; - // can't be named "type" because it's a reserved word in Oracle - // (used by Mybatis to map DB column with DTO field) - private String changeType; - private String login; - private String data; - private long createdAt; - - public String getKey() { - return key; - } - - public QProfileChangeDto setKey(String s) { - this.key = s; - return this; - } - - public String getProfileKey() { - return profileKey; - } - - public QProfileChangeDto setProfileKey(String s) { - this.profileKey = s; - return this; - } - - public String getChangeType() { - return changeType; - } - - public QProfileChangeDto setChangeType(String s) { - this.changeType = s; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public QProfileChangeDto setCreatedAt(long l) { - this.createdAt = l; - return this; - } - - @CheckForNull - public String getLogin() { - return login; - } - - public QProfileChangeDto setLogin(@Nullable String s) { - this.login = s; - return this; - } - - @CheckForNull - public String getData() { - return data; - } - - public Map<String, String> getDataAsMap() { - if (data == null) { - return Collections.emptyMap(); - } - return KeyValueFormat.parse(data); - } - - public QProfileChangeDto setData(@Nullable String csv) { - this.data = csv; - return this; - } - - public QProfileChangeDto setData(@Nullable Map m) { - if (m == null || m.isEmpty()) { - this.data = null; - } else { - this.data = KeyValueFormat.format(m); - } - return this; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeMapper.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeMapper.java deleted file mode 100644 index 0022c01b1de..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface QProfileChangeMapper { - - void insert(QProfileChangeDto dto); - - List<QProfileChangeDto> selectByQuery(@Param("query") QProfileChangeQuery query); - - int countForProfileKey(@Param("profileKey") String profileKey); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeQuery.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeQuery.java deleted file mode 100644 index 8bbcbd88584..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QProfileChangeQuery.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -import static java.util.Objects.requireNonNull; - -public class QProfileChangeQuery { - - private final String profileKey; - private Long fromIncluded; - private Long toExcluded; - private int offset = 0; - private int limit = 100; - - public QProfileChangeQuery(String profileKey) { - this.profileKey = requireNonNull(profileKey); - } - - public String getProfileKey() { - return profileKey; - } - - @CheckForNull - public Long getFromIncluded() { - return fromIncluded; - } - - public void setFromIncluded(@Nullable Long l) { - this.fromIncluded = l; - } - - @CheckForNull - public Long getToExcluded() { - return toExcluded; - } - - public void setToExcluded(@Nullable Long l) { - this.toExcluded = l; - } - - public int getOffset() { - return offset; - } - - public void setOffset(int offset) { - this.offset = offset; - } - - public int getLimit() { - return limit; - } - - public void setLimit(int limit) { - this.limit = limit; - } - - public void setPage(int page, int pageSize) { - offset = (page -1) * pageSize; - limit = pageSize; - } - - public int getTotal() { - return offset + limit; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java deleted file mode 100644 index d7fa7d4755f..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; -import org.sonar.db.RowNotFoundException; -import org.sonar.db.component.ComponentDto; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class QualityProfileDao implements Dao { - - private final MyBatis mybatis; - private final System2 system; - - public QualityProfileDao(MyBatis mybatis, System2 system) { - this.mybatis = mybatis; - this.system = system; - } - - @CheckForNull - public QualityProfileDto selectByKey(DbSession session, String key) { - return mapper(session).selectByKey(key); - } - - public QualityProfileDto selectOrFailByKey(DbSession session, String key) { - QualityProfileDto dto = selectByKey(session, key); - if (dto == null) { - throw new RowNotFoundException("Quality profile not found: " + key); - } - return dto; - } - - public List<QualityProfileDto> selectByKeys(DbSession session, List<String> keys) { - return executeLargeInputs(keys, mapper(session)::selectByKeys); - } - - public List<QualityProfileDto> selectAll(DbSession session) { - return mapper(session).selectAll(); - } - - public void insert(DbSession session, QualityProfileDto profile, QualityProfileDto... otherProfiles) { - QualityProfileMapper mapper = mapper(session); - doInsert(mapper, profile); - for (QualityProfileDto other : otherProfiles) { - doInsert(mapper, other); - } - } - - private void doInsert(QualityProfileMapper mapper, QualityProfileDto profile) { - Preconditions.checkArgument(profile.getId() == null, "Quality profile is already persisted (got id %d)", profile.getId()); - Date now = new Date(system.now()); - profile.setCreatedAt(now); - profile.setUpdatedAt(now); - mapper.insert(profile); - } - - /** - * @deprecated use {@link #insert(DbSession, QualityProfileDto, QualityProfileDto...)} - */ - @Deprecated - public void insert(QualityProfileDto dto) { - DbSession session = mybatis.openSession(false); - try { - insert(session, dto); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void update(DbSession session, QualityProfileDto profile, QualityProfileDto... otherProfiles) { - QualityProfileMapper mapper = mapper(session); - doUpdate(mapper, profile); - for (QualityProfileDto otherProfile : otherProfiles) { - doUpdate(mapper, otherProfile); - } - } - - private void doUpdate(QualityProfileMapper mapper, QualityProfileDto profile) { - Preconditions.checkArgument(profile.getId() != null, "Quality profile is not persisted"); - profile.setUpdatedAt(new Date(system.now())); - mapper.update(profile); - } - - public void delete(DbSession session, int profileId) { - QualityProfileMapper mapper = mapper(session); - mapper.delete(profileId); - } - - /** - * @deprecated Replaced by {@link #selectAll(DbSession)} - */ - @Deprecated - public List<QualityProfileDto> selectAll() { - DbSession session = mybatis.openSession(false); - try { - return mapper(session).selectAll(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public List<QualityProfileDto> selectDefaultProfiles(DbSession session, Collection<String> languageKeys) { - return executeLargeInputs(languageKeys, mapper(session)::selectDefaultProfiles); - } - - @CheckForNull - public QualityProfileDto selectDefaultProfile(DbSession session, String language) { - return mapper(session).selectDefaultProfile(language); - } - - @CheckForNull - public QualityProfileDto selectDefaultProfile(String language) { - DbSession session = mybatis.openSession(false); - try { - return selectDefaultProfile(session, language); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityProfileDto selectByProjectAndLanguage(long projectId, String language) { - DbSession session = mybatis.openSession(false); - try { - return mapper(session).selectByProjectIdAndLanguage(projectId, language); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityProfileDto selectByProjectAndLanguage(DbSession session, String projectKey, String language) { - return mapper(session).selectByProjectAndLanguage(projectKey, language); - } - - public List<QualityProfileDto> selectByProjectAndLanguages(DbSession session, String projectKey, Collection<String> languageKeys) { - return executeLargeInputs(languageKeys, input -> mapper(session).selectByProjectAndLanguages(projectKey, input)); - } - - public List<QualityProfileDto> selectByLanguage(String language) { - DbSession session = mybatis.openSession(false); - try { - return mapper(session).selectByLanguage(language); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityProfileDto selectById(DbSession session, int id) { - return mapper(session).selectById(id); - } - - @CheckForNull - public QualityProfileDto selectById(int id) { - DbSession session = mybatis.openSession(false); - try { - return selectById(session, id); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public QualityProfileDto selectParentById(DbSession session, int childId) { - return mapper(session).selectParentById(childId); - } - - public List<QualityProfileDto> selectChildren(DbSession session, String key) { - return mapper(session).selectChildren(key); - } - - /** - * All descendants, in the top-down order. - */ - public List<QualityProfileDto> selectDescendants(DbSession session, String key) { - List<QualityProfileDto> descendants = Lists.newArrayList(); - for (QualityProfileDto child : selectChildren(session, key)) { - descendants.add(child); - descendants.addAll(selectDescendants(session, child.getKey())); - } - return descendants; - } - - @CheckForNull - public QualityProfileDto selectByNameAndLanguage(String name, String language, DbSession session) { - return mapper(session).selectByNameAndLanguage(name, language); - } - - public List<QualityProfileDto> selectByNameAndLanguages(String name, Collection<String> languageKeys, DbSession session) { - return executeLargeInputs(languageKeys, input -> mapper(session).selectByNameAndLanguages(name, input)); - } - - public List<ComponentDto> selectProjects(String profileName, String language) { - DbSession session = mybatis.openSession(false); - try { - return selectProjects(profileName, language, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public List<ComponentDto> selectProjects(String profileName, String language, DbSession session) { - return mapper(session).selectProjects(profileName, language); - } - - public Map<String, Long> countProjectsByProfileKey() { - DbSession session = mybatis.openSession(false); - try { - Map<String, Long> countByKey = Maps.newHashMap(); - for (QualityProfileProjectCount count : mapper(session).countProjectsByProfile()) { - countByKey.put(count.getProfileKey(), count.getProjectCount()); - } - return countByKey; - } finally { - MyBatis.closeQuietly(session); - } - } - - public void insertProjectProfileAssociation(String projectUuid, String profileKey, DbSession session) { - mapper(session).insertProjectProfileAssociation(projectUuid, profileKey); - } - - public void deleteProjectProfileAssociation(String projectUuid, String profileKey, DbSession session) { - mapper(session).deleteProjectProfileAssociation(projectUuid, profileKey); - } - - public void updateProjectProfileAssociation(String projectUuid, String newProfileKey, String oldProfileKey, DbSession session) { - mapper(session).updateProjectProfileAssociation(projectUuid, newProfileKey, oldProfileKey); - } - - public void deleteAllProjectProfileAssociation(String profileKey, DbSession session) { - mapper(session).deleteAllProjectProfileAssociation(profileKey); - } - - public List<ProjectQprofileAssociationDto> selectSelectedProjects(String profileKey, @Nullable String query, DbSession session) { - String nameQuery = sqlQueryString(query); - return mapper(session).selectSelectedProjects(profileKey, nameQuery); - } - - public List<ProjectQprofileAssociationDto> selectDeselectedProjects(String profileKey, @Nullable String query, DbSession session) { - String nameQuery = sqlQueryString(query); - return mapper(session).selectDeselectedProjects(profileKey, nameQuery); - } - - public List<ProjectQprofileAssociationDto> selectProjectAssociations(String profileKey, @Nullable String query, DbSession session) { - String nameQuery = sqlQueryString(query); - return mapper(session).selectProjectAssociations(profileKey, nameQuery); - } - - private String sqlQueryString(@Nullable String query) { - return query == null ? "%" : "%" + query.toUpperCase(Locale.ENGLISH) + "%"; - } - - private static QualityProfileMapper mapper(DbSession session) { - return session.getMapper(QualityProfileMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDto.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDto.java deleted file mode 100644 index c8abfaa9290..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileDto.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.core.util.UtcDateUtils; -import org.sonar.db.Dto; - -public class QualityProfileDto extends Dto<String> { - - private Integer id; - private String kee; - private String name; - private String language; - private String parentKee; - private String rulesUpdatedAt; - private Long lastUsed; - private Long userUpdatedAt; - private boolean isDefault; - - /** - * @deprecated use {@link #createFor(String)} - */ - @Deprecated - public QualityProfileDto() { - - } - - @Override - public String getKey() { - return kee; - } - - public QualityProfileDto setKey(String s) { - return setKee(s); - } - - public String getKee() { - return kee; - } - - public QualityProfileDto setKee(String s) { - this.kee = s; - return this; - } - - public Integer getId() { - return id; - } - - public QualityProfileDto setId(Integer id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public QualityProfileDto setName(String name) { - this.name = name; - return this; - } - - public String getLanguage() { - return language; - } - - public QualityProfileDto setLanguage(String language) { - this.language = language; - return this; - } - - @CheckForNull - public String getParentKee() { - return parentKee; - } - - public QualityProfileDto setParentKee(@Nullable String s) { - this.parentKee = s; - return this; - } - - public String getRulesUpdatedAt() { - return rulesUpdatedAt; - } - - public QualityProfileDto setRulesUpdatedAt(String s) { - this.rulesUpdatedAt = s; - return this; - } - - public QualityProfileDto setRulesUpdatedAtAsDate(Date d) { - this.rulesUpdatedAt = UtcDateUtils.formatDateTime(d); - return this; - } - - @CheckForNull - public Long getLastUsed() { - return lastUsed; - } - - public QualityProfileDto setLastUsed(@Nullable Long lastUsed) { - this.lastUsed = lastUsed; - return this; - } - - @CheckForNull - public Long getUserUpdatedAt() { - return userUpdatedAt; - } - - public QualityProfileDto setUserUpdatedAt(@Nullable Long userUpdatedAt) { - this.userUpdatedAt = userUpdatedAt; - return this; - } - - public boolean isDefault() { - return isDefault; - } - - public QualityProfileDto setDefault(boolean isDefault) { - this.isDefault = isDefault; - return this; - } - - public static QualityProfileDto createFor(String key) { - return new QualityProfileDto().setKee(key); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileMapper.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileMapper.java deleted file mode 100644 index a44f43ce468..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileMapper.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; -import org.sonar.db.component.ComponentDto; - -public interface QualityProfileMapper { - - void insert(QualityProfileDto dto); - - void update(QualityProfileDto dto); - - void delete(int id); - - List<QualityProfileDto> selectAll(); - - @CheckForNull - QualityProfileDto selectDefaultProfile(@Param("language") String language); - - List<QualityProfileDto> selectDefaultProfiles(@Param("languages") List<String> languages); - - @CheckForNull - QualityProfileDto selectByNameAndLanguage(@Param("name") String name, @Param("language") String language); - - List<QualityProfileDto> selectByNameAndLanguages(@Param("name") String name, @Param("languages") List<String> languages); - - @CheckForNull - QualityProfileDto selectById(@Param("id") Integer id); - - @CheckForNull - QualityProfileDto selectByKey(String key); - - List<QualityProfileDto> selectByLanguage(String language); - - List<QualityProfileDto> selectByKeys(@Param("keys") List<String> keys); - - // INHERITANCE - - @CheckForNull - QualityProfileDto selectParentById(int childId); - - List<QualityProfileDto> selectChildren(String key); - - // PROJECTS - - List<ComponentDto> selectProjects(@Param("profileName") String profileName, @Param("language") String language); - - List<QualityProfileProjectCount> countProjectsByProfile(); - - QualityProfileDto selectByProjectIdAndLanguage(@Param("projectId") Long projectId, @Param("language") String language); - - QualityProfileDto selectByProjectAndLanguage(@Param("projectKey") String projectKey, @Param("language") String language); - - List<QualityProfileDto> selectByProjectAndLanguages(@Param("projectKey") String projectKey, @Param("languages") List<String> input); - - void insertProjectProfileAssociation(@Param("projectUuid") String projectUuid, @Param("profileKey") String profileKey); - - void updateProjectProfileAssociation(@Param("projectUuid") String projectUuid, @Param("profileKey") String profileKey, @Param("oldProfileKey") String oldProfileKey); - - void deleteProjectProfileAssociation(@Param("projectUuid") String projectUuid, @Param("profileKey") String profileKey); - - void deleteAllProjectProfileAssociation(@Param("profileKey") String profileKey); - - List<ProjectQprofileAssociationDto> selectSelectedProjects(@Param("profileKey") String profileKey, @Param("nameQuery") String nameQuery); - - List<ProjectQprofileAssociationDto> selectDeselectedProjects(@Param("profileKey") String profileKey, @Param("nameQuery") String nameQuery); - - List<ProjectQprofileAssociationDto> selectProjectAssociations(@Param("profileKey") String profileKey, @Param("nameQuery") String nameQuery); -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileProjectCount.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileProjectCount.java deleted file mode 100644 index 9a42926b335..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/QualityProfileProjectCount.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -public class QualityProfileProjectCount { - - private String profileKey; - private Long projectCount; - - public String getProfileKey() { - return profileKey; - } - - public Long getProjectCount() { - return projectCount; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/qualityprofile/package-info.java b/sonar-db/src/main/java/org/sonar/db/qualityprofile/package-info.java deleted file mode 100644 index f9761c6cacd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/qualityprofile/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.qualityprofile; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleDao.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleDao.java deleted file mode 100644 index 53e3c95e857..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleDao.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import com.google.common.base.Optional; -import java.util.Collection; -import java.util.List; -import org.apache.ibatis.session.ResultHandler; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.RuleQuery; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class RuleDao implements Dao { - - public Optional<RuleDto> selectByKey(DbSession session, RuleKey key) { - return Optional.fromNullable(mapper(session).selectByKey(key)); - } - - public RuleDto selectOrFailByKey(DbSession session, RuleKey key) { - RuleDto rule = mapper(session).selectByKey(key); - if (rule == null) { - throw new RowNotFoundException(String.format("Rule with key '%s' does not exist", key)); - } - return rule; - } - - /** - * Retrieves a Rule by its id. - * - * Used by Views. - */ - public Optional<RuleDto> selectById(long id, DbSession session) { - return Optional.fromNullable(mapper(session).selectById(id)); - } - - public List<RuleDto> selectByIds(DbSession session, List<Integer> ids) { - return executeLargeInputs(ids, mapper(session)::selectByIds); - } - - /** - * Select rules by keys, whatever their status. Returns an empty list - * if the list of {@code keys} is empty, without any db round trip. - */ - public List<RuleDto> selectByKeys(DbSession session, Collection<RuleKey> keys) { - return executeLargeInputs(keys, mapper(session)::selectByKeys); - } - - public List<RuleDto> selectEnabled(DbSession session) { - return mapper(session).selectEnabled(); - } - - public void selectEnabled(DbSession session, ResultHandler resultHandler) { - mapper(session).selectEnabled(resultHandler); - } - - public List<RuleDto> selectAll(DbSession session) { - return mapper(session).selectAll(); - } - - public List<RuleDto> selectByQuery(DbSession session, RuleQuery ruleQuery) { - return mapper(session).selectByQuery(ruleQuery); - } - - public void insert(DbSession session, RuleDto dto) { - mapper(session).insert(dto); - } - - public void update(DbSession session, RuleDto dto) { - mapper(session).update(dto); - } - - private static RuleMapper mapper(DbSession session) { - return session.getMapper(RuleMapper.class); - } - - /** - * RuleParams - */ - - public List<RuleParamDto> selectRuleParamsByRuleKey(DbSession session, RuleKey key) { - return mapper(session).selectParamsByRuleKey(key); - } - - public List<RuleParamDto> selectRuleParamsByRuleKeys(DbSession session, List<RuleKey> ruleKeys) { - return executeLargeInputs(ruleKeys, mapper(session)::selectParamsByRuleKeys); - } - - public List<RuleParamDto> selectRuleParamsByRuleIds(DbSession dbSession, List<Integer> ruleIds) { - return executeLargeInputs(ruleIds, mapper(dbSession)::selectParamsByRuleIds); - } - - public void insertRuleParam(DbSession session, RuleDto rule, RuleParamDto param) { - checkNotNull(rule.getId(), "Rule id must be set"); - param.setRuleId(rule.getId()); - mapper(session).insertParameter(param); - } - - public RuleParamDto updateRuleParam(DbSession session, RuleDto rule, RuleParamDto param) { - checkNotNull(rule.getId(), "Rule id must be set"); - checkNotNull(param.getId(), "Rule parameter is not yet persisted must be set"); - param.setRuleId(rule.getId()); - mapper(session).updateParameter(param); - return param; - } - - public void deleteRuleParam(DbSession session, int ruleParameterId) { - mapper(session).deleteParameter(ruleParameterId); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleDto.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleDto.java deleted file mode 100644 index 2cb5c355549..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleDto.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rules.RuleType; - -import static com.google.common.base.Preconditions.checkArgument; - -public class RuleDto { - - public enum Format { - HTML, MARKDOWN - } - - private Integer id; - private String repositoryKey; - private String ruleKey; - private String description; - private Format descriptionFormat; - private RuleStatus status; - private String name; - private String configKey; - private Integer severity; - private boolean isTemplate; - private String language; - private Integer templateId; - private String noteData; - private String noteUserLogin; - private Date noteCreatedAt; - private Date noteUpdatedAt; - private String remediationFunction; - private String defRemediationFunction; - private String remediationGapMultiplier; - private String defRemediationGapMultiplier; - private String remediationBaseEffort; - private String defRemediationBaseEffort; - private String gapDescription; - private String tags; - private String systemTags; - private int type; - - private RuleKey key; - - private long createdAt; - private long updatedAt; - - public RuleKey getKey() { - if (key == null) { - key = RuleKey.of(getRepositoryKey(), getRuleKey()); - } - return key; - } - - public Integer getId() { - return id; - } - - public RuleDto setId(Integer id) { - this.id = id; - return this; - } - - public String getRepositoryKey() { - return repositoryKey; - } - - public RuleDto setRepositoryKey(String s) { - checkArgument(s.length() <= 255, "Rule repository is too long: %s", s); - this.repositoryKey = s; - return this; - } - - public String getRuleKey() { - return ruleKey; - } - - public RuleDto setRuleKey(String s) { - checkArgument(s.length() <= 200, "Rule key is too long: %s", s); - this.ruleKey = s; - return this; - } - - public String getDescription() { - return description; - } - - public RuleDto setDescription(String description) { - this.description = description; - return this; - } - - public Format getDescriptionFormat() { - return descriptionFormat; - } - - public RuleDto setDescriptionFormat(Format descriptionFormat) { - this.descriptionFormat = descriptionFormat; - return this; - } - - public RuleStatus getStatus() { - return status; - } - - public RuleDto setStatus(@Nullable RuleStatus s) { - this.status = s; - return this; - } - - public String getName() { - return name; - } - - public RuleDto setName(@Nullable String s) { - checkArgument(s== null || s.length() <= 255, "Rule name is too long: %s", s); - this.name = s; - return this; - } - - public String getConfigKey() { - return configKey; - } - - public RuleDto setConfigKey(@Nullable String configKey) { - this.configKey = configKey; - return this; - } - - @CheckForNull - public Integer getSeverity() { - return severity; - } - - @CheckForNull - public String getSeverityString() { - return severity != null ? SeverityUtil.getSeverityFromOrdinal(severity) : null; - } - - public RuleDto setSeverity(@Nullable String severity) { - return this.setSeverity(severity != null ? SeverityUtil.getOrdinalFromSeverity(severity) : null); - } - - public RuleDto setSeverity(@Nullable Integer severity) { - this.severity = severity; - return this; - } - - public boolean isTemplate() { - return isTemplate; - } - - public RuleDto setIsTemplate(boolean isTemplate) { - this.isTemplate = isTemplate; - return this; - } - - @CheckForNull - public String getLanguage() { - return language; - } - - public RuleDto setLanguage(String language) { - this.language = language; - return this; - } - - @CheckForNull - public Integer getTemplateId() { - return templateId; - } - - public RuleDto setTemplateId(@Nullable Integer templateId) { - this.templateId = templateId; - return this; - } - - public String getNoteData() { - return noteData; - } - - public RuleDto setNoteData(String noteData) { - this.noteData = noteData; - return this; - } - - public String getNoteUserLogin() { - return noteUserLogin; - } - - public RuleDto setNoteUserLogin(String noteUserLogin) { - this.noteUserLogin = noteUserLogin; - return this; - } - - public Date getNoteCreatedAt() { - return noteCreatedAt; - } - - public RuleDto setNoteCreatedAt(Date noteCreatedAt) { - this.noteCreatedAt = noteCreatedAt; - return this; - } - - public Date getNoteUpdatedAt() { - return noteUpdatedAt; - } - - public RuleDto setNoteUpdatedAt(Date noteUpdatedAt) { - this.noteUpdatedAt = noteUpdatedAt; - return this; - } - - @CheckForNull - public String getRemediationFunction() { - return remediationFunction; - } - - public RuleDto setRemediationFunction(@Nullable String remediationFunction) { - this.remediationFunction = remediationFunction; - return this; - } - - @CheckForNull - public String getDefaultRemediationFunction() { - return defRemediationFunction; - } - - public RuleDto setDefaultRemediationFunction(@Nullable String defaultRemediationFunction) { - this.defRemediationFunction = defaultRemediationFunction; - return this; - } - - @CheckForNull - public String getRemediationGapMultiplier() { - return remediationGapMultiplier; - } - - public RuleDto setRemediationGapMultiplier(@Nullable String remediationGapMultiplier) { - this.remediationGapMultiplier = remediationGapMultiplier; - return this; - } - - @CheckForNull - public String getDefaultRemediationGapMultiplier() { - return defRemediationGapMultiplier; - } - - public RuleDto setDefaultRemediationGapMultiplier(@Nullable String defaultRemediationGapMultiplier) { - this.defRemediationGapMultiplier = defaultRemediationGapMultiplier; - return this; - } - - @CheckForNull - public String getRemediationBaseEffort() { - return remediationBaseEffort; - } - - public RuleDto setRemediationBaseEffort(@Nullable String remediationBaseEffort) { - this.remediationBaseEffort = remediationBaseEffort; - return this; - } - - @CheckForNull - public String getDefaultRemediationBaseEffort() { - return defRemediationBaseEffort; - } - - public RuleDto setDefaultRemediationBaseEffort(@Nullable String defaultRemediationBaseEffort) { - this.defRemediationBaseEffort = defaultRemediationBaseEffort; - return this; - } - - @CheckForNull - public String getGapDescription() { - return gapDescription; - } - - public RuleDto setGapDescription(@Nullable String s) { - this.gapDescription = s; - return this; - } - - public Set<String> getTags() { - return tags == null ? new HashSet<>() : new TreeSet<>(Arrays.asList(StringUtils.split(tags, ','))); - } - - public Set<String> getSystemTags() { - return systemTags == null ? new HashSet<>() : new TreeSet<>(Arrays.asList(StringUtils.split(systemTags, ','))); - } - - private String getTagsField() { - return tags; - } - - private String getSystemTagsField() { - return systemTags; - } - - private void setTagsField(String s) { - tags = s; - } - - private void setSystemTagsField(String s) { - systemTags = s; - } - - public RuleDto setTags(Set<String> tags) { - String raw = tags.isEmpty() ? null : StringUtils.join(tags, ','); - checkArgument(raw == null || raw.length() <= 4000, "Rule tags are too long: %s", raw); - this.tags = raw; - return this; - } - - public RuleDto setSystemTags(Set<String> tags) { - this.systemTags = tags.isEmpty() ? null : StringUtils.join(tags, ','); - return this; - } - - public int getType() { - return type; - } - - public RuleDto setType(int type) { - this.type = type; - return this; - } - - public RuleDto setType(RuleType type) { - this.type = type.getDbConstant(); - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public RuleDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public RuleDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof RuleDto)) { - return false; - } - if (this == obj) { - return true; - } - RuleDto other = (RuleDto) obj; - return new EqualsBuilder() - .append(repositoryKey, other.getRepositoryKey()) - .append(ruleKey, other.getRuleKey()) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(repositoryKey) - .append(ruleKey) - .toHashCode(); - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); - } - - public static RuleDto createFor(RuleKey key) { - return new RuleDto() - .setRepositoryKey(key.repository()) - .setRuleKey(key.rule()); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleMapper.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleMapper.java deleted file mode 100644 index 3d768933203..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleMapper.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import java.util.List; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.ResultHandler; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.RuleQuery; - -public interface RuleMapper { - - List<RuleDto> selectAll(); - - List<RuleDto> selectAll(ResultHandler resultHandler); - - List<RuleDto> selectEnabled(); - - void selectEnabled(ResultHandler resultHandler); - - RuleDto selectById(long id); - - List<RuleDto> selectByIds(@Param("ids") List<Integer> ids); - - RuleDto selectByKey(RuleKey ruleKey); - - List<RuleDto> selectByKeys(@Param("ruleKeys") List<RuleKey> keys); - - RuleDto selectByName(String name); - - List<RuleDto> selectByQuery(@Param("query") RuleQuery ruleQuery); - - void update(RuleDto rule); - - void insert(RuleDto rule); - - List<RuleParamDto> selectParamsByRuleIds(@Param("ruleIds") List<Integer> ruleIds); - - List<RuleParamDto> selectParamsByRuleKey(RuleKey ruleKey); - - List<RuleParamDto> selectParamsByRuleKeys(@Param("ruleKeys") List<RuleKey> ruleKeys); - - void insertParameter(RuleParamDto param); - - void updateParameter(RuleParamDto param); - - void deleteParameter(Integer paramId); -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleParamDto.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleParamDto.java deleted file mode 100644 index 867a810b0a7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleParamDto.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -import static com.google.common.base.Preconditions.checkArgument; - -public class RuleParamDto { - - private Integer id; - private Integer ruleId; - private String name; - private String type; - private String defaultValue; - private String description; - - public Integer getId() { - return id; - } - - public RuleParamDto setId(Integer id) { - this.id = id; - return this; - } - - public Integer getRuleId() { - return ruleId; - } - - public RuleParamDto setRuleId(Integer ruleId) { - this.ruleId = ruleId; - return this; - } - - public String getName() { - return name; - } - - public RuleParamDto setName(String s) { - checkArgument(s.length() <= 128, "Rule parameter name is too long: %s", s); - this.name = s; - return this; - } - - public String getType() { - return type; - } - - public RuleParamDto setType(String type) { - this.type = type; - return this; - } - - @CheckForNull - public String getDefaultValue() { - return defaultValue; - } - - public RuleParamDto setDefaultValue(@Nullable String s) { - checkArgument(s == null || s.length() <= 4000, "Rule parameter default value is too long: %s", s); - this.defaultValue = s; - return this; - } - - public String getDescription() { - return description; - } - - public RuleParamDto setDescription(@Nullable String s) { - checkArgument(s == null || s.length() <= 4000, "Rule parameter description is too long: %s", s); - this.description = s; - return this; - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); - } - - public static RuleParamDto createFor(RuleDto rule) { - // Should eventually switch to RuleKey (RuleKey is available before insert) - return new RuleParamDto().setRuleId(rule.getId()); - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDao.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDao.java deleted file mode 100644 index e2f5903551e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDao.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -public class RuleRepositoryDao implements Dao { - - private final System2 system2; - - public RuleRepositoryDao(System2 system2) { - this.system2 = system2; - } - - /** - * @return a non-null list ordered by key (as implemented by database, order may - * depend on case sensitivity) - */ - public List<RuleRepositoryDto> selectAll(DbSession dbSession) { - return dbSession.getMapper(RuleRepositoryMapper.class).selectAll(); - } - - /** - * @return a non-null list ordered by key (as implemented by database, order may - * depend on case sensitivity) - */ - public List<RuleRepositoryDto> selectByLanguage(DbSession dbSession, String language) { - return dbSession.getMapper(RuleRepositoryMapper.class).selectByLanguage(language); - } - - public Optional<RuleRepositoryDto> selectByKey(DbSession dbSession, String key) { - return Optional.ofNullable(dbSession.getMapper(RuleRepositoryMapper.class).selectByKey(key)); - } - - public void truncate(DbSession dbSession) { - dbSession.getMapper(RuleRepositoryMapper.class).truncate(); - } - - public void insert(DbSession dbSession, Collection<RuleRepositoryDto> dtos) { - RuleRepositoryMapper mapper = dbSession.getMapper(RuleRepositoryMapper.class); - long now = system2.now(); - for (RuleRepositoryDto dto : dtos) { - mapper.insert(dto, now); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDto.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDto.java deleted file mode 100644 index 8180c24dcaf..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryDto.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -public class RuleRepositoryDto { - - // do not rename "key" as MyBatis maps it with the db column "kee" - private String kee; - private String language; - private String name; - - public RuleRepositoryDto() { - // used by MyBatis - } - - public RuleRepositoryDto(String kee, String language, String name) { - this.kee = kee; - this.language = language; - this.name = name; - } - - public String getKey() { - return kee; - } - - public String getLanguage() { - return language; - } - - public String getName() { - return name; - } - - public RuleRepositoryDto setKey(String s) { - this.kee = s; - return this; - } - - public RuleRepositoryDto setLanguage(String s) { - this.language = s; - return this; - } - - public RuleRepositoryDto setName(String s) { - this.name = s; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryMapper.java b/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryMapper.java deleted file mode 100644 index 3651ceb54a7..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/RuleRepositoryMapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface RuleRepositoryMapper { - - List<RuleRepositoryDto> selectAll(); - - List<RuleRepositoryDto> selectByLanguage(@Param("language") String language); - - @CheckForNull - RuleRepositoryDto selectByKey(@Param("key") String key); - - void truncate(); - - void insert(@Param("repository") RuleRepositoryDto repository, @Param("now") long now); -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/SeverityUtil.java b/sonar-db/src/main/java/org/sonar/db/rule/SeverityUtil.java deleted file mode 100644 index c5ad4b7317a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/SeverityUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import org.sonar.api.rule.Severity; - -public class SeverityUtil { - - private SeverityUtil() { - // Only static stuff - } - - public static String getSeverityFromOrdinal(int ordinal) { - return Severity.ALL.get(ordinal); - } - - public static int getOrdinalFromSeverity(String severity) { - return Severity.ALL.indexOf(severity); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/rule/package-info.java b/sonar-db/src/main/java/org/sonar/db/rule/package-info.java deleted file mode 100644 index b9d1b93d622..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/rule/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.rule; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDao.java b/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDao.java deleted file mode 100644 index bebddad8f9e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDao.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.schemamigration; - -import java.util.List; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; - -public class SchemaMigrationDao implements Dao { - public List<Integer> selectVersions(DbSession dbSession) { - return getMapper(dbSession).selectVersions(); - } - - public void insert(DbSession dbSession, String version) { - requireNonNull(version, "version can't be null"); - checkArgument(!version.isEmpty(), "version can't be empty"); - getMapper(dbSession).insert(version); - } - - private static SchemaMigrationMapper getMapper(DbSession dbSession) { - return dbSession.getMapper(SchemaMigrationMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDto.java b/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDto.java deleted file mode 100644 index 345c1117661..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationDto.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.schemamigration; - -/** - * Maps the table SCHEMA_MIGRATIONS - * @since 3.0 - */ -public class SchemaMigrationDto { - private String version;// NOSONAR this field is assigned by MyBatis - - public String getVersion() { - return version; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationMapper.java b/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationMapper.java deleted file mode 100644 index 4da1e09cdd9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/schemamigration/SchemaMigrationMapper.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.schemamigration; - -import java.util.List; - -public interface SchemaMigrationMapper { - List<Integer> selectVersions(); - - void insert(String version); -} diff --git a/sonar-db/src/main/java/org/sonar/db/schemamigration/package-info.java b/sonar-db/src/main/java/org/sonar/db/schemamigration/package-info.java deleted file mode 100644 index 646c3ea3913..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/schemamigration/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.schemamigration; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/semaphore/SemaphoresImpl.java b/sonar-db/src/main/java/org/sonar/db/semaphore/SemaphoresImpl.java deleted file mode 100644 index ef9030591aa..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/semaphore/SemaphoresImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.semaphore; - -import org.sonar.api.utils.Semaphores; - -public class SemaphoresImpl implements Semaphores { - - @Override - public Semaphore acquire(String name, int maxAgeInSeconds, int updatePeriodInSeconds) { - throw fail(); - } - - @Override - public Semaphore acquire(String name) { - throw fail(); - } - - @Override - public void release(String name) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException("Semaphores are not supported since 5.2 and the drop of database connection from analyzer"); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/semaphore/package-info.java b/sonar-db/src/main/java/org/sonar/db/semaphore/package-info.java deleted file mode 100644 index a6ff02997db..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/semaphore/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.semaphore; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/source/FileSourceDao.java b/sonar-db/src/main/java/org/sonar/db/source/FileSourceDao.java deleted file mode 100644 index 98754f4df26..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/source/FileSourceDao.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.source; - -import com.google.common.base.Splitter; -import java.io.Reader; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; -import javax.annotation.CheckForNull; -import org.apache.commons.dbutils.DbUtils; -import org.apache.commons.io.IOUtils; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; -import org.sonar.db.source.FileSourceDto.Type; - -public class FileSourceDao implements Dao { - - private static final Splitter END_OF_LINE_SPLITTER = Splitter.on('\n'); - private final MyBatis mybatis; - - public FileSourceDao(MyBatis myBatis) { - this.mybatis = myBatis; - } - - @CheckForNull - public FileSourceDto selectSourceByFileUuid(DbSession session, String fileUuid) { - return mapper(session).select(fileUuid, Type.SOURCE); - } - - @CheckForNull - public FileSourceDto selectTest(String fileUuid) { - DbSession session = mybatis.openSession(false); - try { - return mapper(session).select(fileUuid, Type.TEST); - } finally { - MyBatis.closeQuietly(session); - } - } - - @CheckForNull - public List<String> selectLineHashes(DbSession dbSession, String fileUuid) { - Connection connection = dbSession.getConnection(); - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - pstmt = connection.prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type=?"); - pstmt.setString(1, fileUuid); - pstmt.setString(2, Type.SOURCE); - rs = pstmt.executeQuery(); - if (rs.next()) { - String string = rs.getString(1); - if (string == null) { - return Collections.emptyList(); - } - return END_OF_LINE_SPLITTER.splitToList(string); - } - return null; - } catch (SQLException e) { - throw new IllegalStateException("Fail to read FILE_SOURCES.LINE_HASHES of file " + fileUuid, e); - } finally { - DbUtils.closeQuietly(connection, pstmt, rs); - } - } - - public <T> void readLineHashesStream(DbSession dbSession, String fileUuid, Function<Reader, T> function) { - Connection connection = dbSession.getConnection(); - PreparedStatement pstmt = null; - ResultSet rs = null; - Reader reader = null; - try { - pstmt = connection.prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type=?"); - pstmt.setString(1, fileUuid); - pstmt.setString(2, Type.SOURCE); - rs = pstmt.executeQuery(); - if (rs.next()) { - reader = rs.getCharacterStream(1); - if (reader != null) { - function.apply(reader); - } - } - } catch (SQLException e) { - throw new IllegalStateException("Fail to read FILE_SOURCES.LINE_HASHES of file " + fileUuid, e); - } finally { - IOUtils.closeQuietly(reader); - DbUtils.closeQuietly(connection, pstmt, rs); - } - } - - public void insert(FileSourceDto dto) { - DbSession session = mybatis.openSession(false); - try { - insert(session, dto); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void insert(DbSession session, FileSourceDto dto) { - mapper(session).insert(dto); - } - - public void update(FileSourceDto dto) { - DbSession session = mybatis.openSession(false); - try { - update(session, dto); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void update(DbSession session, FileSourceDto dto) { - mapper(session).update(dto); - } - - private static FileSourceMapper mapper(DbSession session) { - return session.getMapper(FileSourceMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/source/FileSourceDto.java b/sonar-db/src/main/java/org/sonar/db/source/FileSourceDto.java deleted file mode 100644 index 2218054b971..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/source/FileSourceDto.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.source; - -import com.google.protobuf.CodedInputStream; -import com.google.protobuf.InvalidProtocolBufferException; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import net.jpountz.lz4.LZ4BlockInputStream; -import net.jpountz.lz4.LZ4BlockOutputStream; -import org.apache.commons.io.IOUtils; -import org.sonar.db.protobuf.DbFileSources; - -import static java.lang.String.format; - -public class FileSourceDto { - - private static final String SIZE_LIMIT_EXCEEDED_EXCEPTION_MESSAGE = "Protocol message was too large. May be malicious. " + - "Use CodedInputStream.setSizeLimit() to increase the size limit."; - - private Long id; - private String projectUuid; - private String fileUuid; - private long createdAt; - private long updatedAt; - private String lineHashes; - private String srcHash; - private byte[] binaryData; - private String dataType; - private String dataHash; - private String revision; - - public Long getId() { - return id; - } - - public FileSourceDto setId(Long id) { - this.id = id; - return this; - } - - public String getProjectUuid() { - return projectUuid; - } - - public FileSourceDto setProjectUuid(String projectUuid) { - this.projectUuid = projectUuid; - return this; - } - - public String getFileUuid() { - return fileUuid; - } - - public FileSourceDto setFileUuid(String fileUuid) { - this.fileUuid = fileUuid; - return this; - } - - @CheckForNull - public String getDataHash() { - return dataHash; - } - - /** - * MD5 of column BINARY_DATA. Used to know to detect data changes and need for update. - */ - public FileSourceDto setDataHash(String s) { - this.dataHash = s; - return this; - } - - public DbFileSources.Data decodeSourceData(byte[] binaryData) { - try { - return decodeRegularSourceData(binaryData); - } catch (IOException e) { - throw new IllegalStateException( - format("Fail to decompress and deserialize source data [id=%s,fileUuid=%s,projectUuid=%s]", id, fileUuid, projectUuid), - e); - } - } - - private static DbFileSources.Data decodeRegularSourceData(byte[] binaryData) throws IOException { - try (LZ4BlockInputStream lz4Input = new LZ4BlockInputStream(new ByteArrayInputStream(binaryData))) { - return DbFileSources.Data.parseFrom(lz4Input); - } catch (InvalidProtocolBufferException e) { - if (SIZE_LIMIT_EXCEEDED_EXCEPTION_MESSAGE.equals(e.getMessage())) { - return decodeHugeSourceData(binaryData); - } - throw e; - } - } - - private static DbFileSources.Data decodeHugeSourceData(byte[] binaryData) throws IOException { - try (LZ4BlockInputStream lz4Input = new LZ4BlockInputStream(new ByteArrayInputStream(binaryData))) { - CodedInputStream input = CodedInputStream.newInstance(lz4Input); - input.setSizeLimit(Integer.MAX_VALUE); - return DbFileSources.Data.parseFrom(input); - } - } - - /** - * Serialize and compress protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - * in the column BINARY_DATA. - */ - public static byte[] encodeSourceData(DbFileSources.Data data) { - ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); - LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(byteOutput); - try { - data.writeTo(compressedOutput); - compressedOutput.close(); - return byteOutput.toByteArray(); - } catch (IOException e) { - throw new IllegalStateException("Fail to serialize and compress source data", e); - } finally { - IOUtils.closeQuietly(compressedOutput); - } - } - - public static List<DbFileSources.Test> decodeTestData(byte[] binaryData) { - // stream is always closed - return decodeTestData(new ByteArrayInputStream(binaryData)); - } - - /** - * Decompress and deserialize content of column FILE_SOURCES.BINARY_DATA. - * The parameter "input" is always closed by this method. - */ - public static List<DbFileSources.Test> decodeTestData(InputStream binaryInput) { - LZ4BlockInputStream lz4Input = null; - List<DbFileSources.Test> tests = new ArrayList<>(); - try { - lz4Input = new LZ4BlockInputStream(binaryInput); - - DbFileSources.Test currentTest; - do { - currentTest = DbFileSources.Test.parseDelimitedFrom(lz4Input); - if (currentTest != null) { - tests.add(currentTest); - } - } while (currentTest != null); - return tests; - } catch (IOException e) { - throw new IllegalStateException("Fail to decompress and deserialize source data", e); - } finally { - IOUtils.closeQuietly(lz4Input); - } - } - - /** - * Serialize and compress protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - * in the column BINARY_DATA. - */ - public static byte[] encodeTestData(List<DbFileSources.Test> tests) { - ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); - LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(byteOutput); - try { - for (DbFileSources.Test test : tests) { - test.writeDelimitedTo(compressedOutput); - } - compressedOutput.close(); - return byteOutput.toByteArray(); - } catch (IOException e) { - throw new IllegalStateException("Fail to serialize and compress source tests", e); - } finally { - IOUtils.closeQuietly(compressedOutput); - } - } - - /** - * Compressed value of serialized protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - */ - public byte[] getBinaryData() { - return binaryData; - } - - /** - * Set compressed value of the protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - */ - public FileSourceDto setBinaryData(byte[] data) { - this.binaryData = data; - return this; - } - - /** - * Compressed value of serialized protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - */ - public DbFileSources.Data getSourceData() { - return decodeSourceData(binaryData); - } - - public FileSourceDto setSourceData(DbFileSources.Data data) { - this.dataType = Type.SOURCE; - this.binaryData = encodeSourceData(data); - return this; - } - - /** - * Compressed value of serialized protobuf message {@link org.sonar.db.protobuf.DbFileSources.Data} - */ - public List<DbFileSources.Test> getTestData() { - return decodeTestData(binaryData); - } - - public FileSourceDto setTestData(List<DbFileSources.Test> data) { - this.dataType = Type.TEST; - this.binaryData = encodeTestData(data); - return this; - } - - @CheckForNull - public String getLineHashes() { - return lineHashes; - } - - public FileSourceDto setLineHashes(@Nullable String lineHashes) { - this.lineHashes = lineHashes; - return this; - } - - @CheckForNull - public String getSrcHash() { - return srcHash; - } - - /** - * Hash of file content. Value is computed by batch. - */ - public FileSourceDto setSrcHash(@Nullable String srcHash) { - this.srcHash = srcHash; - return this; - } - - public long getCreatedAt() { - return createdAt; - } - - public FileSourceDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } - - public long getUpdatedAt() { - return updatedAt; - } - - public FileSourceDto setUpdatedAt(long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public String getDataType() { - return dataType; - } - - public FileSourceDto setDataType(String dataType) { - this.dataType = dataType; - return this; - } - - public String getRevision() { - return revision; - } - - public FileSourceDto setRevision(@Nullable String revision) { - this.revision = revision; - return this; - } - - public static class Type { - public static final String SOURCE = "SOURCE"; - public static final String TEST = "TEST"; - - private Type() { - // utility class - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/source/FileSourceMapper.java b/sonar-db/src/main/java/org/sonar/db/source/FileSourceMapper.java deleted file mode 100644 index 3b633dd2fa5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/source/FileSourceMapper.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.source; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface FileSourceMapper { - - List<FileSourceDto> selectHashesForProject(@Param("projectUuid") String projectUuid, @Param("dataType") String dataType); - - @CheckForNull - FileSourceDto select(@Param("fileUuid") String fileUuid, @Param("dataType") String dataType); - - void insert(FileSourceDto dto); - - void update(FileSourceDto dto); -} diff --git a/sonar-db/src/main/java/org/sonar/db/source/package-info.java b/sonar-db/src/main/java/org/sonar/db/source/package-info.java deleted file mode 100644 index dbf389c86dd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/source/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.source; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/user/AuthorDao.java b/sonar-db/src/main/java/org/sonar/db/user/AuthorDao.java deleted file mode 100644 index 862bcf4d9ee..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/AuthorDao.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Collection; -import java.util.Date; -import java.util.List; -import org.apache.ibatis.session.SqlSession; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -/** - * Be careful when updating this class because it's used by the Dev Cockpit plugin. - */ -public class AuthorDao implements Dao { - - public AuthorDto selectByLogin(DbSession session, String login) { - return getMapper(session).selectByLogin(login); - } - - public int countDeveloperLogins(DbSession session, long developerId) { - return getMapper(session).countDeveloperLogins(developerId); - } - - public void insertAuthor(DbSession session, String login, long personId) { - Date now = new Date(); - AuthorDto authorDto = new AuthorDto() - .setLogin(login) - .setPersonId(personId) - .setCreatedAt(now) - .setUpdatedAt(now); - - getMapper(session).insert(authorDto); - } - - public List<String> selectScmAccountsByDeveloperUuids(final DbSession session, Collection<String> developerUuids) { - return executeLargeInputs(developerUuids, getMapper(session)::selectScmAccountsByDeveloperUuids); - } - - private static AuthorMapper getMapper(SqlSession session) { - return session.getMapper(AuthorMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/AuthorDto.java b/sonar-db/src/main/java/org/sonar/db/user/AuthorDto.java deleted file mode 100644 index 00b93c40a64..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/AuthorDto.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Date; - -/** - * @since 3.0 - */ -public final class AuthorDto { - - private Long id; - private Long personId; - private String login; - private Date createdAt; - private Date updatedAt; - - public Long getId() { - return id; - } - - public AuthorDto setId(Long id) { - this.id = id; - return this; - } - - public Long getPersonId() { - return personId; - } - - public AuthorDto setPersonId(Long personId) { - this.personId = personId; - return this; - } - - public String getLogin() { - return login; - } - - public AuthorDto setLogin(String login) { - this.login = login; - return this; - } - - public Date getCreatedAt() { - return createdAt;// NOSONAR May expose internal representation by returning reference to mutable object - } - - public AuthorDto setCreatedAt(Date createdAt) { - this.createdAt = createdAt;// NOSONAR May expose internal representation by incorporating reference to mutable object - return this; - } - - public Date getUpdatedAt() { - return updatedAt;// NOSONAR May expose internal representation by returning reference to mutable object - } - - public AuthorDto setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt;// NOSONAR May expose internal representation by incorporating reference to mutable object - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/AuthorMapper.java b/sonar-db/src/main/java/org/sonar/db/user/AuthorMapper.java deleted file mode 100644 index 63321fc7687..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/AuthorMapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Collection; -import java.util.List; -import org.apache.ibatis.annotations.Param; - -/** - * @since 3.0 - */ -public interface AuthorMapper { - - AuthorDto selectByLogin(String login); - - void insert(AuthorDto authorDto); - - int countDeveloperLogins(long developerId); - - List<String> selectScmAccountsByDeveloperUuids(@Param("uuids") Collection<String> uuids); -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupDao.java b/sonar-db/src/main/java/org/sonar/db/user/GroupDao.java deleted file mode 100644 index 22fb347ada5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupDao.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.apache.ibatis.session.RowBounds; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DatabaseUtils; -import org.sonar.db.DbSession; -import org.sonar.db.WildcardPosition; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class GroupDao implements Dao { - - private final System2 system; - - public GroupDao(System2 system) { - this.system = system; - } - - /** - * @param dbSession - * @param organizationUuid non-null UUID of organization (no support of "default" organization) - * @param name non-null group name - * @return the group with the given organization key and name - */ - public Optional<GroupDto> selectByName(DbSession dbSession, String organizationUuid, String name) { - return Optional.ofNullable(mapper(dbSession).selectByName(organizationUuid, name)); - } - - public List<GroupDto> selectByNames(DbSession dbSession, String organizationUuid, Collection<String> names) { - return executeLargeInputs(names, pageOfNames -> mapper(dbSession).selectByNames(organizationUuid, pageOfNames)); - } - - @CheckForNull - public GroupDto selectById(DbSession dbSession, int groupId) { - return mapper(dbSession).selectById(groupId); - } - - public List<GroupDto> selectByIds(DbSession dbSession, List<Integer> ids) { - return executeLargeInputs(ids, mapper(dbSession)::selectByIds); - } - - public void deleteById(DbSession dbSession, int groupId) { - mapper(dbSession).deleteById(groupId); - } - - public void deleteByOrganization(DbSession dbSession, String organizationUuid) { - mapper(dbSession).deleteByOrganization(organizationUuid); - } - - public int countByQuery(DbSession session, String organizationUuid, @Nullable String query) { - return mapper(session).countByQuery(organizationUuid, groupSearchToSql(query)); - } - - public List<GroupDto> selectByQuery(DbSession session, String organizationUuid, @Nullable String query, int offset, int limit) { - return mapper(session).selectByQuery(organizationUuid, groupSearchToSql(query), new RowBounds(offset, limit)); - } - - public GroupDto insert(DbSession session, GroupDto item) { - Date createdAt = new Date(system.now()); - item.setCreatedAt(createdAt) - .setUpdatedAt(createdAt); - mapper(session).insert(item); - return item; - } - - public GroupDto update(DbSession session, GroupDto item) { - item.setUpdatedAt(new Date(system.now())); - mapper(session).update(item); - return item; - } - - public List<GroupDto> selectByUserLogin(DbSession session, String login) { - return mapper(session).selectByUserLogin(login); - } - - @CheckForNull - private static String groupSearchToSql(@Nullable String query) { - if (query == null) { - return null; - } - - String upperCasedNameQuery = StringUtils.upperCase(query, Locale.ENGLISH); - return DatabaseUtils.buildLikeValue(upperCasedNameQuery, WildcardPosition.BEFORE_AND_AFTER); - } - - public List<GroupDto> selectByOrganizationUuid(DbSession dbSession, String organizationUuid) { - return mapper(dbSession).selectByOrganizationUuid(organizationUuid); - } - - private static GroupMapper mapper(DbSession session) { - return session.getMapper(GroupMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupDto.java b/sonar-db/src/main/java/org/sonar/db/user/GroupDto.java deleted file mode 100644 index 8156414f47a..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupDto.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class GroupDto { - - private Integer id; - private String name; - private String description; - private String organizationUuid; - private Date createdAt; - private Date updatedAt; - - public Integer getId() { - return id; - } - - public GroupDto setId(Integer id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public GroupDto setName(String name) { - this.name = name; - return this; - } - - @CheckForNull - public String getDescription() { - return description; - } - - public GroupDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - public String getOrganizationUuid() { - return organizationUuid; - } - - public GroupDto setOrganizationUuid(String s) { - this.organizationUuid = s; - return this; - } - - public GroupDto setCreatedAt(Date d) { - this.createdAt = d; - return this; - } - - public GroupDto setUpdatedAt(Date d) { - this.updatedAt = d; - return this; - } - - public Date getCreatedAt() { - return this.createdAt; - } - - public Date getUpdatedAt() { - return this.updatedAt; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("GroupDto{"); - sb.append("id=").append(id); - sb.append(", name='").append(name).append('\''); - sb.append(", description='").append(description).append('\''); - sb.append(", organizationUuid='").append(organizationUuid).append('\''); - sb.append(", createdAt=").append(createdAt); - sb.append(", updatedAt=").append(updatedAt); - sb.append('}'); - return sb.toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupMapper.java b/sonar-db/src/main/java/org/sonar/db/user/GroupMapper.java deleted file mode 100644 index 3f70d26a190..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface GroupMapper { - - @CheckForNull - GroupDto selectById(int groupId); - - List<GroupDto> selectByUserLogin(String userLogin); - - List<GroupDto> selectByNames(@Param("organizationUuid") String organizationUuid, @Param("names") List<String> names); - - void insert(GroupDto groupDto); - - void update(GroupDto item); - - List<GroupDto> selectByQuery(@Param("organizationUuid") String organizationUuid, @Nullable @Param("query") String query, RowBounds rowBounds); - - int countByQuery(@Param("organizationUuid") String organizationUuid, @Nullable @Param("query") String query); - - /** - * Counts the number of groups with the specified id belonging to the specified organization. - * - * @return 1 or 0. Either because the organization uuid is not the one of the group or because the group does not exist - */ - int countGroupByOrganizationAndId(@Param("organizationUuid") String organizationUuid, @Param("groupId") int groupId); - - void deleteById(int groupId); - - void deleteByOrganization(@Param("organizationUuid") String organizationUuid); - - @CheckForNull - GroupDto selectByName(@Param("organizationUuid") String organizationUuid, @Param("name") String name); - - List<GroupDto> selectByOrganizationUuid(@Param("organizationUuid") String organizationUuid); - - List<GroupDto> selectByIds(@Param("ids") List<Integer> ids); -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDao.java b/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDao.java deleted file mode 100644 index bde120c6167..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDao.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.apache.ibatis.session.RowBounds; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class GroupMembershipDao implements Dao { - - public List<GroupMembershipDto> selectGroups(DbSession session, GroupMembershipQuery query, Integer userId, int offset, int limit) { - Map<String, Object> params = ImmutableMap.of("query", query, "userId", userId); - return mapper(session).selectGroups(params, new RowBounds(offset, limit)); - } - - public int countGroups(DbSession session, GroupMembershipQuery query, Integer userId) { - Map<String, Object> params = ImmutableMap.of("query", query, "userId", userId); - return mapper(session).countGroups(params); - } - - public List<UserMembershipDto> selectMembers(DbSession session, UserMembershipQuery query, int offset, int limit) { - Map<String, Object> params = ImmutableMap.of("query", query, "groupId", query.groupId()); - return mapper(session).selectMembers(params, new RowBounds(offset, limit)); - } - - public int countMembers(DbSession session, UserMembershipQuery query) { - Map<String, Object> params = ImmutableMap.of("query", query, "groupId", query.groupId()); - return mapper(session).countMembers(params); - } - - public Map<String, Integer> countUsersByGroups(DbSession session, Collection<Integer> groupIds) { - Map<String, Integer> result = Maps.newHashMap(); - executeLargeInputs( - groupIds, - input -> { - List<GroupUserCount> userCounts = mapper(session).countUsersByGroup(input); - for (GroupUserCount count : userCounts) { - result.put(count.groupName(), count.userCount()); - } - return userCounts; - }); - - return result; - } - - public List<Integer> selectGroupIdsByUserId(DbSession dbSession, int userId) { - return mapper(dbSession).selectGroupIdsByUserId(userId); - } - - public Multimap<String, String> selectGroupsByLogins(DbSession session, Collection<String> logins) { - Multimap<String, String> result = ArrayListMultimap.create(); - executeLargeInputs( - logins, - input -> { - List<LoginGroup> groupMemberships = mapper(session).selectGroupsByLogins(input); - for (LoginGroup membership : groupMemberships) { - result.put(membership.login(), membership.groupName()); - } - return groupMemberships; - }); - - return result; - } - - private static GroupMembershipMapper mapper(DbSession session) { - return session.getMapper(GroupMembershipMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDto.java b/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDto.java deleted file mode 100644 index 1307352fd60..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipDto.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -/** - * @since 4.1 - */ -public class GroupMembershipDto { - - private Long id; - private String name; - private String description; - private Integer userId; - - public Long getId() { - return id; - } - - public GroupMembershipDto setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public GroupMembershipDto setName(String name) { - this.name = name; - return this; - } - - @CheckForNull - public String getDescription() { - return description; - } - - public GroupMembershipDto setDescription(@Nullable String description) { - this.description = description; - return this; - } - - @CheckForNull - public Integer getUserId() { - return userId; - } - - public GroupMembershipDto setUserId(@Nullable Integer userId) { - this.userId = userId; - return this; - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipMapper.java b/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipMapper.java deleted file mode 100644 index 6bf021b158e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipMapper.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import java.util.Map; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.session.RowBounds; - -public interface GroupMembershipMapper { - - List<GroupMembershipDto> selectGroups(Map<String, Object> params, RowBounds rowBounds); - - int countGroups(Map<String, Object> params); - - List<UserMembershipDto> selectMembers(Map<String, Object> params, RowBounds rowBounds); - - int countMembers(Map<String, Object> params); - - List<GroupUserCount> countUsersByGroup(@Param("groupIds") List<Integer> groupIds); - - List<LoginGroup> selectGroupsByLogins(@Param("logins") List<String> logins); - - List<Integer> selectGroupIdsByUserId(@Param("userId") int userId); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipQuery.java b/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipQuery.java deleted file mode 100644 index 5876cd07082..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupMembershipQuery.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; - -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -public class GroupMembershipQuery { - - public static final int DEFAULT_PAGE_INDEX = 1; - public static final int DEFAULT_PAGE_SIZE = 100; - - public static final String ANY = "ANY"; - public static final String IN = "IN"; - public static final String OUT = "OUT"; - public static final Set<String> AVAILABLE_MEMBERSHIP = ImmutableSet.of(ANY, IN, OUT); - - private final String login; - private final String membership; - - private final String groupSearch; - - // for internal use in MyBatis - final String groupSearchSql; - - // max results per page - private final int pageSize; - - // index of selected page. Start with 1. - private final int pageIndex; - - private GroupMembershipQuery(Builder builder) { - this.login = builder.login; - this.membership = builder.membership; - this.groupSearch = builder.groupSearch; - this.groupSearchSql = groupSearchToSql(groupSearch); - - this.pageSize = builder.pageSize; - this.pageIndex = builder.pageIndex; - } - - private static String groupSearchToSql(@Nullable String s) { - String sql = null; - if (s != null) { - sql = StringUtils.replace(StringUtils.upperCase(s), "%", "/%"); - sql = StringUtils.replace(sql, "_", "/_"); - sql = "%" + sql + "%"; - } - return sql; - } - - public String login() { - return login; - } - - @CheckForNull - public String membership() { - return membership; - } - - /** - * Search for groups containing a given string - */ - @CheckForNull - public String groupSearch() { - return groupSearch; - } - - public int pageSize() { - return pageSize; - } - - public int pageIndex() { - return pageIndex; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String login; - private String membership; - private String groupSearch; - - private Integer pageIndex = DEFAULT_PAGE_INDEX; - private Integer pageSize = DEFAULT_PAGE_SIZE; - - private Builder() { - } - - public Builder login(String login) { - this.login = login; - return this; - } - - public Builder membership(@Nullable String membership) { - this.membership = membership; - return this; - } - - public Builder groupSearch(@Nullable String s) { - this.groupSearch = StringUtils.defaultIfBlank(s, null); - return this; - } - - public Builder pageSize(@Nullable Integer i) { - this.pageSize = i; - return this; - } - - public Builder pageIndex(@Nullable Integer i) { - this.pageIndex = i; - return this; - } - - private void initMembership() { - membership = firstNonNull(membership, ANY); - checkArgument(AVAILABLE_MEMBERSHIP.contains(membership), - "Membership is not valid (got " + membership + "). Availables values are " + AVAILABLE_MEMBERSHIP); - } - - private void initPageSize() { - pageSize = firstNonNull(pageSize, DEFAULT_PAGE_SIZE); - } - - private void initPageIndex() { - pageIndex = firstNonNull(pageIndex, DEFAULT_PAGE_INDEX); - checkArgument(pageIndex > 0, "Page index must be greater than 0 (got " + pageIndex + ")"); - } - - public GroupMembershipQuery build() { - checkNotNull(login, "User login cant be null."); - initMembership(); - initPageIndex(); - initPageSize(); - return new GroupMembershipQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/GroupUserCount.java b/sonar-db/src/main/java/org/sonar/db/user/GroupUserCount.java deleted file mode 100644 index 8aac6b7a878..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/GroupUserCount.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -public class GroupUserCount { - - private String groupName; - private int userCount; - - public String groupName() { - return groupName; - } - - public int userCount() { - return userCount; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/LoginGroup.java b/sonar-db/src/main/java/org/sonar/db/user/LoginGroup.java deleted file mode 100644 index 0a2be3b7ce3..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/LoginGroup.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -public class LoginGroup { - - private String login; - private String groupName; - - public String login() { - return login; - } - - public String groupName() { - return groupName; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/RoleDao.java b/sonar-db/src/main/java/org/sonar/db/user/RoleDao.java deleted file mode 100644 index 66e14f432a1..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/RoleDao.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -public class RoleDao implements Dao { - - /** - * All the projects on which the user has {@code permission}, directly or through - * groups. - */ - public List<Long> selectComponentIdsByPermissionAndUserId(DbSession dbSession, String permission, int userId) { - return mapper(dbSession).selectComponentIdsByPermissionAndUserId(permission, userId); - } - - public void deleteGroupRolesByGroupId(DbSession session, int groupId) { - mapper(session).deleteGroupRolesByGroupId(groupId); - } - - private static RoleMapper mapper(DbSession session) { - return session.getMapper(RoleMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/RoleMapper.java b/sonar-db/src/main/java/org/sonar/db/user/RoleMapper.java deleted file mode 100644 index 6e9e45a4b03..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/RoleMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface RoleMapper { - - List<Long> selectComponentIdsByPermissionAndUserId(@Param("permission") String permission, @Param("userId") int userId); - - void deleteGroupRolesByGroupId(int groupId); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserDao.java b/sonar-db/src/main/java/org/sonar/db/user/UserDao.java deleted file mode 100644 index 754cb376ef5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserDao.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import org.sonar.api.user.UserQuery; -import org.sonar.api.utils.System2; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; -import org.sonar.db.RowNotFoundException; - -import static com.google.common.collect.FluentIterable.from; -import static java.util.Arrays.asList; -import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class UserDao implements Dao { - - private final MyBatis mybatis; - private final System2 system2; - - public UserDao(MyBatis mybatis, System2 system2) { - this.mybatis = mybatis; - this.system2 = system2; - } - - public UserDto selectUserById(int userId) { - try (DbSession session = mybatis.openSession(false)) { - return selectUserById(session, userId); - } - } - - public UserDto selectUserById(DbSession session, int userId) { - return mapper(session).selectUser(userId); - } - - /** - * Select users by ids, including disabled users. An empty list is returned - * if list of ids is empty, without any db round trips. - * - * Used by the Governance plugin - */ - public List<UserDto> selectByIds(DbSession session, Collection<Integer> ids) { - return executeLargeInputs(ids, mapper(session)::selectByIds); - } - - /** - * Search for user by login. Disabled users are ignored. - * - * @return the user, null if user not found - */ - @CheckForNull - public UserDto selectActiveUserByLogin(String login) { - try (DbSession session = mybatis.openSession(false)) { - return selectActiveUserByLogin(session, login); - } - } - - @CheckForNull - public UserDto selectActiveUserByLogin(DbSession session, String login) { - UserMapper mapper = mapper(session); - return mapper.selectUserByLogin(login); - } - - /** - * Select users by logins, including disabled users. An empty list is returned - * if list of logins is empty, without any db round trips. - */ - public List<UserDto> selectByLogins(DbSession session, Collection<String> logins) { - return executeLargeInputs(logins, mapper(session)::selectByLogins); - } - - /** - * @deprecated since 6.0 please use {@link #selectByLogins(DbSession, Collection)} instead - */ - @Deprecated - public List<UserDto> selectByLogins(Collection<String> logins) { - try (DbSession session = mybatis.openSession(false)) { - return selectByLogins(session, logins); - } - } - - /** - * Gets a list users by their logins. The result does NOT contain {@code null} values for users not found, so - * the size of result may be less than the number of keys. - * A single user is returned if input keys contain multiple occurrences of a key. - * <p>Contrary to {@link #selectByLogins(DbSession, Collection)}, results are in the same order as input keys.</p> - */ - public List<UserDto> selectByOrderedLogins(DbSession session, Collection<String> logins) { - List<UserDto> unordered = selectByLogins(session, logins); - return from(logins).transform(new LoginToUser(unordered)).filter(Predicates.notNull()).toList(); - } - - public List<UserDto> selectUsers(UserQuery query) { - try (DbSession session = mybatis.openSession(false)) { - return selectUsers(session, query); - } - } - - public List<UserDto> selectUsers(DbSession dbSession, UserQuery query) { - return mapper(dbSession).selectUsers(query); - } - - public long countRootUsersButLogin(DbSession dbSession, String login) { - return mapper(dbSession).countRootUsersButLogin(login); - } - - public UserDto insert(DbSession session, UserDto dto) { - mapper(session).insert(dto); - return dto; - } - - public UserDto update(DbSession session, UserDto dto) { - mapper(session).update(dto); - return dto; - } - - public void setRoot(DbSession session, String login, boolean root) { - mapper(session).setRoot(login, root, system2.now()); - } - - /** - * Deactivate a user and drops all his preferences. - * @return false if the user does not exist, true if the existing user has been deactivated - */ - public boolean deactivateUserByLogin(DbSession dbSession, String login) { - UserMapper mapper = mapper(dbSession); - UserDto dto = mapper.selectUserByLogin(login); - if (dto == null) { - return false; - } - - mapper.removeUserFromGroups(dto.getId()); - mapper.deleteUserProperties(dto.getId()); - mapper.deleteUserRoles(dto.getId()); - mapper.deletePropertiesMatchingLogin(asList(DEFAULT_ISSUE_ASSIGNEE), dto.getLogin()); - mapper.deactivateUser(dto.getId(), system2.now()); - dbSession.commit(); - return true; - } - - @CheckForNull - public UserDto selectByLogin(DbSession session, String login) { - return mapper(session).selectByLogin(login); - } - - public UserDto selectOrFailByLogin(DbSession session, String login) { - UserDto user = selectByLogin(session, login); - if (user == null) { - throw new RowNotFoundException(String.format("User with login '%s' has not been found", login)); - } - return user; - } - - public List<UserDto> selectByScmAccountOrLoginOrEmail(DbSession session, String scmAccountOrLoginOrEmail) { - String like = new StringBuilder().append("%") - .append(UserDto.SCM_ACCOUNTS_SEPARATOR).append(scmAccountOrLoginOrEmail) - .append(UserDto.SCM_ACCOUNTS_SEPARATOR).append("%").toString(); - return mapper(session).selectNullableByScmAccountOrLoginOrEmail(scmAccountOrLoginOrEmail, like); - } - - /** - * Check if an active user with the given email exits in database - * - * Please note that email is case insensitive, result for searching 'mail@email.com' or 'Mail@Email.com' will be the same - */ - public boolean doesEmailExist(DbSession dbSession, String email) { - return mapper(dbSession).countByEmail(email.toLowerCase(Locale.ENGLISH)) > 0; - } - - protected UserMapper mapper(DbSession session) { - return session.getMapper(UserMapper.class); - } - - private static class LoginToUser implements Function<String, UserDto> { - private final Map<String, UserDto> map = new HashMap<>(); - - private LoginToUser(Collection<UserDto> unordered) { - for (UserDto dto : unordered) { - map.put(dto.getLogin(), dto); - } - } - - @Override - public UserDto apply(@Nonnull String login) { - return map.get(login); - } - } - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserDto.java b/sonar-db/src/main/java/org/sonar/db/user/UserDto.java deleted file mode 100644 index 7f41ce65250..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserDto.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang.StringUtils; -import org.sonar.core.user.DefaultUser; - -import static java.util.Objects.requireNonNull; - -/** - * @since 3.2 - */ -public class UserDto { - public static final char SCM_ACCOUNTS_SEPARATOR = '\n'; - - private Integer id; - private String login; - private String name; - private String email; - private boolean active = true; - private String scmAccounts; - private String externalIdentity; - private String externalIdentityProvider; - private String cryptedPassword; - private String salt; - private Long createdAt; - private Long updatedAt; - private boolean local = true; - private boolean root = false; - - public Integer getId() { - return id; - } - - public UserDto setId(Integer id) { - this.id = id; - return this; - } - - /** - * Spaces were authorized before SQ 5.4. - * For versions 5.4+ it's not possible to create a login with a space character. - */ - public String getLogin() { - return login; - } - - public UserDto setLogin(String login) { - this.login = login; - return this; - } - - public String getName() { - return name; - } - - public UserDto setName(String name) { - this.name = name; - return this; - } - - @CheckForNull - public String getEmail() { - return email; - } - - public UserDto setEmail(@Nullable String email) { - this.email = email; - return this; - } - - public boolean isActive() { - return active; - } - - public UserDto setActive(boolean b) { - this.active = b; - return this; - } - - @CheckForNull - public String getScmAccounts() { - return scmAccounts; - } - - public List<String> getScmAccountsAsList() { - return decodeScmAccounts(scmAccounts); - } - - public UserDto setScmAccounts(@Nullable String s) { - this.scmAccounts = s; - return this; - } - - public UserDto setScmAccounts(@Nullable List list) { - this.scmAccounts = encodeScmAccounts(list); - return this; - } - - @CheckForNull - public static String encodeScmAccounts(@Nullable List<String> scmAccounts) { - if (scmAccounts != null && !scmAccounts.isEmpty()) { - return String.format("%s%s%s", SCM_ACCOUNTS_SEPARATOR, StringUtils.join(scmAccounts, SCM_ACCOUNTS_SEPARATOR), SCM_ACCOUNTS_SEPARATOR); - } - return null; - } - - public static List<String> decodeScmAccounts(@Nullable String dbValue) { - if (dbValue == null) { - return new ArrayList<>(); - } else { - return Lists.newArrayList(Splitter.on(SCM_ACCOUNTS_SEPARATOR).omitEmptyStrings().split(dbValue)); - } - } - - public String getExternalIdentity() { - return externalIdentity; - } - - public UserDto setExternalIdentity(String authorithy) { - this.externalIdentity = authorithy; - return this; - } - - public String getExternalIdentityProvider() { - return externalIdentityProvider; - } - - public UserDto setExternalIdentityProvider(String externalIdentityProvider) { - this.externalIdentityProvider = externalIdentityProvider; - return this; - } - - public boolean isLocal() { - return local; - } - - public UserDto setLocal(boolean local) { - this.local = local; - return this; - } - - @CheckForNull - public String getCryptedPassword() { - return cryptedPassword; - } - - public UserDto setCryptedPassword(@Nullable String cryptedPassword) { - this.cryptedPassword = cryptedPassword; - return this; - } - - @CheckForNull - public String getSalt() { - return salt; - } - - public UserDto setSalt(@Nullable String salt) { - this.salt = salt; - return this; - } - - public Long getCreatedAt() { - return createdAt; - } - - public UserDto setCreatedAt(Long createdAt) { - this.createdAt = createdAt; - return this; - } - - public Long getUpdatedAt() { - return updatedAt; - } - - public UserDto setUpdatedAt(Long updatedAt) { - this.updatedAt = updatedAt; - return this; - } - - public boolean isRoot() { - return root; - } - - /** - * Setters is not accessible as MyBatis doesn't need setter to set the field and dedicated SQL requests must be used - * to update the root flag of a user: - * <ul> - * <li>a user can not be created root</li> - * <li>the generic update method of a user can not change its root flag</li> - * </ul> - */ - protected void setRoot(boolean root) { - this.root = root; - } - - public static String encryptPassword(String password, String salt) { - requireNonNull(password, "Password cannot be empty"); - requireNonNull(salt, "Salt cannot be empty"); - return DigestUtils.sha1Hex("--" + salt + "--" + password + "--"); - } - - public DefaultUser toUser() { - return new DefaultUser() - .setLogin(login) - .setName(name) - .setEmail(email) - .setActive(active); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserGroupDao.java b/sonar-db/src/main/java/org/sonar/db/user/UserGroupDao.java deleted file mode 100644 index 1e53f6a312e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserGroupDao.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -public class UserGroupDao implements Dao { - - public UserGroupDto insert(DbSession session, UserGroupDto dto) { - mapper(session).insert(dto); - return dto; - } - - public void delete(DbSession session, int groupId, int userId) { - mapper(session).delete(groupId, userId); - } - - public void deleteByGroupId(DbSession session, int groupId) { - mapper(session).deleteByGroupId(groupId); - } - - private static UserGroupMapper mapper(DbSession session) { - return session.getMapper(UserGroupMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserGroupDto.java b/sonar-db/src/main/java/org/sonar/db/user/UserGroupDto.java deleted file mode 100644 index 8e8443bf830..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserGroupDto.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -public class UserGroupDto { - - private int userId; - private int groupId; - - public int getUserId() { - return userId; - } - - public UserGroupDto setUserId(int userId) { - this.userId = userId; - return this; - } - - public int getGroupId() { - return groupId; - } - - public UserGroupDto setGroupId(int groupId) { - this.groupId = groupId; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserGroupMapper.java b/sonar-db/src/main/java/org/sonar/db/user/UserGroupMapper.java deleted file mode 100644 index ce0d053d701..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserGroupMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import org.apache.ibatis.annotations.Param; - -public interface UserGroupMapper { - - void insert(UserGroupDto dto); - - void delete(@Param("groupId") int groupId, @Param("userId") int userId); - - void deleteByGroupId(@Param("groupId") int groupId); -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserMapper.java b/sonar-db/src/main/java/org/sonar/db/user/UserMapper.java deleted file mode 100644 index eac60d442ea..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserMapper.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; -import org.sonar.api.user.UserQuery; - -public interface UserMapper { - - @CheckForNull - UserDto selectByLogin(String login); - - /** - * Search for a user by SCM account, login or email. - * Can return multiple results if an email is used by many users (For instance, technical account can use the same email as a none technical account) - */ - @CheckForNull - List<UserDto> selectNullableByScmAccountOrLoginOrEmail(@Param("scmAccount") String scmAccountOrLoginOrEmail, @Param("likeScmAccount") String likeScmAccount); - - @CheckForNull - UserDto selectUser(int userId); - - /** - * Select user by login. Note that disabled users are ignored. - */ - @CheckForNull - UserDto selectUserByLogin(String login); - - List<UserDto> selectUsers(UserQuery query); - - List<UserDto> selectByLogins(List<String> logins); - - List<UserDto> selectByIds(@Param("ids") List<Integer> ids); - - long countByEmail(String email); - - /** - * Count actives users which are root and which login is not the specified one. - */ - long countRootUsersButLogin(@Param("login") String login); - - void insert(UserDto userDto); - - void update(UserDto userDto); - - void setRoot(@Param("login") String login, @Param("root") boolean root, @Param("now") long now); - - void removeUserFromGroups(int userId); - - void deleteUserProperties(int userId); - - void deleteUserRoles(int userId); - - void deletePropertiesMatchingLogin(@Param("propertyKeys") List<String> propertyKeys, @Param("login") String login); - - void deactivateUser(@Param("id") int userId, @Param("now") long now); - -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserMembershipDto.java b/sonar-db/src/main/java/org/sonar/db/user/UserMembershipDto.java deleted file mode 100644 index a8b5dd6be1d..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserMembershipDto.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -public class UserMembershipDto { - - private Long id; - private Integer groupId; - private String login; - private String name; - - public Long getId() { - return id; - } - - public UserMembershipDto setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public UserMembershipDto setName(String name) { - this.name = name; - return this; - } - - @CheckForNull - public String getLogin() { - return login; - } - - public UserMembershipDto setLogin(@Nullable String login) { - this.login = login; - return this; - } - - @CheckForNull - public Integer getGroupId() { - return groupId; - } - - public UserMembershipDto setGroupId(@Nullable Integer groupId) { - this.groupId = groupId; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserMembershipQuery.java b/sonar-db/src/main/java/org/sonar/db/user/UserMembershipQuery.java deleted file mode 100644 index e93513c5191..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserMembershipQuery.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.collect.ImmutableSet; -import java.util.Locale; -import java.util.Set; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; - -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.sonar.db.DatabaseUtils.buildLikeValue; -import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; - -public class UserMembershipQuery { - - public static final int DEFAULT_PAGE_INDEX = 1; - public static final int DEFAULT_PAGE_SIZE = 100; - - public static final String ANY = "ANY"; - public static final String IN = "IN"; - public static final String OUT = "OUT"; - public static final Set<String> AVAILABLE_MEMBERSHIPS = ImmutableSet.of(ANY, IN, OUT); - - private final int groupId; - private final String membership; - - private final String memberSearch; - - // for internal use in MyBatis - final String memberSearchSql; - final String memberSearchSqlLowercase; - - // max results per page - private final int pageSize; - - // index of selected page. Start with 1. - private final int pageIndex; - - private UserMembershipQuery(Builder builder) { - this.groupId = builder.groupId; - this.membership = builder.membership; - this.memberSearch = builder.memberSearch; - this.memberSearchSql = memberSearch == null ? null : buildLikeValue(memberSearch, BEFORE_AND_AFTER); - this.memberSearchSqlLowercase = memberSearchSql == null ? null : memberSearchSql.toLowerCase(Locale.ENGLISH); - this.pageSize = builder.pageSize; - this.pageIndex = builder.pageIndex; - } - - public int groupId() { - return groupId; - } - - @CheckForNull - public String membership() { - return membership; - } - - /** - * Search for users email, login and name containing a given string - */ - @CheckForNull - public String memberSearch() { - return memberSearch; - } - - public int pageSize() { - return pageSize; - } - - public int pageIndex() { - return pageIndex; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private Integer groupId; - private String membership; - private String memberSearch; - - private Integer pageIndex = DEFAULT_PAGE_INDEX; - private Integer pageSize = DEFAULT_PAGE_SIZE; - - private Builder() { - } - - public Builder groupId(Integer groupId) { - this.groupId = groupId; - return this; - } - - public Builder membership(@Nullable String membership) { - this.membership = membership; - return this; - } - - public Builder memberSearch(@Nullable String s) { - this.memberSearch = StringUtils.defaultIfBlank(s, null); - return this; - } - - public Builder pageSize(@Nullable Integer i) { - this.pageSize = i; - return this; - } - - public Builder pageIndex(@Nullable Integer i) { - this.pageIndex = i; - return this; - } - - private void initMembership() { - membership = firstNonNull(membership, ANY); - checkArgument(AVAILABLE_MEMBERSHIPS.contains(membership), - "Membership is not valid (got " + membership + "). Availables values are " + AVAILABLE_MEMBERSHIPS); - } - - private void initPageSize() { - pageSize = firstNonNull(pageSize, DEFAULT_PAGE_SIZE); - } - - private void initPageIndex() { - pageIndex = firstNonNull(pageIndex, DEFAULT_PAGE_INDEX); - checkArgument(pageIndex > 0, "Page index must be greater than 0 (got " + pageIndex + ")"); - } - - public UserMembershipQuery build() { - checkNotNull(groupId, "Group ID cant be null."); - initMembership(); - initPageIndex(); - initPageSize(); - return new UserMembershipQuery(this); - } - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserTokenCount.java b/sonar-db/src/main/java/org/sonar/db/user/UserTokenCount.java deleted file mode 100644 index 027661218c1..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserTokenCount.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -public class UserTokenCount { - private String login; - private Integer tokenCount; - - public String getLogin() { - return login; - } - - public UserTokenCount setLogin(String login) { - this.login = login; - return this; - } - - public Integer tokenCount() { - return tokenCount; - } - - public UserTokenCount setTokenCount(Integer tokenCount) { - this.tokenCount = tokenCount; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserTokenDao.java b/sonar-db/src/main/java/org/sonar/db/user/UserTokenDao.java deleted file mode 100644 index f7210d9a1fd..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserTokenDao.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.base.Optional; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; -import org.sonar.db.RowNotFoundException; - -import static java.lang.String.format; -import static org.sonar.db.DatabaseUtils.executeLargeInputs; - -public class UserTokenDao implements Dao { - public void insert(DbSession dbSession, UserTokenDto userTokenDto) { - mapper(dbSession).insert(userTokenDto); - } - - public UserTokenDto selectOrFailByTokenHash(DbSession dbSession, String tokenHash) { - UserTokenDto userToken = mapper(dbSession).selectByTokenHash(tokenHash); - if (userToken == null) { - throw new RowNotFoundException(format("User token with token hash '%s' not found", tokenHash)); - } - - return userToken; - } - - public Optional<UserTokenDto> selectByTokenHash(DbSession dbSession, String tokenHash) { - return Optional.fromNullable(mapper(dbSession).selectByTokenHash(tokenHash)); - } - - public Optional<UserTokenDto> selectByLoginAndName(DbSession dbSession, String login, String name) { - return Optional.fromNullable(mapper(dbSession).selectByLoginAndName(login, name)); - } - - public List<UserTokenDto> selectByLogin(DbSession dbSession, String login) { - return mapper(dbSession).selectByLogin(login); - } - - public Map<String, Integer> countTokensByLogins(DbSession dbSession, List<String> logins) { - Map<String, Integer> result = new HashMap<>(logins.size()); - executeLargeInputs( - logins, - input -> { - List<UserTokenCount> userTokenCounts = mapper(dbSession).countTokensByLogins(input); - for (UserTokenCount userTokenCount : userTokenCounts) { - result.put(userTokenCount.getLogin(), userTokenCount.tokenCount()); - } - return userTokenCounts; - }); - - return result; - } - - public void deleteByLogin(DbSession dbSession, String login) { - mapper(dbSession).deleteByLogin(login); - } - - public void deleteByLoginAndName(DbSession dbSession, String login, String name) { - mapper(dbSession).deleteByLoginAndName(login, name); - } - - private static UserTokenMapper mapper(DbSession dbSession) { - return dbSession.getMapper(UserTokenMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserTokenDto.java b/sonar-db/src/main/java/org/sonar/db/user/UserTokenDto.java deleted file mode 100644 index e2b859725f2..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserTokenDto.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import static org.sonar.db.user.UserTokenValidator.checkTokenHash; -import static org.sonar.db.user.UserTokenValidator.checkTokenName; - -public class UserTokenDto { - private String login; - private String name; - private String tokenHash; - private Long createdAt; - - public String getLogin() { - return login; - } - - public UserTokenDto setLogin(String login) { - this.login = login; - return this; - } - - public String getName() { - return name; - } - - public UserTokenDto setName(String name) { - this.name = checkTokenName(name); - return this; - } - - public String getTokenHash() { - return tokenHash; - } - - public UserTokenDto setTokenHash(String tokenHash) { - this.tokenHash = checkTokenHash(tokenHash); - return this; - } - - public Long getCreatedAt() { - return createdAt; - } - - public UserTokenDto setCreatedAt(long createdAt) { - this.createdAt = createdAt; - return this; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserTokenMapper.java b/sonar-db/src/main/java/org/sonar/db/user/UserTokenMapper.java deleted file mode 100644 index 9a777fd139e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserTokenMapper.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.List; -import org.apache.ibatis.annotations.Param; - -public interface UserTokenMapper { - void insert(UserTokenDto userToken); - - UserTokenDto selectByTokenHash(String tokenHash); - - UserTokenDto selectByLoginAndName(@Param("login") String login, @Param("name") String name); - - List<UserTokenDto> selectByLogin(String login); - - void deleteByLogin(String login); - - void deleteByLoginAndName(@Param("login") String login, @Param("name") String name); - - List<UserTokenCount> countTokensByLogins(@Param("logins") List<String> logins); -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/UserTokenValidator.java b/sonar-db/src/main/java/org/sonar/db/user/UserTokenValidator.java deleted file mode 100644 index be4a82a32a9..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/UserTokenValidator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import static com.google.common.base.Preconditions.checkArgument; - -public class UserTokenValidator { - private static final int MAX_TOKEN_NAME_LENGTH = 100; - private static final int MAX_TOKEN_HASH_LENGTH = 255; - - private UserTokenValidator() { - // utility methods - } - - public static String checkTokenName(String name) { - checkArgument(name.length() <= MAX_TOKEN_NAME_LENGTH, "Token name length (%s) is longer than the maximum authorized (%s)", name.length(), MAX_TOKEN_NAME_LENGTH); - return name; - } - - static String checkTokenHash(String hash) { - checkArgument(hash.length() <= MAX_TOKEN_HASH_LENGTH, "Token hash length (%s) is longer than the maximum authorized (%s)", hash.length(), MAX_TOKEN_HASH_LENGTH); - return hash; - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/user/package-info.java b/sonar-db/src/main/java/org/sonar/db/user/package-info.java deleted file mode 100644 index 9affdd060c5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/user/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.user; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/version/SqTables.java b/sonar-db/src/main/java/org/sonar/db/version/SqTables.java deleted file mode 100644 index 968be26f244..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/version/SqTables.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.version; - -import com.google.common.collect.ImmutableSet; -import java.util.Set; - -public final class SqTables { - /** - * These tables are still involved in DB migrations, so potentially - * incorrect collation must be fixed so that joins with other - * tables are possible. - */ - public static final Set<String> OLD_DROPPED_TABLES = ImmutableSet.of( - "active_dashboards", - "activities", - "dashboards", - "issue_filters", - "issue_filter_favourites", - "measure_filters", - "measure_filter_favourites", - "resource_index", - "widgets", - "widget_properties"); - - /** - * List of all the tables. - * This list is hardcoded because we didn't succeed in using java.sql.DatabaseMetaData#getTables() in the same way - * for all the supported databases, particularly due to Oracle results. - */ - public static final Set<String> TABLES = ImmutableSet.of( - "active_rules", - "active_rule_parameters", - "authors", - "ce_activity", - "ce_queue", - "ce_task_input", - "ce_scanner_context", - "duplications_index", - "events", - "file_sources", - "groups", - "groups_users", - "group_roles", - "internal_properties", - "issues", - "issue_changes", - "loaded_templates", - "manual_measures", - "metrics", - "notifications", - "organizations", - "permission_templates", - "perm_templates_users", - "perm_templates_groups", - "perm_tpl_characteristics", - "quality_gates", - "quality_gate_conditions", - "projects", - "project_links", - "project_measures", - "project_qprofiles", - "properties", - "qprofile_changes", - "rules", - "rules_parameters", - "rules_profiles", - "rule_repositories", - "schema_migrations", - "snapshots", - "users", - "user_roles", - "user_tokens", - "webhook_deliveries"); - - private SqTables() { - // prevents instantiation - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/version/package-info.java b/sonar-db/src/main/java/org/sonar/db/version/package-info.java deleted file mode 100644 index 225b5e6fba6..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/version/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.version; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDao.java b/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDao.java deleted file mode 100644 index 1ce48f8df3e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDao.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.List; -import java.util.Optional; -import org.sonar.db.Dao; -import org.sonar.db.DbSession; - -public class WebhookDeliveryDao implements Dao { - - public Optional<WebhookDeliveryDto> selectByUuid(DbSession dbSession, String uuid) { - return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid)); - } - - /** - * All the deliveries for the specified component. Results are ordered by descending date. - */ - public List<WebhookDeliveryLiteDto> selectOrderedByComponentUuid(DbSession dbSession, String componentUuid) { - return mapper(dbSession).selectOrderedByComponentUuid(componentUuid); - } - - /** - * All the deliveries for the specified CE task. Results are ordered by descending date. - */ - public List<WebhookDeliveryLiteDto> selectOrderedByCeTaskUuid(DbSession dbSession, String ceTaskUuid) { - return mapper(dbSession).selectOrderedByCeTaskUuid(ceTaskUuid); - } - - public void insert(DbSession dbSession, WebhookDeliveryDto dto) { - mapper(dbSession).insert(dto); - } - - public void deleteComponentBeforeDate(DbSession dbSession, String componentUuid, long beforeDate) { - mapper(dbSession).deleteComponentBeforeDate(componentUuid, beforeDate); - } - - private static WebhookDeliveryMapper mapper(DbSession dbSession) { - return dbSession.getMapper(WebhookDeliveryMapper.class); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDto.java b/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDto.java deleted file mode 100644 index 5fbedbff388..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryDto.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; - -public class WebhookDeliveryDto extends WebhookDeliveryLiteDto<WebhookDeliveryDto> { - /** Error message if HTTP request cannot be sent, else null */ - private String errorStacktrace; - /** The payload that has been sent, cannot be null */ - private String payload; - - @CheckForNull - public String getErrorStacktrace() { - return errorStacktrace; - } - - public WebhookDeliveryDto setErrorStacktrace(@Nullable String s) { - this.errorStacktrace = s; - return this; - } - - @CheckForNull - public String getPayload() { - return payload; - } - - public WebhookDeliveryDto setPayload(@Nullable String s) { - this.payload = s; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("uuid", uuid) - .append("componentUuid", componentUuid) - .append("name", name) - .append("success", success) - .append("httpStatus", httpStatus) - .append("durationMs", durationMs) - .append("url", url) - .append("errorStacktrace", errorStacktrace) - .append("createdAt", createdAt) - .toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryLiteDto.java b/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryLiteDto.java deleted file mode 100644 index 22a5aa03cd5..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryLiteDto.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ToStringBuilder; - -public class WebhookDeliveryLiteDto<T extends WebhookDeliveryLiteDto> { - /** Technical unique identifier, can't be null */ - protected String uuid; - /** Component UUID, can't be null */ - protected String componentUuid; - /** Compute Engine task UUID, can't be null */ - protected String ceTaskUuid; - /** Name, can't be null */ - protected String name; - protected boolean success; - /** HTTP response status. Null if HTTP request cannot be sent */ - protected Integer httpStatus; - /** Duration in ms. Null if HTTP request cannot be sent */ - protected Integer durationMs; - /** URL, cannot be null */ - protected String url; - /** Time of delivery */ - protected long createdAt; - - public String getUuid() { - return uuid; - } - - public T setUuid(String s) { - this.uuid = s; - return (T)this; - } - - public String getComponentUuid() { - return componentUuid; - } - - public T setComponentUuid(String s) { - this.componentUuid = s; - return (T)this; - } - - public String getCeTaskUuid() { - return ceTaskUuid; - } - - public T setCeTaskUuid(String s) { - this.ceTaskUuid = s; - return (T)this; - } - - public String getName() { - return name; - } - - public T setName(String s) { - this.name = s; - return (T)this; - } - - public boolean isSuccess() { - return success; - } - - public T setSuccess(boolean b) { - this.success = b; - return (T)this; - } - - @CheckForNull - public Integer getHttpStatus() { - return httpStatus; - } - - public T setHttpStatus(@Nullable Integer i) { - this.httpStatus = i; - return (T)this; - } - - @CheckForNull - public Integer getDurationMs() { - return durationMs; - } - - public T setDurationMs(@Nullable Integer i) { - this.durationMs = i; - return (T)this; - } - - public String getUrl() { - return url; - } - - public T setUrl(String s) { - this.url = s; - return (T)this; - } - - public long getCreatedAt() { - return createdAt; - } - - public T setCreatedAt(long l) { - this.createdAt = l; - return (T)this; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("uuid", uuid) - .append("componentUuid", componentUuid) - .append("ceTaskUuid", ceTaskUuid) - .append("name", name) - .append("success", success) - .append("httpStatus", httpStatus) - .append("durationMs", durationMs) - .append("url", url) - .append("createdAt", createdAt) - .toString(); - } -} diff --git a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryMapper.java b/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryMapper.java deleted file mode 100644 index 1b13b0d4591..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/webhook/WebhookDeliveryMapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.apache.ibatis.annotations.Param; - -public interface WebhookDeliveryMapper { - - @CheckForNull - WebhookDeliveryDto selectByUuid(@Param("uuid") String uuid); - - List<WebhookDeliveryLiteDto> selectOrderedByComponentUuid(@Param("componentUuid") String componentUuid); - - List<WebhookDeliveryLiteDto> selectOrderedByCeTaskUuid(@Param("ceTaskUuid") String ceTaskUuid); - - void insert(WebhookDeliveryDto dto); - - void deleteComponentBeforeDate(@Param("componentUuid") String componentUuid, @Param("beforeDate") long beforeDate); -} diff --git a/sonar-db/src/main/java/org/sonar/db/webhook/package-info.java b/sonar-db/src/main/java/org/sonar/db/webhook/package-info.java deleted file mode 100644 index ccc107e118e..00000000000 --- a/sonar-db/src/main/java/org/sonar/db/webhook/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public 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.db.webhook; - -import javax.annotation.ParametersAreNonnullByDefault; - |