aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEric Hartmann <hartmann.eric@gmail.com>2017-06-14 16:05:29 +0200
committerSimon Brandhof <simon.brandhof@sonarsource.com>2017-06-15 00:14:36 +0200
commitd54a64ddb75b2125631a37f2158237870969d667 (patch)
treeef925c9c8c7024785d3dd6b1342c202101f0c2fd
parent764185d9211229e5dcafe885cfdcbfbfadf54ce7 (diff)
downloadsonarqube-d54a64ddb75b2125631a37f2158237870969d667.tar.gz
sonarqube-d54a64ddb75b2125631a37f2158237870969d667.zip
SONAR-9305 complete tests
-rw-r--r--server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java2
-rw-r--r--server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java15
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java4
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java2
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java12
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DeleteOrphansFromRulesProfiles.java2
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DropIsDefaultColumnFromRulesProfiles.java2
-rw-r--r--server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/PopulateTableDefaultQProfiles.java2
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java4
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImpl.java7
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java6
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java111
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactoryImpl.java141
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java2
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java2
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchAction.java3
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java11
-rw-r--r--server/sonar-server/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.java6
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java3
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java273
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperMediumTest.java410
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierMediumTest.java191
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java172
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java462
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java (renamed from server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryTest.java)4
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorMediumTest.java216
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java19
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java3
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java4
-rw-r--r--server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java4
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/bad-xml-backup.xml1
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/empty.xml5
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/expected-backup.xml30
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/keep_other_inherited_rules.xml12
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/not-xml-backup.txt1
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-child.xml18
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-parent.xml18
-rw-r--r--server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore.xml18
38 files changed, 918 insertions, 1280 deletions
diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java b/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java
index 6f82c926bd1..494d623402e 100644
--- a/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java
+++ b/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java
@@ -115,7 +115,7 @@ public class QualityProfileDao implements Dao {
mapper.updateRuleProfile(rulesProfile, new Date(now));
}
- private void doUpdate(QualityProfileMapper mapper, QProfileDto profile, long now) {
+ private static void doUpdate(QualityProfileMapper mapper, QProfileDto profile, long now) {
mapper.updateRuleProfile(RulesProfileDto.from(profile), new Date(now));
mapper.updateOrgQProfile(OrgQProfileDto.from(profile), now);
}
diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java
index 7ba24919da6..7f222a3e0ae 100644
--- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java
+++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java
@@ -65,6 +65,12 @@ public class RuleDbTester {
return rule;
}
+ public RuleDefinitionDto update(RuleDefinitionDto rule) {
+ db.getDbClient().ruleDao().update(db.getSession(), rule);
+ db.commit();
+ return rule;
+ }
+
@SafeVarargs
public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, OrganizationDto organization, Consumer<RuleMetadataDto>... populaters) {
RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, organization);
@@ -101,6 +107,15 @@ public class RuleDbTester {
return ruleDto;
}
+ public RuleDto updateRule(RuleDto ruleDto) {
+ update(ruleDto.getDefinition());
+ RuleMetadataDto metadata = ruleDto.getMetadata();
+ if (metadata.getOrganizationUuid() != null) {
+ db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata.setRuleId(ruleDto.getId()));
+ db.commit();
+ }
+ return ruleDto;
+ }
/**
* Create and persist a rule with random values.
*/
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java
index 37311afd3b5..10b5a96d54c 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java
@@ -40,7 +40,9 @@ public class TinyIntColumnDef extends AbstractColumnDef {
super(builder.columnName, builder.isNullable, null);
}
- public static Builder newTinyIntColumnDefBuilder() { return new Builder(); }
+ public static Builder newTinyIntColumnDefBuilder() {
+ return new Builder();
+ }
@Override
public String generateSqlType(Dialect dialect) {
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java
index d0a05ae05c8..cb1f12ed738 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java
@@ -115,7 +115,7 @@ public class Validations {
}
private static void checkDbIdentifierCharacters(String identifier, String identifierDesc) {
- checkArgument(identifier != null && identifier.length() > 0, "Identifier must not be empty");
+ checkArgument(identifier.length() > 0, "Identifier must not be empty");
checkArgument(
LOWER_CASE_ASCII_LETTERS_CHAR_MATCHER.or(DIGIT_CHAR_MATCHER).or(anyOf("_")).matchesAllOf(identifier),
"%s must be lower case and contain only alphanumeric chars or '_', got '%s'", identifierDesc, identifier);
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java
index 19fb80d7212..83cb0494945 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java
@@ -47,7 +47,7 @@ public class RenameColumnsBuilder {
private final Dialect dialect;
private final String tableName;
- private final List<Renaming> renamings = new ArrayList();
+ private final List<Renaming> renamings = new ArrayList<>();
public RenameColumnsBuilder(Dialect dialect, String tableName) {
this.dialect = dialect;
@@ -61,13 +61,12 @@ public class RenameColumnsBuilder {
public List<String> build() {
validateTableName(tableName);
- renamings.stream().forEach(
+ renamings.forEach(
r -> {
validateColumnName(r.getOldColumnName());
validateColumnName(r.getNewColumnName());
checkArgument(!r.getNewColumnName().equals(r.getOldColumnName()), "Column names must be different");
- }
- );
+ });
return createSqlStatement();
}
@@ -87,11 +86,10 @@ public class RenameColumnsBuilder {
default:
throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
}
- }
- ).collect(Collectors.toList());
+ }).collect(Collectors.toList());
}
- private class Renaming implements ColumnDef {
+ private static class Renaming implements ColumnDef {
private final ColumnDef columnDef;
private final String oldColumnName;
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DeleteOrphansFromRulesProfiles.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DeleteOrphansFromRulesProfiles.java
index a63fd8fd0ba..741f75edb20 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DeleteOrphansFromRulesProfiles.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DeleteOrphansFromRulesProfiles.java
@@ -42,7 +42,7 @@ public class DeleteOrphansFromRulesProfiles extends DataChange {
execute(context, "qprofile_changes", "delete from qprofile_changes where not exists ( select 1 from rules_profiles rp where rp.kee = qprofile_key)");
}
- private void execute(Context context, String tableName, String sql) throws SQLException {
+ private static void execute(Context context, String tableName, String sql) throws SQLException {
LOG.info("Deleting orphans from " + tableName);
context
.prepareUpsert(sql)
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DropIsDefaultColumnFromRulesProfiles.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DropIsDefaultColumnFromRulesProfiles.java
index d50668a5c24..48ee5935e16 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DropIsDefaultColumnFromRulesProfiles.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/DropIsDefaultColumnFromRulesProfiles.java
@@ -65,7 +65,7 @@ public class DropIsDefaultColumnFromRulesProfiles extends DdlChange {
}
}
- private void dropMssqlConstraint(Connection connection, String constraintName) throws SQLException {
+ private static void dropMssqlConstraint(Connection connection, String constraintName) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(format("ALTER TABLE %s DROP CONSTRAINT %s", TABLE_NAME, constraintName));
}
diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/PopulateTableDefaultQProfiles.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/PopulateTableDefaultQProfiles.java
index df0a8645e6e..721fa1ef36b 100644
--- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/PopulateTableDefaultQProfiles.java
+++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v65/PopulateTableDefaultQProfiles.java
@@ -82,7 +82,7 @@ public class PopulateTableDefaultQProfiles extends DataChange {
* profile marked as default for an organization and language.
* This method returns the buggy rows.
*/
- private Set<OrgLang> selectOrgsWithMultipleDefaultProfiles(Context context) throws SQLException {
+ private static Set<OrgLang> selectOrgsWithMultipleDefaultProfiles(Context context) throws SQLException {
Select rows = context.prepareSelect("select organization_uuid, language from rules_profiles " +
" where is_default = ? " +
" group by organization_uuid, language " +
diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java
index 17ef26d842b..45722f00c6a 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java
@@ -146,7 +146,7 @@ import org.sonar.server.qualityprofile.QProfileBackuperImpl;
import org.sonar.server.qualityprofile.QProfileComparison;
import org.sonar.server.qualityprofile.QProfileCopier;
import org.sonar.server.qualityprofile.QProfileExporters;
-import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.QProfileLookup;
import org.sonar.server.qualityprofile.QProfileResetImpl;
import org.sonar.server.qualityprofile.RuleActivator;
@@ -273,7 +273,7 @@ public class PlatformLevel4 extends PlatformLevel {
RuleActivator.class,
QProfileExporters.class,
RuleActivatorContextFactory.class,
- QProfileFactory.class,
+ QProfileFactoryImpl.class,
QProfileCopier.class,
QProfileBackuperImpl.class,
QProfileResetImpl.class,
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImpl.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImpl.java
index 222b5f1b736..de3c45dd3bc 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImpl.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImpl.java
@@ -52,16 +52,15 @@ public class BuiltInQProfileUpdateImpl implements BuiltInQProfileUpdate {
.collect(MoreCollectors.toHashSet());
List<ActiveRuleChange> changes = new ArrayList<>();
- builtIn.getActiveRules().forEach(ar -> {
+ builtIn.getActiveRules().forEach(ar -> {
RuleActivation activation = convert(ar);
toBeDeactivated.remove(activation.getRuleKey());
changes.addAll(ruleActivator.activateOnBuiltInRulesProfile(dbSession, activation, ruleProfile));
});
// these rules are not part of the built-in profile anymore
- toBeDeactivated.forEach(ruleKey -> {
- changes.addAll(ruleActivator.deactivateOnBuiltInRulesProfile(dbSession, ruleProfile, ruleKey, false));
- });
+ toBeDeactivated.forEach(ruleKey ->
+ changes.addAll(ruleActivator.deactivateOnBuiltInRulesProfile(dbSession, ruleProfile, ruleKey, false)));
dbSession.commit();
activeRuleIndexer.indexChanges(dbSession, changes);
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java
index b2fd1a69879..3eeed5368d5 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java
@@ -26,7 +26,6 @@ import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.TempFolder;
import org.sonar.db.DbClient;
@@ -79,11 +78,6 @@ public class QProfileCopier {
}
private void verify(QProfileDto fromProfile, QProfileName toProfileName) {
- if (!StringUtils.equals(fromProfile.getLanguage(), toProfileName.getLanguage())) {
- throw new IllegalArgumentException(String.format(
- "Source and target profiles do not have the same language: %s and %s",
- fromProfile.getLanguage(), toProfileName.getLanguage()));
- }
if (fromProfile.getName().equals(toProfileName.getName())) {
throw new IllegalArgumentException(String.format("Source and target profiles are equal: %s",
fromProfile.getName()));
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java
index e7bede32896..1e823900e4c 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java
@@ -19,97 +19,26 @@
*/
package org.sonar.server.qualityprofile;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import javax.annotation.Nullable;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.utils.System2;
-import org.sonar.core.util.UuidFactory;
-import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
-import org.sonar.db.qualityprofile.DefaultQProfileDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.server.ws.WsUtils.checkRequest;
/**
* Create, delete and set as default profile.
*/
-public class QProfileFactory {
-
- private final DbClient db;
- private final UuidFactory uuidFactory;
- private final System2 system2;
- private final ActiveRuleIndexer activeRuleIndexer;
-
- public QProfileFactory(DbClient db, UuidFactory uuidFactory, System2 system2, ActiveRuleIndexer activeRuleIndexer) {
- this.db = db;
- this.uuidFactory = uuidFactory;
- this.system2 = system2;
- this.activeRuleIndexer = activeRuleIndexer;
- }
-
- // ------------- CREATION
-
- private static OrganizationDto requireNonNull(@Nullable OrganizationDto organization) {
- Objects.requireNonNull(organization, "Organization is required, when creating a quality profile.");
- return organization;
- }
+public interface QProfileFactory {
- QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
- requireNonNull(organization);
- QProfileDto profile = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, name.getName(), name.getLanguage());
- if (profile == null) {
- profile = doCreate(dbSession, organization, name, false, false);
- } else {
- checkArgument(!profile.isBuiltIn(), "Operation forbidden for built-in Quality Profile '%s' with language '%s'", profile.getName(), profile.getLanguage());
- }
-
- return profile;
- }
+ QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name);
/**
* Create the quality profile in DB with the specified name.
*
* @throws BadRequestException if a quality profile with the specified name already exists
*/
- public QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
- requireNonNull(organization);
- QProfileDto dto = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, name.getName(), name.getLanguage());
- checkRequest(dto == null, "Quality profile already exists: %s", name);
- return doCreate(dbSession, organization, name, false, false);
- }
-
- private QProfileDto doCreate(DbSession dbSession, OrganizationDto organization, QProfileName name, boolean isDefault, boolean isBuiltIn) {
- if (StringUtils.isEmpty(name.getName())) {
- throw BadRequestException.create("quality_profiles.profile_name_cant_be_blank");
- }
- Date now = new Date(system2.now());
- QProfileDto dto = new QProfileDto()
- .setKee(uuidFactory.create())
- .setRulesProfileUuid(uuidFactory.create())
- .setName(name.getName())
- .setOrganizationUuid(organization.getUuid())
- .setLanguage(name.getLanguage())
- .setIsBuiltIn(isBuiltIn)
- .setRulesUpdatedAtAsDate(now);
- db.qualityProfileDao().insert(dbSession, dto);
- if (isDefault) {
- db.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(dto));
- }
- return dto;
- }
+ QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name);
- // ------------- DELETION
/**
* Deletes the specified profiles from database and Elasticsearch.
* All information related to custom profiles are deleted. Only association
@@ -117,37 +46,5 @@ public class QProfileFactory {
* The profiles marked as "default" are deleted too. Deleting a parent profile
* does not delete descendants if the latter are not listed.
*/
- public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
- if (profiles.isEmpty()) {
- return;
- }
-
- Set<String> uuids = new HashSet<>();
- List<QProfileDto> customProfiles = new ArrayList<>();
- Set<String> rulesProfileUuidsOfCustomProfiles = new HashSet<>();
- profiles.forEach(p -> {
- uuids.add(p.getKee());
- if (!p.isBuiltIn()) {
- customProfiles.add(p);
- rulesProfileUuidsOfCustomProfiles.add(p.getRulesProfileUuid());
- }
- });
-
- // tables org_qprofiles, default_qprofiles and project_qprofiles
- // are deleted whatever custom or built-in
- db.qualityProfileDao().deleteProjectAssociationsByProfileUuids(dbSession, uuids);
- db.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
- db.qualityProfileDao().deleteOrgQProfilesByUuids(dbSession, uuids);
-
- // tables related to rules_profiles and active_rules are deleted
- // only for custom profiles
- if (!rulesProfileUuidsOfCustomProfiles.isEmpty()) {
- db.activeRuleDao().deleteParametersByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
- db.activeRuleDao().deleteByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
- db.qProfileChangeDao().deleteByRulesProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
- db.qualityProfileDao().deleteRulesProfilesByUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
- }
- dbSession.commit();
- activeRuleIndexer.deleteByProfiles(customProfiles);
- }
+ void delete(DbSession dbSession, Collection<QProfileDto> profiles);
}
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactoryImpl.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactoryImpl.java
new file mode 100644
index 00000000000..5210dfff3df
--- /dev/null
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactoryImpl.java
@@ -0,0 +1,141 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.qualityprofile;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.commons.lang.StringUtils;
+import org.sonar.api.utils.System2;
+import org.sonar.core.util.UuidFactory;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.DefaultQProfileDto;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static org.sonar.server.ws.WsUtils.checkRequest;
+
+public class QProfileFactoryImpl implements QProfileFactory {
+
+ private final DbClient db;
+ private final UuidFactory uuidFactory;
+ private final System2 system2;
+ private final ActiveRuleIndexer activeRuleIndexer;
+
+ public QProfileFactoryImpl(DbClient db, UuidFactory uuidFactory, System2 system2, ActiveRuleIndexer activeRuleIndexer) {
+ this.db = db;
+ this.uuidFactory = uuidFactory;
+ this.system2 = system2;
+ this.activeRuleIndexer = activeRuleIndexer;
+ }
+
+ // ------------- CREATION
+
+ private static OrganizationDto requireNonNull(@Nullable OrganizationDto organization) {
+ Objects.requireNonNull(organization, "Organization is required, when creating a quality profile.");
+ return organization;
+ }
+
+ @Override
+ public QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
+ requireNonNull(organization);
+ QProfileDto profile = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, name.getName(), name.getLanguage());
+ if (profile == null) {
+ profile = doCreate(dbSession, organization, name, false, false);
+ } else {
+ checkArgument(!profile.isBuiltIn(), "Operation forbidden for built-in Quality Profile '%s' with language '%s'", profile.getName(), profile.getLanguage());
+ }
+
+ return profile;
+ }
+
+ @Override
+ public QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
+ requireNonNull(organization);
+ QProfileDto dto = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, name.getName(), name.getLanguage());
+ checkRequest(dto == null, "Quality profile already exists: %s", name);
+ return doCreate(dbSession, organization, name, false, false);
+ }
+
+ private QProfileDto doCreate(DbSession dbSession, OrganizationDto organization, QProfileName name, boolean isDefault, boolean isBuiltIn) {
+ if (StringUtils.isEmpty(name.getName())) {
+ throw BadRequestException.create("quality_profiles.profile_name_cant_be_blank");
+ }
+ Date now = new Date(system2.now());
+ QProfileDto dto = new QProfileDto()
+ .setKee(uuidFactory.create())
+ .setRulesProfileUuid(uuidFactory.create())
+ .setName(name.getName())
+ .setOrganizationUuid(organization.getUuid())
+ .setLanguage(name.getLanguage())
+ .setIsBuiltIn(isBuiltIn)
+ .setRulesUpdatedAtAsDate(now);
+ db.qualityProfileDao().insert(dbSession, dto);
+ if (isDefault) {
+ db.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(dto));
+ }
+ return dto;
+ }
+
+ // ------------- DELETION
+ @Override
+ public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
+ if (profiles.isEmpty()) {
+ return;
+ }
+
+ Set<String> uuids = new HashSet<>();
+ List<QProfileDto> customProfiles = new ArrayList<>();
+ Set<String> rulesProfileUuidsOfCustomProfiles = new HashSet<>();
+ profiles.forEach(p -> {
+ uuids.add(p.getKee());
+ if (!p.isBuiltIn()) {
+ customProfiles.add(p);
+ rulesProfileUuidsOfCustomProfiles.add(p.getRulesProfileUuid());
+ }
+ });
+
+ // tables org_qprofiles, default_qprofiles and project_qprofiles
+ // are deleted whatever custom or built-in
+ db.qualityProfileDao().deleteProjectAssociationsByProfileUuids(dbSession, uuids);
+ db.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
+ db.qualityProfileDao().deleteOrgQProfilesByUuids(dbSession, uuids);
+
+ // tables related to rules_profiles and active_rules are deleted
+ // only for custom profiles
+ if (!rulesProfileUuidsOfCustomProfiles.isEmpty()) {
+ db.activeRuleDao().deleteParametersByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
+ db.activeRuleDao().deleteByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
+ db.qProfileChangeDao().deleteByRulesProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
+ db.qualityProfileDao().deleteRulesProfilesByUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
+ }
+ dbSession.commit();
+ activeRuleIndexer.deleteByProfiles(customProfiles);
+ }
+}
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java
index a643716fc38..c6dc54582bb 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java
@@ -223,7 +223,7 @@ public class RuleActivator {
}
@CheckForNull
- private String firstNonNull(String... strings) {
+ private static String firstNonNull(String... strings) {
for (String s : strings) {
if (s != null) {
return s;
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java
index 48b4a941a93..4c18c12695e 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java
@@ -111,7 +111,7 @@ public class ActivateRuleAction implements QProfileWsAction {
response.noContent();
}
- private RuleActivation readActivation(Request request) {
+ private static RuleActivation readActivation(Request request) {
RuleKey ruleKey = RuleKey.parse(request.mandatoryParam(PARAM_RULE_KEY));
boolean reset = Boolean.TRUE.equals(request.paramAsBoolean(PARAM_RESET));
if (reset) {
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchAction.java
index eac4d097bc6..f7f78adbd7a 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchAction.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchAction.java
@@ -157,7 +157,8 @@ public class SearchAction implements QProfileWsAction {
}
List<QProfileDto> profiles = dataLoader.findProfiles(dbSession, request, organization, project);
- Set<String> defaultProfiles = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, organization.getUuid(), profiles.stream().map(QProfileDto::getKee).collect(MoreCollectors.toList()));
+ List<String> profileUuids = profiles.stream().map(QProfileDto::getKee).collect(MoreCollectors.toList());
+ Set<String> defaultProfiles = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, organization.getUuid(), profileUuids);
return new SearchData()
.setOrganization(organization)
diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java b/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java
index 41932387d03..8638e255fa8 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java
@@ -57,6 +57,7 @@ import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsUtils;
import org.sonar.server.es.SearchIdResult;
@@ -291,11 +292,12 @@ public class RuleIndex {
}
/* Implementation of activation query */
- if (query.getActivation() != null && query.getQProfile() != null) {
+ QProfileDto profile = query.getQProfile();
+ if (query.getActivation() != null && profile != null) {
// ActiveRule Filter (profile and inheritance)
BoolQueryBuilder childrenFilter = boolQuery();
- addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, query.getQProfile().getRulesProfileUuid());
+ addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid());
addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance());
addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_SEVERITY, query.getActiveSeverities());
@@ -419,7 +421,8 @@ public class RuleIndex {
private static void addActiveSeverityFacetIfNeeded(RuleQuery query, SearchOptions options, Map<String, AbstractAggregationBuilder> aggregations,
StickyFacetBuilder stickyFacetBuilder) {
- if (options.getFacets().contains(FACET_ACTIVE_SEVERITIES) && query.getQProfile() != null) {
+ QProfileDto profile = query.getQProfile();
+ if (options.getFacets().contains(FACET_ACTIVE_SEVERITIES) && profile != null) {
// We are building a children aggregation on active rules
// so the rule filter has to be used as parent filter for active rules
// from which we remove filters that concern active rules ("activation")
@@ -429,7 +432,7 @@ public class RuleIndex {
// Rebuilding the active rule filter without severities
BoolQueryBuilder childrenFilter = boolQuery();
- addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, query.getQProfile().getRulesProfileUuid());
+ addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid());
RuleIndex.addTermFilter(childrenFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance());
QueryBuilder activeRuleFilter = childrenFilter.must(ruleFilter);
diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.java b/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.java
index 2837318a565..1b1849dc26c 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.java
@@ -104,11 +104,7 @@ public class ActiveRuleCompleter {
Multimap<RuleKey, OrgActiveRuleDto> activeRulesByRuleKey = activeRules.stream()
.collect(MoreCollectors.index(OrgActiveRuleDto::getRuleKey));
ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = loadParams(dbSession, activeRules);
- rules.forEach(rule -> {
- });
- for (RuleDto rule : rules) {
- profileUuids.addAll(writeActiveRules(rule.getKey(), activeRulesByRuleKey.get(rule.getKey()), activeRuleParamsByActiveRuleKey, activesBuilder));
- }
+ rules.forEach(rule -> profileUuids.addAll(writeActiveRules(rule.getKey(), activeRulesByRuleKey.get(rule.getKey()), activeRuleParamsByActiveRuleKey, activesBuilder)));
}
response.setActives(activesBuilder);
diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java
index 71a2d98b14b..cf543edbb1b 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java
@@ -49,6 +49,7 @@ import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.organization.TestOrganizationFlags;
import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.index.UserIndex;
@@ -81,7 +82,7 @@ public class DeleteActionTest {
private ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
private TestOrganizationFlags organizationFlags = TestOrganizationFlags.standalone().setEnabled(true);
private TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
- private QProfileFactory qProfileFactory = new QProfileFactory(dbClient, mock(UuidFactory.class), System2.INSTANCE, mock(ActiveRuleIndexer.class));
+ private QProfileFactory qProfileFactory = new QProfileFactoryImpl(dbClient, mock(UuidFactory.class), System2.INSTANCE, mock(ActiveRuleIndexer.class));
private UserIndex userIndex = new UserIndex(es.client());
private UserIndexer userIndexer = new UserIndexer(dbClient, es.client());
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java
new file mode 100644
index 00000000000..d56d9ad0f01
--- /dev/null
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java
@@ -0,0 +1,273 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.qualityprofile;
+
+import com.google.common.io.Resources;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import javax.xml.stream.XMLStreamException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.utils.System2;
+import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.ActiveRuleDto;
+import org.sonar.db.qualityprofile.ActiveRuleParamDto;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.qualityprofile.QualityProfileTesting;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleParamDto;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+
+public class QProfileBackuperImplTest {
+
+ private static final String EMPTY_BACKUP = "<?xml version='1.0' encoding='UTF-8'?>" +
+ "<profile><name>foo</name>" +
+ "<language>js</language>" +
+ "<rules/>" +
+ "</profile>";
+
+ private System2 system2 = new AlwaysIncreasingSystem2();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+ @Rule
+ public DbTester db = DbTester.create(system2);
+
+ private DummyReset reset = new DummyReset();
+ private QProfileFactory profileFactory = new DummyProfileFactory();
+ private QProfileBackuper underTest = new QProfileBackuperImpl(db.getDbClient(), reset, profileFactory);
+
+ @Test
+ public void backup_generates_xml_file() {
+ RuleDefinitionDto rule = createRule();
+ QProfileDto profile = createProfile(rule);
+ ActiveRuleDto activeRule = activate(profile, rule);
+
+ StringWriter writer = new StringWriter();
+ underTest.backup(db.getSession(), profile, writer);
+
+ assertThat(writer.toString()).isEqualTo("<?xml version='1.0' encoding='UTF-8'?>" +
+ "<profile><name>" + profile.getName() + "</name>" +
+ "<language>" + profile.getLanguage() + "</language>" +
+ "<rules>" +
+ "<rule>" +
+ "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" +
+ "<key>" + rule.getRuleKey() + "</key>" +
+ "<priority>" + activeRule.getSeverityString() + "</priority>" +
+ "<parameters/>" +
+ "</rule>" +
+ "</rules>" +
+ "</profile>");
+ }
+
+ @Test
+ public void backup_rules_having_parameters() {
+ RuleDefinitionDto rule = createRule();
+ RuleParamDto param = db.rules().insertRuleParam(rule);
+ QProfileDto profile = createProfile(rule);
+ ActiveRuleDto activeRule = activate(profile, rule, param);
+
+ StringWriter writer = new StringWriter();
+ underTest.backup(db.getSession(), profile, writer);
+
+ assertThat(writer.toString()).contains(
+ "<rule>" +
+ "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" +
+ "<key>" + rule.getRuleKey() + "</key>" +
+ "<priority>" + activeRule.getSeverityString() + "</priority>" +
+ "<parameters><parameter>" +
+ "<key>" + param.getName() + "</key>" +
+ "<value>20</value>" +
+ "</parameter></parameters>" +
+ "</rule>");
+ }
+
+ @Test
+ public void backup_empty_profile() {
+ RuleDefinitionDto rule = createRule();
+ QProfileDto profile = createProfile(rule);
+
+ StringWriter writer = new StringWriter();
+ underTest.backup(db.getSession(), profile, writer);
+
+ assertThat(writer.toString()).isEqualTo("<?xml version='1.0' encoding='UTF-8'?>" +
+ "<profile><name>" + profile.getName() + "</name>" +
+ "<language>" + profile.getLanguage() + "</language>" +
+ "<rules/>" +
+ "</profile>");
+ }
+
+ @Test
+ public void restore_backup_on_the_profile_specified_in_backup() {
+ OrganizationDto organization = db.organizations().insert();
+ Reader backup = new StringReader(EMPTY_BACKUP);
+
+ QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, organization, null);
+
+ assertThat(summary.getProfile().getName()).isEqualTo("foo");
+ assertThat(summary.getProfile().getLanguage()).isEqualTo("js");
+
+ assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee());
+ assertThat(reset.calledActivations).isEmpty();
+ }
+
+ @Test
+ public void restore_backup_on_profile_having_different_name() {
+ OrganizationDto organization = db.organizations().insert();
+ Reader backup = new StringReader(EMPTY_BACKUP);
+
+ QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, organization, "bar");
+
+ assertThat(summary.getProfile().getName()).isEqualTo("bar");
+ assertThat(summary.getProfile().getLanguage()).isEqualTo("js");
+
+ assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee());
+ assertThat(reset.calledActivations).isEmpty();
+ }
+
+ @Test
+ public void restore_resets_the_activated_rules() {
+ OrganizationDto organization = db.organizations().insert();
+ Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
+ "<profile><name>foo</name>" +
+ "<language>js</language>" +
+ "<rules>" +
+ "<rule>" +
+ "<repositoryKey>sonarjs</repositoryKey>" +
+ "<key>s001</key>" +
+ "<priority>BLOCKER</priority>" +
+ "<parameters>" +
+ "<parameter><key>bar</key><value>baz</value></parameter>" +
+ "</parameters>" +
+ "</rule>" +
+ "</rules>" +
+ "</profile>");
+
+ underTest.restore(db.getSession(), backup, organization, null);
+
+ assertThat(reset.calledActivations).hasSize(1);
+ RuleActivation activation = reset.calledActivations.get(0);
+ assertThat(activation.getSeverity()).isEqualTo("BLOCKER");
+ assertThat(activation.getRuleKey()).isEqualTo(RuleKey.of("sonarjs", "s001"));
+ assertThat(activation.getParameter("bar")).isEqualTo("baz");
+ }
+
+ @Test
+ public void fail_to_restore_if_not_xml_backup() throws Exception {
+ OrganizationDto organization = db.organizations().insert();
+ try {
+ underTest.restore(db.getSession(), new StringReader("foo"), organization, null);
+ fail();
+ } catch (IllegalStateException e) {
+ assertThat(e).hasMessage("Fail to restore Quality profile backup");
+ assertThat(e.getCause()).isInstanceOf(XMLStreamException.class);
+ assertThat(reset.calledProfile).isNull();
+ }
+ }
+
+ @Test
+ public void fail_to_restore_if_bad_xml_format() throws Exception {
+ OrganizationDto organization = db.organizations().insert();
+ try {
+ underTest.restore(db.getSession(), new StringReader("<rules><rule></rules>"), organization, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Backup XML is not valid. Root element must be <profile>.");
+ assertThat(reset.calledProfile).isNull();
+ }
+ }
+
+ @Test
+ public void fail_to_restore_if_duplicate_rule() throws Exception {
+ OrganizationDto organization = db.organizations().insert();
+ try {
+ String xml = Resources.toString(getClass().getResource("QProfileBackuperMediumTest/duplicates-xml-backup.xml"), UTF_8);
+ underTest.restore(db.getSession(), new StringReader(xml), organization, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("The quality profile cannot be restored as it contains duplicates for the following rules: xoo:x1, xoo:x2");
+ assertThat(reset.calledProfile).isNull();
+ }
+ }
+
+ private RuleDefinitionDto createRule() {
+ return db.rules().insert();
+ }
+
+ private QProfileDto createProfile(RuleDefinitionDto rule) {
+ return db.qualityProfiles().insert(db.getDefaultOrganization(), p -> p.setLanguage(rule.getLanguage()));
+ }
+
+ private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule) {
+ return db.qualityProfiles().activateRule(profile, rule);
+ }
+
+ private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule, RuleParamDto param) {
+ ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile, rule);
+ ActiveRuleParamDto dto = ActiveRuleParamDto.createFor(param)
+ .setValue("20")
+ .setActiveRuleId(activeRule.getId());
+ db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule, dto);
+ return activeRule;
+ }
+
+ private static class DummyReset implements QProfileReset {
+ private QProfileDto calledProfile;
+ private List<RuleActivation> calledActivations;
+
+ @Override
+ public BulkChangeResult reset(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations) {
+ this.calledProfile = profile;
+ this.calledActivations = new ArrayList<>(activations);
+ return new BulkChangeResult();
+ }
+ }
+ private static class DummyProfileFactory implements QProfileFactory {
+ @Override
+ public QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName key) {
+ return QualityProfileTesting.newQualityProfileDto()
+ .setOrganizationUuid(organization.getUuid())
+ .setLanguage(key.getLanguage())
+ .setName(key.getName());
+ }
+
+ @Override
+ public QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperMediumTest.java
deleted file mode 100644
index dfac17445f8..00000000000
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperMediumTest.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.qualityprofile;
-
-import com.google.common.io.Resources;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.nio.charset.StandardCharsets;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.List;
-import javax.xml.stream.XMLStreamException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rule.Severity;
-import org.sonar.api.server.rule.RuleParamType;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.organization.OrganizationDto;
-import org.sonar.db.organization.OrganizationTesting;
-import org.sonar.db.qualityprofile.ActiveRuleDao;
-import org.sonar.db.qualityprofile.ActiveRuleDto;
-import org.sonar.db.qualityprofile.ActiveRuleParamDto;
-import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
-import org.sonar.db.rule.RuleDto;
-import org.sonar.db.rule.RuleParamDto;
-import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
-import org.sonar.server.rule.index.RuleIndex;
-import org.sonar.server.rule.index.RuleIndexer;
-import org.sonar.server.rule.index.RuleQuery;
-import org.sonar.server.tester.ServerTester;
-import org.sonar.server.tester.UserSessionRule;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
-import static org.sonar.db.qualityprofile.ActiveRuleDto.INHERITED;
-import static org.sonar.db.qualityprofile.ActiveRuleDto.OVERRIDES;
-import static org.sonar.db.rule.RuleTesting.XOO_X1;
-import static org.sonar.db.rule.RuleTesting.XOO_X2;
-import static org.sonar.db.rule.RuleTesting.newRule;
-import static org.sonar.db.rule.RuleTesting.newXooX1;
-import static org.sonar.db.rule.RuleTesting.newXooX2;
-import static org.sonar.server.qualityprofile.QProfileTesting.XOO_P1_KEY;
-import static org.sonar.server.qualityprofile.QProfileTesting.XOO_P1_NAME;
-import static org.sonar.server.qualityprofile.QProfileTesting.XOO_P2_KEY;
-import static org.sonar.server.qualityprofile.QProfileTesting.XOO_P2_NAME;
-import static org.sonar.server.qualityprofile.QProfileTesting.XOO_P3_NAME;
-import static org.sonar.server.qualityprofile.QProfileTesting.newXooP1;
-import static org.sonar.server.qualityprofile.QProfileTesting.newXooP2;
-
-public class QProfileBackuperMediumTest {
-
-// @ClassRule
-// public static ServerTester tester = new ServerTester().withEsIndexes();
-// @Rule
-// public ExpectedException thrown = ExpectedException.none();
-// @Rule
-// public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester);
-//
-// private DbClient db;
-// private DbSession dbSession;
-// private RuleIndexer ruleIndexer;
-// private ActiveRuleIndexer activeRuleIndexer;
-// private OrganizationDto organization;
-//
-// @Before
-// public void before() {
-// tester.clearDbAndIndexes();
-// db = tester.get(DbClient.class);
-// dbSession = db.openSession(false);
-// ruleIndexer = tester.get(RuleIndexer.class);
-// activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
-//
-// // create pre-defined rules
-// RuleDto xooRule1 = newXooX1().setSeverity("MINOR").setLanguage("xoo");
-// db.ruleDao().insert(dbSession, xooRule1.getDefinition());
-// db.ruleDao().insertRuleParam(dbSession, xooRule1.getDefinition(), RuleParamDto.createFor(xooRule1.getDefinition())
-// .setName("max").setDefaultValue("10").setType(RuleParamType.INTEGER.type()));
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinition(xooRule1.getDefinition().getKey());
-//
-// RuleDto xooRule2 = newXooX2().setSeverity("MAJOR").setLanguage("xoo");
-// db.ruleDao().insert(dbSession, xooRule2.getDefinition());
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinition(xooRule2.getDefinition().getKey());
-//
-// this.organization = OrganizationTesting.newOrganizationDto();
-// db.organizationDao().insert(dbSession, organization, false);
-// }
-//
-// @After
-// public void after() {
-// dbSession.close();
-// }
-//
-// @Test
-// public void backup() throws Exception {
-// RuleKey blahRuleKey = RuleKey.of("blah", "my-rule");
-// RuleDefinitionDto blahRule = newRule(blahRuleKey).setSeverity("INFO").setLanguage("xoo");
-// db.ruleDao().insert(dbSession, blahRule);
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinition(blahRule.getKey());
-//
-// // create profile P1 with rules x2 and x1 activated
-// QProfileDto profile = newXooP1(organization);
-// db.qualityProfileDao().insert(dbSession, profile);
-// RuleActivation activation1 = new RuleActivation(XOO_X2).setSeverity("MINOR");
-// RuleActivation activation2 = new RuleActivation(XOO_X1);
-// RuleActivation activation3 = new RuleActivation(blahRuleKey);
-// activation2.setSeverity(Severity.BLOCKER);
-// activation2.setParameter("max", "7");
-// QProfileDto profileDto = get(XOO_P1_NAME);
-// tester.get(RuleActivator.class).activate(dbSession, activation1, profileDto);
-// tester.get(RuleActivator.class).activate(dbSession, activation2, profileDto);
-// tester.get(RuleActivator.class).activate(dbSession, activation3, profileDto);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// StringWriter output = new StringWriter();
-// tester.get(QProfileBackuper.class).backup(dbSession, profile, output);
-//
-// String expectedXml = Resources.toString(getClass().getResource("QProfileBackuperMediumTest/expected-backup.xml"), StandardCharsets.UTF_8);
-// assertThat(output.toString()).isXmlEqualTo(expectedXml);
-// }
-//
-// @Test
-// public void restore_and_create_profile() throws Exception {
-// // Backup file declares profile P1 on xoo
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/restore.xml"), StandardCharsets.UTF_8)),
-// organization, null);
-//
-// // Check in db
-// QProfileDto profile = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "P1", "xoo");
-// assertThat(profile).isNotNull();
-//
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee());
-// assertThat(activeRules).hasSize(1);
-// ActiveRuleDto activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("BLOCKER");
-// assertThat(activeRuleDoc.getInheritance()).isNull();
-//
-// ActiveRuleDto activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// List<ActiveRuleParamDto> params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("7");
-//
-// // Check in es
-// assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery().setQProfileKey(profile.getKee()).setActivation(true))).containsOnly(XOO_X1);
-// }
-//
-// @Test
-// public void restore_and_update_profile() throws Exception {
-// // create profile P1 with rules x1 and x2 activated
-// db.qualityProfileDao().insert(dbSession, newXooP1(organization));
-// RuleActivation activation = new RuleActivation(XOO_X1);
-// activation.setSeverity(Severity.INFO);
-// activation.setParameter("max", "10");
-// QProfileDto profileDto = get(XOO_P1_NAME);
-// tester.get(RuleActivator.class).activate(dbSession, activation, profileDto);
-//
-// activation = new RuleActivation(XOO_X2);
-// activation.setSeverity(Severity.INFO);
-// tester.get(RuleActivator.class).activate(dbSession, activation, profileDto);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // restore backup, which activates only x1
-// // -> update x1 and deactivate x2
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/restore.xml"), StandardCharsets.UTF_8)), organization, null);
-//
-// // Check in db
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P1_KEY);
-// assertThat(activeRules).hasSize(1);
-// ActiveRuleDto activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("BLOCKER");
-// assertThat(activeRuleDoc.getInheritance()).isNull();
-//
-// ActiveRuleDto activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// List<ActiveRuleParamDto> params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("7");
-//
-// // Check in es
-// assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery().setQProfileKey(XOO_P1_KEY).setActivation(true))).containsOnly(XOO_X1);
-// }
-//
-// @Test
-// public void restore_child_profile() throws Exception {
-// // define two parent/child profiles
-// db.qualityProfileDao().insert(dbSession,
-// newXooP1(organization),
-// newXooP2(organization).setParentKee(XOO_P1_KEY));
-// dbSession.commit();
-//
-// // rule x1 is activated on parent profile (so inherited by child profile)
-// RuleActivation activation = new RuleActivation(XOO_X1);
-// activation.setSeverity(Severity.INFO);
-// activation.setParameter("max", "10");
-// tester.get(RuleActivator.class).activate(dbSession, activation, XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // restore backup of child profile -> overrides x1
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/restore-child.xml"), StandardCharsets.UTF_8)), organization, null);
-//
-// // parent profile is unchanged
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P1_KEY);
-// assertThat(activeRules).hasSize(1);
-// ActiveRuleDto activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("INFO");
-// assertThat(activeRuleDoc.getInheritance()).isNull();
-//
-// ActiveRuleDto activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// List<ActiveRuleParamDto> params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("10");
-//
-// // child profile overrides parent
-// activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P2_KEY);
-// assertThat(activeRules).hasSize(1);
-// activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("BLOCKER");
-// assertThat(activeRuleDoc.getInheritance()).isEqualTo(OVERRIDES);
-//
-// activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("7");
-// }
-//
-// @Test
-// public void restore_parent_profile() throws Exception {
-// // define two parent/child profiles
-// db.qualityProfileDao().insert(dbSession,
-// newXooP1(organization),
-// newXooP2(organization).setParentKee(XOO_P1_KEY));
-// dbSession.commit();
-//
-// // rule x1 is activated on parent profile (so inherited by child profile)
-// RuleActivation activation = new RuleActivation(XOO_X1);
-// activation.setSeverity(Severity.INFO);
-// activation.setParameter("max", "10");
-// tester.get(RuleActivator.class).activate(dbSession, activation, XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // restore backup of parent profile -> update x1 and propagates to child
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/restore-parent.xml"), StandardCharsets.UTF_8)), organization, null);
-//
-// // parent profile is updated
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P1_KEY);
-// assertThat(activeRules).hasSize(1);
-//
-// ActiveRuleDto activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("BLOCKER");
-// assertThat(activeRuleDoc.getInheritance()).isNull();
-//
-// ActiveRuleDto activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// List<ActiveRuleParamDto> params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("7");
-//
-// // child profile is inherited
-// activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P2_KEY);
-// assertThat(activeRules).hasSize(1);
-// activeRuleDoc = activeRules.get(0);
-// assertThat(activeRuleDoc.getSeverityString()).isEqualTo("BLOCKER");
-// assertThat(activeRuleDoc.getInheritance()).isEqualTo(INHERITED);
-//
-// activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRuleDoc.getKey());
-// params = tester.get(ActiveRuleDao.class).selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(1);
-// assertThat(params.get(0).getKey()).isEqualTo("max");
-// assertThat(params.get(0).getValue()).isEqualTo("7");
-// }
-//
-// @Test
-// public void keep_other_inherited_rules() throws Exception {
-// // define two parent/child profiles
-// db.qualityProfileDao().insert(dbSession,
-// newXooP1(organization),
-// newXooP2(organization).setParentKee(XOO_P1_KEY));
-// dbSession.commit();
-//
-// // rule x1 is activated on parent profile and is inherited by child profile
-// RuleActivation activation = new RuleActivation(XOO_X1);
-// activation.setSeverity(Severity.INFO);
-// activation.setParameter("max", "10");
-// tester.get(RuleActivator.class).activate(dbSession, activation, XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // backup of child profile contains x2 but not x1
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/keep_other_inherited_rules.xml"), StandardCharsets.UTF_8)), organization, XOO_P2_NAME.getName());
-//
-// // x1 and x2
-// assertThat(db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P2_KEY)).hasSize(2);
-// }
-//
-// @Test
-// public void fail_to_restore_if_not_xml_backup() throws Exception {
-// try {
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/not-xml-backup.txt"), StandardCharsets.UTF_8)), organization, null);
-// fail();
-// } catch (IllegalStateException e) {
-// assertThat(e).hasMessage("Fail to restore Quality profile backup");
-// assertThat(e.getCause()).isInstanceOf(XMLStreamException.class);
-// }
-// }
-//
-// @Test
-// public void fail_to_restore_if_bad_xml_format() throws Exception {
-// try {
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/bad-xml-backup.xml"), StandardCharsets.UTF_8)), organization, null);
-// fail();
-// } catch (IllegalArgumentException e) {
-// assertThat(e).hasMessage("Backup XML is not valid. Root element must be <profile>.");
-// }
-// }
-//
-// @Test
-// public void fail_to_restore_if_duplicate_rule() throws Exception {
-// try {
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/duplicates-xml-backup.xml"), StandardCharsets.UTF_8)), organization, null);
-// fail();
-// } catch (IllegalArgumentException e) {
-// assertThat(e).hasMessage("The quality profile cannot be restored as it contains duplicates for the following rules: xoo:x1, xoo:x2");
-// }
-// }
-//
-// @Test
-// public void restore_and_override_profile_name() throws Exception {
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/restore.xml"), StandardCharsets.UTF_8)),
-// organization, XOO_P3_NAME.getName());
-//
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, XOO_P1_KEY);
-// assertThat(activeRules).hasSize(0);
-//
-// QProfileDto target = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "P3", "xoo");
-// assertThat(target).isNotNull();
-// assertThat(db.activeRuleDao().selectByProfileUuid(dbSession, target.getKee())).hasSize(1);
-// }
-//
-// @Test
-// public void restore_profile_with_zero_rules() throws Exception {
-// tester.get(QProfileBackuper.class).restore(dbSession, new StringReader(
-// Resources.toString(getClass().getResource("QProfileBackuperMediumTest/empty.xml"), StandardCharsets.UTF_8)),
-// organization, null);
-//
-// dbSession.clearCache();
-// assertThat(anyActiveRuleExists()).isFalse();
-// List<QProfileDto> profiles = db.qualityProfileDao().selectOrderedByOrganizationUuid(dbSession, organization);
-// assertThat(profiles).hasSize(1);
-// assertThat(profiles.get(0).getName()).isEqualTo("P1");
-// }
-//
-// private boolean anyActiveRuleExists() throws SQLException {
-// try (PreparedStatement preparedStatement = db.openSession(false).getConnection().prepareStatement("SELECT * FROM active_rules");
-// ResultSet resultSet = preparedStatement.executeQuery();) {
-// return resultSet.next();
-// }
-// }
-//
-// private QProfileDto get(QProfileName profileName) {
-// return db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, profileName.getName(), profileName.getLanguage());
-// }
-}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierMediumTest.java
deleted file mode 100644
index 37f0ee1f038..00000000000
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierMediumTest.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.server.qualityprofile;
-
-public class QProfileCopierMediumTest {
-
-// @ClassRule
-// public static ServerTester tester = new ServerTester().withEsIndexes();
-// @Rule
-// public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester);
-//
-// private DbClient db;
-// private DbSession dbSession;
-// private RuleActivator ruleActivator;
-// private QProfileCopier copier;
-// private RuleIndexer ruleIndexer;
-// private ActiveRuleIndexer activeRuleIndexer;
-// private OrganizationDto organization;
-// private QProfileDto sourceProfile;
-//
-// @Before
-// public void before() {
-// tester.clearDbAndIndexes();
-// db = tester.get(DbClient.class);
-// dbSession = db.openSession(false);
-// ruleActivator = tester.get(RuleActivator.class);
-// copier = tester.get(QProfileCopier.class);
-// ruleIndexer = tester.get(RuleIndexer.class);
-// activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
-// organization = getDefaultOrganization(tester, db, dbSession);
-//
-// // create pre-defined rules
-// RuleDto xooRule1 = RuleTesting.newXooX1().setSeverity("MINOR");
-// RuleDefinitionDto xooRule1Definition = xooRule1.getDefinition();
-// db.ruleDao().insert(dbSession, xooRule1Definition);
-// db.ruleDao().insertRuleParam(dbSession, xooRule1Definition, RuleParamDto.createFor(xooRule1Definition)
-// .setName("max").setDefaultValue("10").setType(RuleParamType.INTEGER.type()));
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinition(xooRule1Definition.getKey());
-//
-// RuleDto xooRule2 = RuleTesting.newXooX2().setSeverity("MAJOR");
-// RuleDefinitionDto xooRule2Definition = xooRule2.getDefinition();
-// db.ruleDao().insert(dbSession, xooRule2Definition);
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinition(xooRule2Definition.getKey());
-//
-// // create pre-defined profile
-// sourceProfile = QProfileTesting.newXooP1(organization);
-// db.qualityProfileDao().insert(dbSession, sourceProfile);
-// dbSession.commit();
-// }
-//
-// @After
-// public void after() {
-// dbSession.close();
-// }
-//
-// @Test
-// public void create_target_profile() {
-// // source
-// RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
-// activation.setSeverity(Severity.BLOCKER);
-// activation.setParameter("max", "7");
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // target does not exist
-// copier.copyToName(dbSession, sourceProfile, QProfileTesting.XOO_P2_NAME.getName());
-//
-// verifyOneActiveRule(QProfileTesting.XOO_P2_NAME, Severity.BLOCKER, null, ImmutableMap.of("max", "7"));
-// }
-//
-// @Test
-// public void update_target_profile() {
-// // source with x1 activated
-// RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
-// activation.setSeverity(Severity.BLOCKER);
-// activation.setParameter("max", "7");
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // create target with both x1 and x2 activated
-// db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2(organization));
-// activation = new RuleActivation(RuleTesting.XOO_X1);
-// activation.setSeverity(Severity.CRITICAL);
-// activation.setParameter("max", "20");
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P2_KEY);
-// activation = new RuleActivation(RuleTesting.XOO_X2);
-// activation.setSeverity(Severity.CRITICAL);
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P2_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // copy -> reset x1 and deactivate x2
-// copier.copyToName(dbSession, sourceProfile, QProfileTesting.XOO_P2_NAME.getName());
-//
-// verifyOneActiveRule(QProfileTesting.XOO_P2_KEY, Severity.BLOCKER, null, ImmutableMap.of("max", "7"));
-// }
-//
-// @Test
-// public void create_target_profile_with_same_parent_than_source() {
-// // two profiles : parent and its child
-// db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2(organization).setParentKee(QProfileTesting.XOO_P1_KEY));
-//
-// // parent and child with x1 activated
-// RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
-// activation.setSeverity(Severity.BLOCKER);
-// activation.setParameter("max", "7");
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// // copy child -> profile2 is created with parent P1
-// copier.copyToName(dbSession, sourceProfile, QProfileTesting.XOO_P2_NAME.getName());
-//
-// verifyOneActiveRule(QProfileTesting.XOO_P2_KEY, Severity.BLOCKER, ActiveRuleDto.INHERITED, ImmutableMap.of("max", "7"));
-// QProfileDto profile2Dto = db.qualityProfileDao().selectByUuid(dbSession, QProfileTesting.XOO_P2_KEY);
-// assertThat(profile2Dto.getParentKee()).isEqualTo(QProfileTesting.XOO_P1_KEY);
-// }
-//
-// @Test
-// public void fail_to_copy_on_self() {
-// RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
-// activation.setSeverity(Severity.BLOCKER);
-// activation.setParameter("max", "7");
-// ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index();
-//
-// try {
-// copier.copyToName(dbSession, sourceProfile, QProfileTesting.XOO_P1_NAME.getName());
-// fail();
-// } catch (IllegalArgumentException e) {
-// assertThat(e).hasMessage("Source and target profiles are equal: P1");
-// }
-// }
-//
-// private void verifyOneActiveRule(QProfileName profileName, String expectedSeverity,
-// @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-// QProfileDto dto = db.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, profileName.getName(), profileName.getLanguage());
-// verifyOneActiveRule(dto.getKee(), expectedSeverity, expectedInheritance, expectedParams);
-// }
-//
-// private void verifyOneActiveRule(String profileKey, String expectedSeverity, @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-//
-// // check in db
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, profileKey);
-// assertThat(activeRules).hasSize(1);
-//
-// ActiveRuleDto activeRule = activeRules.get(0);
-// assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity);
-// assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance);
-//
-// // verify parameters
-// ActiveRuleDto activeRuleDto = db.activeRuleDao().selectOrFailByKey(dbSession, activeRule.getKey());
-// List<ActiveRuleParamDto> params = db.activeRuleDao().selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(params).hasSize(expectedParams.size());
-// Map<String, ActiveRuleParamDto> paramsByKey = ActiveRuleParamDto.groupByKey(params);
-// for (Map.Entry<String, String> entry : expectedParams.entrySet()) {
-// String value = paramsByKey.get(entry.getKey()).getValue();
-// assertThat(value).isEqualTo(entry.getValue());
-// }
-//
-// // check in es
-// assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery().setQProfileKey(profileKey).setActivation(true))).hasSize(1);
-// }
-}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java
new file mode 100644
index 00000000000..bbcaa77a28a
--- /dev/null
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java
@@ -0,0 +1,172 @@
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.qualityprofile;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.Collection;
+import javax.annotation.Nullable;
+import org.apache.commons.io.IOUtils;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.sonar.api.utils.System2;
+import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
+import org.sonar.api.utils.internal.JUnitTempFolder;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.qualityprofile.QualityProfileTesting;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+
+public class QProfileCopierTest {
+
+ private static final String BACKUP = "<backup/>";
+ private System2 system2 = new AlwaysIncreasingSystem2();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+ @Rule
+ public DbTester db = DbTester.create(system2);
+ @Rule
+ public JUnitTempFolder temp = new JUnitTempFolder();
+
+ private DummyProfileFactory profileFactory = new DummyProfileFactory();
+ private DummyBackuper backuper = new DummyBackuper();
+ private QProfileCopier underTest = new QProfileCopier(db.getDbClient(), profileFactory, backuper, temp);
+
+ @Test
+ public void create_target_profile_and_copy_rules() {
+ OrganizationDto organization = db.organizations().insert();
+ QProfileDto source = db.qualityProfiles().insert(organization);
+
+ QProfileDto target = underTest.copyToName(db.getSession(), source, "foo");
+
+ assertThat(target.getLanguage()).isEqualTo(source.getLanguage());
+ assertThat(target.getName()).isEqualTo("foo");
+ assertThat(target.getParentKee()).isNull();
+ assertThat(backuper.backuped).isSameAs(source);
+ assertThat(backuper.restored.getName()).isEqualTo("foo");
+ assertThat(backuper.restoredBackup).isEqualTo(BACKUP);
+ }
+
+ @Test
+ public void create_target_profile_with_same_parent_than_source_profile() {
+ OrganizationDto organization = db.organizations().insert();
+ QProfileDto parent = db.qualityProfiles().insert(organization);
+ QProfileDto source = db.qualityProfiles().insert(organization, p -> p.setParentKee(parent.getKee()));
+
+ QProfileDto target = underTest.copyToName(db.getSession(), source, "foo");
+
+ assertThat(target.getLanguage()).isEqualTo(source.getLanguage());
+ assertThat(target.getName()).isEqualTo("foo");
+ assertThat(target.getParentKee()).isEqualTo(parent.getKee());
+ }
+
+ @Test
+ public void fail_to_copy_on_self() {
+ OrganizationDto organization = db.organizations().insert();
+ QProfileDto source = db.qualityProfiles().insert(organization);
+
+ try {
+ underTest.copyToName(db.getSession(), source, source.getName());
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Source and target profiles are equal: " + source.getName());
+ assertThat(backuper.backuped).isNull();
+ assertThat(backuper.restored).isNull();
+ }
+ }
+
+ @Test
+ public void copy_to_existing_profile() {
+ OrganizationDto organization = db.organizations().insert();
+ QProfileDto profile1 = db.qualityProfiles().insert(organization);
+ QProfileDto profile2 = db.qualityProfiles().insert(organization, p -> p.setLanguage(profile1.getLanguage()));
+
+ QProfileDto target = underTest.copyToName(db.getSession(), profile1, profile2.getName());
+
+ assertThat(profileFactory.createdProfile).isNull();
+ assertThat(target.getLanguage()).isEqualTo(profile2.getLanguage());
+ assertThat(target.getName()).isEqualTo(profile2.getName());
+ assertThat(backuper.backuped).isSameAs(profile1);
+ assertThat(backuper.restored.getName()).isEqualTo(profile2.getName());
+ assertThat(backuper.restoredBackup).isEqualTo(BACKUP);
+ }
+
+ private static class DummyProfileFactory implements QProfileFactory {
+ private QProfileDto createdProfile;
+
+ @Override
+ public QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName key) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName key) {
+ createdProfile = QualityProfileTesting.newQualityProfileDto()
+ .setOrganizationUuid(organization.getUuid())
+ .setLanguage(key.getLanguage())
+ .setName(key.getName());
+ return createdProfile;
+ }
+
+ @Override
+ public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private static class DummyBackuper implements QProfileBackuper {
+ private QProfileDto backuped;
+ private String restoredBackup;
+ private QProfileDto restored;
+
+ @Override
+ public void backup(DbSession dbSession, QProfileDto profile, Writer backupWriter) {
+ this.backuped = profile;
+ try {
+ backupWriter.write(BACKUP);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ @Override
+ public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, OrganizationDto organization, @Nullable String overriddenProfileName) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
+ try {
+ this.restoredBackup = IOUtils.toString(backup);
+ this.restored = profile;
+ return null;
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java
index ba771a0f4c4..97388984434 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java
@@ -19,215 +19,261 @@
*/
package org.sonar.server.qualityprofile;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.sonar.api.profiles.ProfileExporter;
+import org.sonar.api.profiles.ProfileImporter;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleFinder;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.api.utils.System2;
+import org.sonar.api.utils.ValidationMessages;
+import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleParamDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
+import org.sonar.server.rule.DefaultRuleFinder;
+import org.sonar.server.tester.UserSessionRule;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.apache.commons.io.IOUtils.toInputStream;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
public class QProfileExportersTest {
-// @ClassRule
-// public static ServerTester tester = new ServerTester()
-// .withEsIndexes()
-// .withStartupTasks()
-// .addXoo()
-// .addComponents(XooRulesDefinition.class, XooProfileDefinition.class, XooExporter.class, StandardExporter.class,
-// XooProfileImporter.class, XooProfileImporterWithMessages.class, XooProfileImporterWithError.class);
-//
-// @org.junit.Rule
-// public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester);
-//
-// private DbClient db;
-// private DbSession dbSession;
-// private QProfileExporters underTest;
-// private ActiveRuleIndexer activeRuleIndexer;
-//
-// @Before
-// public void before() {
-// db = tester.get(DbClient.class);
-// dbSession = db.openSession(false);
-// underTest = tester.get(QProfileExporters.class);
-// activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
-// }
-//
-// @After
-// public void after() {
-// dbSession.close();
-// }
-//
-// @Test
-// public void exportersForLanguage() {
-// assertThat(underTest.exportersForLanguage("xoo")).hasSize(2);
-// assertThat(underTest.exportersForLanguage("java")).hasSize(1);
-// assertThat(underTest.exportersForLanguage("java").get(0)).isInstanceOf(StandardExporter.class);
-// }
-//
-// @Test
-// public void mimeType() {
-// assertThat(underTest.mimeType("xootool")).isEqualTo("plain/custom");
-//
-// // default mime type
-// assertThat(underTest.mimeType("standard")).isEqualTo("text/plain");
-// }
-//
-// @Test
-// public void import_xml() {
-// QProfileDto profile = QProfileTesting.newQProfileDto("org-123", QProfileName.createFor("xoo", "import_xml"), "import_xml");
-// db.qualityProfileDao().insert(dbSession, profile);
-// dbSession.commit();
-//
-// assertThat(db.activeRuleDao().selectByProfile(dbSession, profile)).isEmpty();
-//
-// QProfileResult result = underTest.importXml(profile, "XooProfileImporter", toInputStream("<xml/>", UTF_8), dbSession);
-// dbSession.commit();
-// activeRuleIndexer.index(result.getChanges());
-//
-// // Check in db
-// List<ActiveRuleDto> activeRules = db.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee());
-// assertThat(activeRules).hasSize(1);
-// ActiveRuleDto activeRule = activeRules.get(0);
-// assertThat(activeRule.getKey().getRuleKey()).isEqualTo(RuleKey.of("xoo", "R1"));
-// assertThat(activeRule.getSeverityString()).isEqualTo(Severity.CRITICAL);
-//
-// // Check in es
-// assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery().setQProfile(profile).setActivation(true))).containsOnly(RuleKey.of("xoo", "R1"));
-// }
-//
-// @Test
-// public void import_xml_return_messages() {
-// QProfileResult result = underTest.importXml(QProfileTesting.newXooP1("org-123"), "XooProfileImporterWithMessages", toInputStream("<xml/>", UTF_8), dbSession);
-// dbSession.commit();
-//
-// assertThat(result.infos()).containsOnly("an info");
-// assertThat(result.warnings()).containsOnly("a warning");
-// }
-//
-// @Test
-// public void fail_to_import_xml_when_error_in_importer() {
-// try {
-// underTest.importXml(QProfileTesting.newXooP1("org-123"), "XooProfileImporterWithError", toInputStream("<xml/>", UTF_8), dbSession);
-// fail();
-// } catch (Exception e) {
-// assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("error!");
-// }
-// }
-//
-// @Test
-// public void fail_to_import_xml_on_unknown_importer() {
-// try {
-// underTest.importXml(QProfileTesting.newXooP1("org-123"), "Unknown", toInputStream("<xml/>", UTF_8), dbSession);
-// fail();
-// } catch (Exception e) {
-// assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("No such importer : Unknown");
-// }
-// }
-//
-// public static class XooExporter extends ProfileExporter {
-// public XooExporter() {
-// super("xootool", "Xoo Tool");
-// }
-//
-// @Override
-// public String[] getSupportedLanguages() {
-// return new String[] {"xoo"};
-// }
-//
-// @Override
-// public String getMimeType() {
-// return "plain/custom";
-// }
-//
-// @Override
-// public void exportProfile(RulesProfile profile, Writer writer) {
-// try {
-// writer.write("xoo -> " + profile.getName() + " -> " + profile.getActiveRules().size());
-// } catch (IOException e) {
-// throw new IllegalStateException(e);
-// }
-// }
-// }
-//
-// public static class StandardExporter extends ProfileExporter {
-// public StandardExporter() {
-// super("standard", "Standard");
-// }
-//
-// @Override
-// public void exportProfile(RulesProfile profile, Writer writer) {
-// try {
-// writer.write("standard -> " + profile.getName() + " -> " + profile.getActiveRules().size());
-// } catch (IOException e) {
-// throw new IllegalStateException(e);
-// }
-// }
-// }
-//
-// public static class XooRulesDefinition implements RulesDefinition {
-// @Override
-// public void define(Context context) {
-// NewRepository repository = context.createRepository("xoo", "xoo").setName("Xoo Repo");
-// NewRule x1 = repository.createRule("R1")
-// .setName("R1 name")
-// .setHtmlDescription("R1 desc")
-// .setSeverity(Severity.MINOR);
-// x1.createParam("acceptWhitespace")
-// .setDefaultValue("false")
-// .setType(RuleParamType.BOOLEAN)
-// .setDescription("Accept whitespaces on the line");
-// repository.done();
-// }
-// }
-//
-// public static class XooProfileDefinition extends ProfileDefinition {
-// @Override
-// public RulesProfile createProfile(ValidationMessages validation) {
-// RulesProfile profile = RulesProfile.create("P1", "xoo");
-// profile.activateRule(new Rule("xoo", "R1"), RulePriority.BLOCKER).setParameter("acceptWhitespace", "true");
-// return profile;
-// }
-// }
-//
-// public static class XooProfileImporter extends ProfileImporter {
-// public XooProfileImporter() {
-// super("XooProfileImporter", "Xoo Profile Importer");
-// }
-//
-// @Override
-// public String[] getSupportedLanguages() {
-// return new String[] {"xoo"};
-// }
-//
-// @Override
-// public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
-// RulesProfile rulesProfile = RulesProfile.create();
-// rulesProfile.activateRule(Rule.create("xoo", "R1"), RulePriority.CRITICAL);
-// return rulesProfile;
-// }
-// }
-//
-// public static class XooProfileImporterWithMessages extends ProfileImporter {
-// public XooProfileImporterWithMessages() {
-// super("XooProfileImporterWithMessages", "Xoo Profile Importer With Message");
-// }
-//
-// @Override
-// public String[] getSupportedLanguages() {
-// return new String[] {};
-// }
-//
-// @Override
-// public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
-// messages.addWarningText("a warning");
-// messages.addInfoText("an info");
-// return RulesProfile.create();
-// }
-// }
-//
-// public static class XooProfileImporterWithError extends ProfileImporter {
-// public XooProfileImporterWithError() {
-// super("XooProfileImporterWithError", "Xoo Profile Importer With Error");
-// }
-//
-// @Override
-// public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
-// messages.addErrorText("error!");
-// return RulesProfile.create();
-// }
-// }
+ @org.junit.Rule
+ public UserSessionRule userSessionRule = UserSessionRule.standalone();
+
+ private System2 system2 = new AlwaysIncreasingSystem2();
+
+ @org.junit.Rule
+ public ExpectedException expectedException = ExpectedException.none();
+ @org.junit.Rule
+ public DbTester db = DbTester.create(system2);
+
+ public DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
+ private RuleFinder ruleFinder = new DefaultRuleFinder(db.getDbClient(), defaultOrganizationProvider);
+ private RuleActivator ruleActivator = mock(RuleActivator.class);
+ private ProfileExporter[] exporters = new ProfileExporter[] {
+ new StandardExporter(), new XooExporter()};
+ private ProfileImporter[] importers = new ProfileImporter[] {
+ new XooProfileImporter(), new XooProfileImporterWithMessages(), new XooProfileImporterWithError()};
+ private RuleDefinitionDto rule;
+ private RuleParamDto ruleParam;
+ private QProfileExporters underTest = new QProfileExporters(db.getDbClient(), ruleFinder, ruleActivator, exporters, importers);
+
+ @Before
+ public void setUp() {
+ rule = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("SonarXoo").setRuleKey("R1"));
+ ruleParam = db.rules().insertRuleParam(rule);
+ }
+
+ @Test
+ public void exportersForLanguage() {
+ assertThat(underTest.exportersForLanguage("xoo")).hasSize(2);
+ assertThat(underTest.exportersForLanguage("java")).hasSize(1);
+ assertThat(underTest.exportersForLanguage("java").get(0)).isInstanceOf(StandardExporter.class);
+ }
+
+ @Test
+ public void mimeType() {
+ assertThat(underTest.mimeType("xootool")).isEqualTo("plain/custom");
+
+ // default mime type
+ assertThat(underTest.mimeType("standard")).isEqualTo("text/plain");
+ }
+
+ @Test
+ public void import_xml() {
+ QProfileDto profile = createProfile();
+
+
+ underTest.importXml(profile, "XooProfileImporter", toInputStream("<xml/>", UTF_8), db.getSession());
+
+ ArgumentCaptor<QProfileDto> profileCapture = ArgumentCaptor.forClass(QProfileDto.class);
+ ArgumentCaptor<RuleActivation> activationCapture = ArgumentCaptor.forClass(RuleActivation.class);
+ verify(ruleActivator).activate(any(DbSession.class), activationCapture.capture(), profileCapture.capture());
+
+ assertThat(profileCapture.getValue().getKee()).isEqualTo(profile.getKee());
+ assertThat(activationCapture.getValue().getRuleKey()).isEqualTo(rule.getKey());
+ assertThat(activationCapture.getValue().getSeverity()).isEqualTo("CRITICAL");
+ }
+
+ @Test
+ public void import_xml_return_messages() {
+ QProfileDto profile = createProfile();
+
+ QProfileResult result = underTest.importXml(profile, "XooProfileImporterWithMessages", toInputStream("<xml/>", UTF_8), db.getSession());
+
+ assertThat(result.infos()).containsOnly("an info");
+ assertThat(result.warnings()).containsOnly("a warning");
+ }
+
+ @Test
+ public void fail_to_import_xml_when_error_in_importer() {
+ try {
+ underTest.importXml(QProfileTesting.newXooP1("org-123"), "XooProfileImporterWithError", toInputStream("<xml/>", UTF_8), db.getSession());
+ fail();
+ } catch (BadRequestException e) {
+ assertThat(e).hasMessage("error!");
+ }
+ }
+
+ @Test
+ public void fail_to_import_xml_on_unknown_importer() {
+ try {
+ underTest.importXml(QProfileTesting.newXooP1("org-123"), "Unknown", toInputStream("<xml/>", UTF_8), db.getSession());
+ fail();
+ } catch (BadRequestException e) {
+ assertThat(e).hasMessage("No such importer : Unknown");
+ }
+ }
+
+ @Test
+ public void export_empty_profile() {
+ QProfileDto profile = createProfile();
+
+ StringWriter writer = new StringWriter();
+ underTest.export(db.getSession(), profile, "standard", writer);
+ assertThat(writer.toString()).isEqualTo("standard -> " + profile.getName() + " -> 0");
+
+ writer = new StringWriter();
+ underTest.export(db.getSession(), profile, "xootool", writer);
+ assertThat(writer.toString()).isEqualTo("xoo -> " + profile.getName() + " -> 0");
+ }
+
+ @Test
+ public void export_profile() {
+ QProfileDto profile = createProfile();
+ db.qualityProfiles().activateRule(profile, rule);
+
+ StringWriter writer = new StringWriter();
+ underTest.export(db.getSession(), profile, "standard", writer);
+ assertThat(writer.toString()).isEqualTo("standard -> " + profile.getName() + " -> 1");
+
+ writer = new StringWriter();
+ underTest.export(db.getSession(), profile, "xootool", writer);
+ assertThat(writer.toString()).isEqualTo("xoo -> " + profile.getName() + " -> 1");
+ }
+
+ @Test
+ public void export_throws_NotFoundException_if_exporter_does_not_exist() {
+ QProfileDto profile = createProfile();
+
+ expectedException.expect(NotFoundException.class);
+ expectedException.expectMessage("Unknown quality profile exporter: does_not_exist");
+
+ underTest.export(db.getSession(), profile, "does_not_exist", new StringWriter());
+
+ }
+
+ private QProfileDto createProfile() {
+ return db.qualityProfiles().insert(db.getDefaultOrganization(), p -> p.setLanguage(rule.getLanguage()));
+ }
+
+ public static class XooExporter extends ProfileExporter {
+ public XooExporter() {
+ super("xootool", "Xoo Tool");
+ }
+
+ @Override
+ public String[] getSupportedLanguages() {
+ return new String[] {"xoo"};
+ }
+
+ @Override
+ public String getMimeType() {
+ return "plain/custom";
+ }
+
+ @Override
+ public void exportProfile(RulesProfile profile, Writer writer) {
+ try {
+ writer.write("xoo -> " + profile.getName() + " -> " + profile.getActiveRules().size());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+
+ public static class StandardExporter extends ProfileExporter {
+ public StandardExporter() {
+ super("standard", "Standard");
+ }
+
+ @Override
+ public void exportProfile(RulesProfile profile, Writer writer) {
+ try {
+ writer.write("standard -> " + profile.getName() + " -> " + profile.getActiveRules().size());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+
+ public class XooProfileImporter extends ProfileImporter {
+ public XooProfileImporter() {
+ super("XooProfileImporter", "Xoo Profile Importer");
+ }
+
+ @Override
+ public String[] getSupportedLanguages() {
+ return new String[] {"xoo"};
+ }
+
+ @Override
+ public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
+ RulesProfile rulesProfile = RulesProfile.create();
+ rulesProfile.activateRule(Rule.create(rule.getRepositoryKey(), rule.getRuleKey()), RulePriority.CRITICAL);
+ return rulesProfile;
+ }
+ }
+
+ public static class XooProfileImporterWithMessages extends ProfileImporter {
+ public XooProfileImporterWithMessages() {
+ super("XooProfileImporterWithMessages", "Xoo Profile Importer With Message");
+ }
+
+ @Override
+ public String[] getSupportedLanguages() {
+ return new String[] {};
+ }
+
+ @Override
+ public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
+ messages.addWarningText("a warning");
+ messages.addInfoText("an info");
+ return RulesProfile.create();
+ }
+ }
+
+ public static class XooProfileImporterWithError extends ProfileImporter {
+ public XooProfileImporterWithError() {
+ super("XooProfileImporterWithError", "Xoo Profile Importer With Error");
+ }
+
+ @Override
+ public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
+ messages.addErrorText("error!");
+ return RulesProfile.create();
+ }
+ }
}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java
index 72af140e8fe..95195117374 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java
@@ -53,7 +53,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
-public class QProfileFactoryTest {
+public class QProfileFactoryImplTest {
private System2 system2 = new AlwaysIncreasingSystem2();
@@ -64,7 +64,7 @@ public class QProfileFactoryTest {
private DbSession dbSession = db.getSession();
private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
- private QProfileFactory underTest = new QProfileFactory(db.getDbClient(), new SequenceUuidFactory(), system2, activeRuleIndexer);
+ private QProfileFactory underTest = new QProfileFactoryImpl(db.getDbClient(), new SequenceUuidFactory(), system2, activeRuleIndexer);
private RuleDefinitionDto rule;
private RuleParamDto ruleParam;
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorMediumTest.java
deleted file mode 100644
index 7553421f401..00000000000
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorMediumTest.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.server.qualityprofile;
-
-// TODO Replace ServerTester by EsTester and DbTester
-public class RuleActivatorMediumTest {
-
-// static final RuleKey TEMPLATE_RULE_KEY = RuleKey.of("xoo", "template1");
-// static final RuleKey CUSTOM_RULE_KEY = RuleKey.of("xoo", "custom1");
-//
-// @Before
-// public void before() {
-// tester.clearDbAndIndexes();
-// db = tester.get(DbClient.class);
-// dbSession = db.openSession(false);
-// ruleActivator = tester.get(RuleActivator.class);
-// activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
-// ruleIndexer = tester.get(RuleIndexer.class);
-// String defaultOrganizationUuid = tester.get(DefaultOrganizationProvider.class).get().getUuid();
-// organization = db.organizationDao().selectByUuid(dbSession, defaultOrganizationUuid).orElseThrow(() -> new IllegalStateException(String.format("Cannot find default organization '%s'", defaultOrganizationUuid)));
-//
-// // create pre-defined rules
-// RuleDto javaRule = newDto(RuleKey.of("squid", "j1"))
-// .setSeverity("MAJOR").setLanguage("java");
-// RuleDto xooRule1 = newXooX1().setSeverity("MINOR");
-// RuleDto xooRule2 = newXooX2().setSeverity("INFO");
-// RuleDto xooTemplateRule1 = newTemplateRule(TEMPLATE_RULE_KEY)
-// .setSeverity("MINOR").setLanguage("xoo");
-//
-// // store pre-defined rules in database
-// asList(javaRule, xooRule1, xooRule2, xooTemplateRule1).stream()
-// .map(RuleDto::getDefinition)
-// .forEach(definition -> db.ruleDao().insert(dbSession, definition));
-// db.ruleDao().insertRuleParam(dbSession, xooRule1.getDefinition(), RuleParamDto.createFor(xooRule1.getDefinition())
-// .setName("max").setDefaultValue("10").setType(RuleParamType.INTEGER.type()));
-// db.ruleDao().insertRuleParam(dbSession, xooRule1.getDefinition(), RuleParamDto.createFor(xooRule1.getDefinition())
-// .setName("min").setType(RuleParamType.INTEGER.type()));
-// db.ruleDao().insertRuleParam(dbSession, xooTemplateRule1.getDefinition(), RuleParamDto.createFor(xooTemplateRule1.getDefinition())
-// .setName("format").setType(RuleParamType.STRING.type()));
-//
-// // create custom rule
-// RuleDto xooCustomRule1 = newCustomRule(xooTemplateRule1).setRuleKey(CUSTOM_RULE_KEY.rule())
-// .setSeverity("MINOR").setLanguage("xoo");
-//
-// // store custom rule in database
-// db.ruleDao().insert(dbSession, xooCustomRule1.getDefinition());
-// db.ruleDao().insertRuleParam(dbSession, xooCustomRule1.getDefinition(), RuleParamDto.createFor(xooTemplateRule1.getDefinition())
-// .setName("format").setDefaultValue("txt").setType(RuleParamType.STRING.type()));
-//
-// // create pre-defined profile P1
-// profileDto = QProfileTesting.newXooP1(organization);
-// db.qualityProfileDao().insert(dbSession, profileDto);
-//
-// // index all rules
-// dbSession.commit();
-// ruleIndexer.indexRuleDefinitions(Stream.of(javaRule, xooRule1, xooRule2, xooTemplateRule1, xooCustomRule1).map(RuleDto::getKey).collect(Collectors.toList()));
-// }
-//
-// @After
-// public void after() {
-// dbSession.close();
-// }
-//
-//
-//
-//
-//
-//
-//
-//
-//
-// @Test
-// public void ignore_activation_errors_when_setting_parent() {
-// // x1 and x2 are activated on the "future parent" P1
-// RuleActivation activation = new RuleActivation(XOO_X1).setSeverity("MAJOR");
-// activate(activation, XOO_P1_KEY);
-// activation = new RuleActivation(XOO_X2).setSeverity("MAJOR");
-// activate(activation, XOO_P1_KEY);
-//
-// // create profile P2
-// db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2("org-123"));
-//
-// // mark rule x1 as REMOVED
-// RuleDefinitionDto rule = db.ruleDao().selectOrFailDefinitionByKey(dbSession, XOO_X1);
-// rule.setStatus(RuleStatus.REMOVED);
-// db.ruleDao().update(dbSession, rule);
-// dbSession.commit();
-// dbSession.clearCache();
-//
-// // set parent -> child profile inherits x2 but not x1
-// ruleActivator.setParent(dbSession, selectProfile(XOO_P2_KEY), selectProfile(XOO_P1_KEY));
-// dbSession.clearCache();
-//
-// assertThat(db.qualityProfileDao().selectByUuid(dbSession, XOO_P2_KEY).getParentKee()).isEqualTo(XOO_P1_KEY);
-// assertThat(countActiveRules(XOO_P2_KEY)).isEqualTo(1);
-// verifyHasActiveRuleInDbAndIndex(ActiveRuleKey.of(XOO_P2_KEY, XOO_X2), MAJOR, INHERITED, Collections.emptyMap());
-// }
-//
-//
-// private int countActiveRules(String profileKey) {
-// List<ActiveRuleDto> activeRuleDtos = db.activeRuleDao().selectByProfileUuid(dbSession, profileKey);
-// return activeRuleDtos.size();
-// }
-//
-// private void verifyOneActiveRuleInDb(String profileKey, RuleKey ruleKey, String expectedSeverity,
-// @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-// assertThat(countActiveRules(profileKey)).isEqualTo(1);
-// verifyHasActiveRuleInDb(ActiveRuleKey.of(profileKey, ruleKey), expectedSeverity, expectedInheritance, expectedParams);
-// }
-//
-// private void verifyOneActiveRuleInDbAndIndex(String profileKey, RuleKey ruleKey, String expectedSeverity,
-// @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-// assertThat(countActiveRules(profileKey)).isEqualTo(1);
-// verifyHasActiveRuleInDbAndIndex(ActiveRuleKey.of(profileKey, ruleKey), expectedSeverity, expectedInheritance, expectedParams);
-// }
-//
-// private void verifyHasActiveRuleInDb(ActiveRuleKey activeRuleKey, String expectedSeverity,
-// @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-// // verify db
-// boolean found = false;
-// List<ActiveRuleDto> activeRuleDtos = db.activeRuleDao().selectByProfileUuid(dbSession, activeRuleKey.getRuleProfileUuid());
-// for (ActiveRuleDto activeRuleDto : activeRuleDtos) {
-// if (activeRuleDto.getKey().equals(activeRuleKey)) {
-// found = true;
-// assertThat(activeRuleDto.getSeverityString()).isEqualTo(expectedSeverity);
-// assertThat(activeRuleDto.getInheritance()).isEqualTo(expectedInheritance);
-// // Dates should be set
-// assertThat(activeRuleDto.getCreatedAt()).isNotNull();
-// assertThat(activeRuleDto.getUpdatedAt()).isNotNull();
-//
-// List<ActiveRuleParamDto> paramDtos = db.activeRuleDao().selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
-// assertThat(paramDtos).hasSize(expectedParams.size());
-// for (Map.Entry<String, String> entry : expectedParams.entrySet()) {
-// ActiveRuleParamDto paramDto = db.activeRuleDao().selectParamByKeyAndName(activeRuleDto.getKey(), entry.getKey(), dbSession);
-// assertThat(paramDto).isNotNull();
-// assertThat(paramDto.getValue()).isEqualTo(entry.getValue());
-// }
-// }
-// }
-// assertThat(found).as("Rule is not activated in db").isTrue();
-// }
-//
-// private void verifyHasActiveRuleInIndex(ActiveRuleKey activeRuleKey, String expectedSeverity, @Nullable String expectedInheritance) {
-// // verify es
-// List<RuleKey> ruleKeys = newArrayList(tester.get(RuleIndex.class).searchAll(
-// new RuleQuery()
-// .setKey(activeRuleKey.getRuleKey().toString())
-// .setQProfileKey(activeRuleKey.getRuleProfileUuid())
-// .setActivation(true)
-// .setInheritance(singleton(expectedInheritance == null ? ActiveRule.Inheritance.NONE.name() : ActiveRule.Inheritance.valueOf(expectedInheritance).name()))
-// .setActiveSeverities(singleton(expectedSeverity))));
-// assertThat(ruleKeys).as("Rule is not activated in index").hasSize(1);
-// }
-//
-// private void verifyHasActiveRuleInDbAndIndex(ActiveRuleKey activeRuleKey, String expectedSeverity,
-// @Nullable String expectedInheritance, Map<String, String> expectedParams) {
-// verifyHasActiveRuleInDb(activeRuleKey, expectedSeverity, expectedInheritance, expectedParams);
-// verifyHasActiveRuleInIndex(activeRuleKey, expectedSeverity, expectedInheritance);
-// }
-//
-// private void createChildProfiles() {
-// db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2("org-123").setParentKee(XOO_P1_KEY));
-// db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP3("org-123").setParentKee(XOO_P2_KEY));
-// dbSession.commit();
-// }
-//
-// private List<ActiveRuleChange> activate(RuleActivation activation, String profileKey) {
-// List<ActiveRuleChange> changes = ruleActivator.activate(dbSession, activation, profileKey);
-// dbSession.commit();
-// dbSession.clearCache();
-// activeRuleIndexer.index(changes);
-// return changes;
-// }
-//
-// private void verifyZeroActiveRules(String key) {
-// // verify db
-// dbSession.clearCache();
-// List<ActiveRuleDto> activeRuleDtos = db.activeRuleDao().selectByProfileUuid(dbSession, key);
-// assertThat(activeRuleDtos).isEmpty();
-//
-// // verify es
-// assertThat(tester.get(RuleIndex.class).searchAll(
-// new RuleQuery()
-// .setQProfileKey(key)
-// .setActivation(true))).isEmpty();
-// }
-//
-// private void assertProfileHasBeenUpdatedManually(String profileKey) {
-// QProfileDto profile = db.qualityProfileDao().selectByUuid(dbSession, profileKey);
-// assertThat(profile.getRulesUpdatedAt()).isNotEmpty();
-// assertThat(profile.getUserUpdatedAt()).isNotNull();
-// }
-//
-// private void assertProfileHasBeenUpdatedAutomatically(String profileKey) {
-// QProfileDto profile = db.qualityProfileDao().selectByUuid(dbSession, profileKey);
-// assertThat(profile.getRulesUpdatedAt()).isNotEmpty();
-// assertThat(profile.getUserUpdatedAt()).isNull();
-// }
-}
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java
index d75471f8ec5..8f3a6ae214b 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RuleActivatorTest.java
@@ -113,6 +113,7 @@ public class RuleActivatorTest {
RuleActivation activation = RuleActivation.create(rule.getKey(), BLOCKER, null);
List<ActiveRuleChange> changes = activate(profile, activation);
+
assertThatRuleIsActivated(profile, rule, changes, BLOCKER, null, emptyMap());
assertThatProfileIsUpdatedByUser(profile);
}
@@ -1046,6 +1047,24 @@ public class RuleActivatorTest {
.hasSize(3);
}
+ @Test
+ public void activation_errors_are_ignored_when_setting_a_parent() {
+ RuleDefinitionDto rule1 = createJavaRule();
+ RuleDefinitionDto rule2 = createJavaRule();
+ QProfileDto parentProfile = createProfile(rule1);
+ activate(parentProfile, RuleActivation.create(rule1.getKey()));
+ activate(parentProfile, RuleActivation.create(rule2.getKey()));
+
+ rule1.setStatus(RuleStatus.REMOVED);
+ db.rules().update(rule1);
+
+ QProfileDto childProfile = createProfile(rule1);
+ List<ActiveRuleChange> changes = underTest.setParent(db.getSession(), childProfile, parentProfile);
+
+ assertThatRuleIsNotPresent(childProfile, rule1);
+ assertThatRuleIsActivated(childProfile, rule2, changes, rule2.getSeverityString(), INHERITED, emptyMap());
+ }
+
private void assertThatProfileHasNoActiveRules(QProfileDto profile) {
List<OrgActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile);
assertThat(activeRules).isEmpty();
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java
index a7f7fc21bcd..73faa831fa5 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java
@@ -44,6 +44,7 @@ import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileCopier;
import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.QProfileRestoreSummary;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
@@ -68,7 +69,7 @@ public class CopyActionTest {
@Rule
public JUnitTempFolder tempDir = new JUnitTempFolder();
private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
- private QProfileFactory profileFactory = new QProfileFactory(db.getDbClient(), new SequenceUuidFactory(), System2.INSTANCE, activeRuleIndexer);
+ private QProfileFactory profileFactory = new QProfileFactoryImpl(db.getDbClient(), new SequenceUuidFactory(), System2.INSTANCE, activeRuleIndexer);
private TestBackuper backuper = new TestBackuper();
private QProfileCopier profileCopier = new QProfileCopier(db.getDbClient(), profileFactory, backuper, tempDir);
private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java
index 55e59f3ca32..bb59a6dcf81 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java
@@ -47,7 +47,7 @@ import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.qualityprofile.QProfileExporters;
-import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.RuleActivator;
import org.sonar.server.qualityprofile.RuleActivatorContextFactory;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
@@ -100,7 +100,7 @@ public class CreateActionTest {
profileImporters);
private OrganizationDto organization;
- private CreateAction underTest = new CreateAction(dbClient, new QProfileFactory(dbClient, UuidFactoryFast.getInstance(), system2, activeRuleIndexer), qProfileExporters,
+ private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), system2, activeRuleIndexer), qProfileExporters,
newLanguages(XOO_LANGUAGE), new QProfileWsSupport(dbClient, userSession, defaultOrganizationProvider),
userSession, activeRuleIndexer, profileImporters);
private WsActionTester wsTester = new WsActionTester(underTest);
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java
index a1b8bdb03c1..f1bfc65009e 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java
@@ -38,7 +38,7 @@ import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
-import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
@@ -64,7 +64,7 @@ public class DeleteActionTest {
private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private DeleteAction underTest = new DeleteAction(
new Languages(LanguageTesting.newLanguage(A_LANGUAGE)),
- new QProfileFactory(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
+ new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
dbClient, userSessionRule,
new QProfileWsSupport(dbClient, userSessionRule, TestDefaultOrganizationProvider.from(dbTester)));
private WsActionTester tester = new WsActionTester(underTest);
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/bad-xml-backup.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/bad-xml-backup.xml
deleted file mode 100644
index f1999f80cc1..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/bad-xml-backup.xml
+++ /dev/null
@@ -1 +0,0 @@
-<foo/>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/empty.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/empty.xml
deleted file mode 100644
index 937009dce6c..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/empty.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P1</name>
- <language>xoo</language>
-</profile>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/expected-backup.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/expected-backup.xml
deleted file mode 100644
index 037019f9c5a..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/expected-backup.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P1</name>
- <language>xoo</language>
- <rules>
- <rule>
- <repositoryKey>blah</repositoryKey>
- <key>my-rule</key>
- <priority>INFO</priority>
- <parameters/>
- </rule>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x1</key>
- <priority>BLOCKER</priority>
- <parameters>
- <parameter>
- <key>max</key>
- <value>7</value>
- </parameter>
- </parameters>
- </rule>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x2</key>
- <priority>MINOR</priority>
- <parameters/>
- </rule>
- </rules>
-</profile>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/keep_other_inherited_rules.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/keep_other_inherited_rules.xml
deleted file mode 100644
index 368fa6cd456..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/keep_other_inherited_rules.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P2</name>
- <language>xoo</language>
- <rules>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x2</key>
- <priority>BLOCKER</priority>
- </rule>
- </rules>
-</profile>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/not-xml-backup.txt b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/not-xml-backup.txt
deleted file mode 100644
index 53451f2e47b..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/not-xml-backup.txt
+++ /dev/null
@@ -1 +0,0 @@
-invalid backup
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-child.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-child.xml
deleted file mode 100644
index 94c63aa3a43..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-child.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P2</name>
- <language>xoo</language>
- <rules>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x1</key>
- <priority>BLOCKER</priority>
- <parameters>
- <parameter>
- <key>max</key>
- <value>7</value>
- </parameter>
- </parameters>
- </rule>
- </rules>
-</profile>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-parent.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-parent.xml
deleted file mode 100644
index 1786ed941dd..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore-parent.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P1</name>
- <language>xoo</language>
- <rules>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x1</key>
- <priority>BLOCKER</priority>
- <parameters>
- <parameter>
- <key>max</key>
- <value>7</value>
- </parameter>
- </parameters>
- </rule>
- </rules>
-</profile>
diff --git a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore.xml b/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore.xml
deleted file mode 100644
index 1786ed941dd..00000000000
--- a/server/sonar-server/src/test/resources/org/sonar/server/qualityprofile/QProfileBackuperMediumTest/restore.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<profile>
- <name>P1</name>
- <language>xoo</language>
- <rules>
- <rule>
- <repositoryKey>xoo</repositoryKey>
- <key>x1</key>
- <priority>BLOCKER</priority>
- <parameters>
- <parameter>
- <key>max</key>
- <value>7</value>
- </parameter>
- </parameters>
- </rule>
- </rules>
-</profile>