]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-4326 Refactor ESActiveRule out of RuleRegistry
authorJean-Baptiste Lievremont <jean-baptiste.lievremont@sonarsource.com>
Thu, 23 Jan 2014 12:11:06 +0000 (13:11 +0100)
committerJean-Baptiste Lievremont <jean-baptiste.lievremont@sonarsource.com>
Thu, 23 Jan 2014 15:39:00 +0000 (16:39 +0100)
32 files changed:
sonar-core/src/main/java/org/sonar/core/qualityprofile/db/ActiveRuleDto.java
sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java
sonar-core/src/main/java/org/sonar/core/rule/SeverityUtil.java [new file with mode: 0644]
sonar-core/src/test/java/org/sonar/core/qualityprofile/db/ActiveRuleDaoTest.java
sonar-core/src/test/java/org/sonar/core/rule/RuleDaoTest.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperations.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfilePluginExporter.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleLookup.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleOperations.java
sonar-server/src/main/java/org/sonar/server/rule/RuleRegistration.java
sonar-server/src/main/java/org/sonar/server/rule/RuleRegistry.java
sonar-server/src/main/java/org/sonar/server/startup/RegisterNewProfiles.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/ESActiveRuleTest.java [new file with mode: 0644]
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperationsTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackupTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileOperationsTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilePluginExporterTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleLookupTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleOperationsTest.java
sonar-server/src/test/java/org/sonar/server/rule/RuleRegistryTest.java
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule25.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule2702.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule523.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule1.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule2.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule3.json [new file with mode: 0644]
sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule25.json [deleted file]
sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule2702.json [deleted file]
sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule523.json [deleted file]

index 1f83e8e52f4d942f48f217814073e1aa34ed1825..860a1d7ee99cfffbd718f135e000896166becf17 100644 (file)
@@ -20,6 +20,8 @@
 
 package org.sonar.core.qualityprofile.db;
 
+import org.sonar.core.rule.SeverityUtil;
+
 import org.apache.commons.lang.StringUtils;
 
 import javax.annotation.CheckForNull;
@@ -78,11 +80,20 @@ public class ActiveRuleDto {
     return severity;
   }
 
+  public String getSeverityString() {
+    return SeverityUtil.getSeverityFromOrdinal(severity);
+  }
+
   public ActiveRuleDto setSeverity(Integer severity) {
     this.severity = severity;
     return this;
   }
 
+  public ActiveRuleDto setSeverity(String severity) {
+    this.severity = SeverityUtil.getOrdinalFromSeverity(severity);
+    return this;
+  }
+
   @CheckForNull
   public String getInheritance() {
     return inheritance;
index 3616c00cd51a409672f0301a51deeceedbc5306d..05ab52775ca878e9a9a2f2f854265c0ab32553f9 100644 (file)
@@ -113,11 +113,21 @@ public final class RuleDto {
     return severity;
   }
 
+  public String getSeverityString() {
+    return SeverityUtil.getSeverityFromOrdinal(severity);
+  }
+
+  public RuleDto setSeverity(String severity) {
+    this.severity = SeverityUtil.getOrdinalFromSeverity(severity);
+    return this;
+  }
+
   public RuleDto setSeverity(Integer severity) {
     this.severity = severity;
     return this;
   }
 
+
   public Cardinality getCardinality() {
     return cardinality;
   }
@@ -231,7 +241,7 @@ public final class RuleDto {
       .append("key", ruleKey)
       .append("configKey", configKey)
       .append("plugin", repositoryKey)
-      .append("severity", getSeverity())
+      .append("severity", getSeverityString())
       .append("cardinality", cardinality)
       .append("status", status)
       .append("language", language)
diff --git a/sonar-core/src/main/java/org/sonar/core/rule/SeverityUtil.java b/sonar-core/src/main/java/org/sonar/core/rule/SeverityUtil.java
new file mode 100644 (file)
index 0000000..578ae7d
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+package org.sonar.core.rule;
+
+import org.sonar.api.rule.Severity;
+
+public class SeverityUtil {
+
+  private SeverityUtil() {
+    // Only static stuff
+  }
+
+  public static String getSeverityFromOrdinal(int ordinal) {
+    return Severity.ALL.get(ordinal);
+  }
+
+  public static int getOrdinalFromSeverity(String severity) {
+    return Severity.ALL.indexOf(severity);
+  }
+}
index fe8482ee956fa4442b4a10c0d3e55d1a0efdc95d..9b3ba405b717d5e65a7fd02c3871e489f6a7bfbb 100644 (file)
@@ -25,6 +25,7 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import org.junit.Before;
 import org.junit.Test;
+import org.sonar.api.rule.Severity;
 import org.sonar.api.utils.DateUtils;
 import org.sonar.core.persistence.AbstractDaoTestCase;
 
@@ -48,7 +49,7 @@ public class ActiveRuleDaoTest extends AbstractDaoTestCase {
     ActiveRuleDto dto = new ActiveRuleDto()
       .setProfileId(1)
       .setRuleId(10)
-      .setSeverity(2)
+      .setSeverity(Severity.MAJOR)
       .setInheritance("INHERITED");
 
     dao.insert(dto);
@@ -64,7 +65,7 @@ public class ActiveRuleDaoTest extends AbstractDaoTestCase {
       .setId(1)
       .setProfileId(1)
       .setRuleId(10)
-      .setSeverity(4)
+      .setSeverity(Severity.BLOCKER)
       .setInheritance(null)
       .setNoteData("text");
 
@@ -108,7 +109,7 @@ public class ActiveRuleDaoTest extends AbstractDaoTestCase {
     assertThat(result.getId()).isEqualTo(1);
     assertThat(result.getProfileId()).isEqualTo(1);
     assertThat(result.getRulId()).isEqualTo(10);
-    assertThat(result.getSeverity()).isEqualTo(2);
+    assertThat(result.getSeverityString()).isEqualTo(Severity.MAJOR);
     assertThat(result.getInheritance()).isEqualTo("INHERITED");
     assertThat(result.getNoteData()).isEqualTo("some note");
     assertThat(result.getNoteUserLogin()).isEqualTo("henry");
@@ -135,7 +136,7 @@ public class ActiveRuleDaoTest extends AbstractDaoTestCase {
     assertThat(result.getId()).isEqualTo(1);
     assertThat(result.getProfileId()).isEqualTo(1);
     assertThat(result.getRulId()).isEqualTo(10);
-    assertThat(result.getSeverity()).isEqualTo(2);
+    assertThat(result.getSeverityString()).isEqualTo(Severity.MAJOR);
     assertThat(result.getInheritance()).isEqualTo("INHERITED");
     assertThat(result.getNoteData()).isEqualTo("some note");
     assertThat(result.getNoteUserLogin()).isEqualTo("henry");
index 4c661e119cb1a86a92273d8e4db8c5fcb19463e9..61ff4eaced99cc40f6886d042494123245d60cf6 100644 (file)
@@ -23,6 +23,7 @@ import com.google.common.collect.ImmutableList;
 import org.apache.ibatis.session.SqlSession;
 import org.junit.Before;
 import org.junit.Test;
+import org.sonar.api.rule.Severity;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.utils.DateUtils;
 import org.sonar.check.Cardinality;
@@ -110,7 +111,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
       .setDescription("new description")
       .setStatus(Rule.STATUS_DEPRECATED)
       .setConfigKey("NewConfigKey")
-      .setSeverity(0)
+      .setSeverity(Severity.INFO)
       .setCardinality(Cardinality.MULTIPLE)
       .setLanguage("dart")
       .setParentId(3)
@@ -135,7 +136,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
     String newDescription = "new description";
     String newStatus = Rule.STATUS_DEPRECATED;
     String newConfigKey = "NewConfigKey";
-    Integer newSeverity = 0;
+    String newSeverity = Severity.INFO;
     Cardinality newCardinality = Cardinality.MULTIPLE;
     String newLanguage = "dart";
     Date updatedAt = new Date();
@@ -147,7 +148,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
     ruleToInsert.setDescription(newDescription);
     ruleToInsert.setStatus(newStatus);
     ruleToInsert.setConfigKey(newConfigKey);
-    ruleToInsert.setSeverity(0);
+    ruleToInsert.setSeverity(Severity.INFO);
     ruleToInsert.setCardinality(newCardinality);
     ruleToInsert.setLanguage(newLanguage);
     ruleToInsert.setUpdatedAt(updatedAt);
@@ -165,7 +166,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
     assertThat(insertedRule.getDescription()).isEqualTo(newDescription);
     assertThat(insertedRule.getStatus()).isEqualTo(newStatus);
     assertThat(insertedRule.getConfigKey()).isEqualTo(newConfigKey);
-    assertThat(insertedRule.getSeverity()).isEqualTo(newSeverity);
+    assertThat(insertedRule.getSeverityString()).isEqualTo(newSeverity);
     assertThat(insertedRule.getCardinality()).isEqualTo(newCardinality);
     assertThat(insertedRule.getLanguage()).isEqualTo(newLanguage);
     assertThat(insertedRule.getParentId()).isEqualTo(newParentId);
@@ -181,7 +182,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
     String newDescription = "new description1";
     String newStatus = Rule.STATUS_DEPRECATED;
     String newConfigKey = "NewConfigKey1";
-    Integer newSeverity = 0;
+    String newSeverity = Severity.INFO;
     Cardinality newCardinality = Cardinality.MULTIPLE;
     String newLanguage = "dart";
     Date createdAt = new Date();
@@ -206,7 +207,7 @@ public class RuleDaoTest extends AbstractDaoTestCase {
     String newDescription1 = "new description2";
     String newStatus1 = Rule.STATUS_DEPRECATED;
     String newConfigKey1 = "NewConfigKey2";
-    Integer newSeverity1 = 0;
+    String newSeverity1 = Severity.INFO;
     Cardinality newCardinality1 = Cardinality.MULTIPLE;
     String newLanguage1 = "dart";
     Date createdAt1 = new Date();
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java
new file mode 100644 (file)
index 0000000..eafacdd
--- /dev/null
@@ -0,0 +1,216 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with 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 org.elasticsearch.common.io.BytesStream;
+import org.elasticsearch.index.query.FilterBuilders;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
+import org.sonar.server.rule.ActiveRuleDocument;
+import org.sonar.server.rule.RuleDocument;
+import com.google.common.base.Function;
+import com.google.common.collect.Iterables;
+import org.sonar.server.es.SearchQuery;
+import org.sonar.server.es.ESIndex;
+import org.sonar.server.rule.RuleRegistry;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
+import org.apache.ibatis.session.SqlSession;
+import org.sonar.api.utils.TimeProfiler;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+import org.sonar.core.persistence.MyBatis;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+
+public class ESActiveRule {
+
+  public static final String TYPE_ACTIVE_RULE = "active_rule";
+  private final ESIndex esIndex;
+  private final ActiveRuleDao activeRuleDao;
+  private final MyBatis myBatis;
+
+  public ESActiveRule(ESIndex esIndex, ActiveRuleDao activeRuleDao, MyBatis myBatis) {
+    this.esIndex = esIndex;
+    this.activeRuleDao = activeRuleDao;
+    this.myBatis = myBatis;
+  }
+
+  public void start() {
+    esIndex.addMappingFromClasspath(RuleRegistry.INDEX_RULES, TYPE_ACTIVE_RULE, "/org/sonar/server/es/config/mappings/active_rule_mapping.json");
+  }
+
+  public void bulkRegisterActiveRules() {
+    SqlSession session = myBatis.openSession();
+    try {
+      TimeProfiler profiler = new TimeProfiler();
+      profiler.start("Rebuilding active rules index - query");
+
+      List<ActiveRuleDto> activeRules = activeRuleDao.selectAll(session);
+      List<ActiveRuleParamDto> activeRuleParams = activeRuleDao.selectAllParams(session);
+      profiler.stop();
+
+      Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
+      for (ActiveRuleParamDto param : activeRuleParams) {
+        paramsByActiveRule.put(param.getActiveRuleId(), param);
+      }
+
+      String[] ids = bulkIndexActiveRules(activeRules, paramsByActiveRule);
+      removeDeletedActiveRules(ids);
+    } finally {
+      MyBatis.closeQuietly(session);
+    }
+  }
+
+  public void bulkIndexProfile(int profileId, SqlSession session) {
+    bulkIndexActiveRules(activeRuleDao.selectByProfileId(profileId, session), session);
+  }
+
+  public void bulkIndexActiveRuleIds(List<Integer> activeRulesIds, SqlSession session) {
+    bulkIndexActiveRules(activeRuleDao.selectByIds(activeRulesIds, session), session);
+  }
+
+  public void bulkIndexActiveRules(List<Integer> ids) {
+    SqlSession session = myBatis.openSession();
+    try {
+      bulkIndexActiveRuleIds(ids, session);
+    } finally {
+      MyBatis.closeQuietly(session);
+    }
+  }
+
+  public void deleteActiveRulesFromProfile(int profileId) {
+    esIndex.client().prepareDeleteByQuery(RuleRegistry.INDEX_RULES).setTypes(ESActiveRule.TYPE_ACTIVE_RULE)
+      .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
+        FilterBuilders.termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, profileId)))
+      .execute().actionGet();
+  }
+
+  public String[] bulkIndexActiveRules(List<ActiveRuleDto> activeRules, Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule) {
+    try {
+      int size = activeRules.size();
+      String[] ids = new String[size];
+      BytesStream[] docs = new BytesStream[size];
+      String[] parentIds = new String[size];
+      int index = 0;
+
+      TimeProfiler profiler = new TimeProfiler();
+      profiler.start("Build active rules documents");
+      for (ActiveRuleDto activeRule : activeRules) {
+        ids[index] = activeRule.getId().toString();
+        docs[index] = activeRuleDocument(activeRule, paramsByActiveRule.get(activeRule.getId()));
+        parentIds[index] = activeRule.getRulId().toString();
+        index++;
+      }
+      profiler.stop();
+
+      if (!activeRules.isEmpty()) {
+        profiler.start("Index active rules");
+        esIndex.bulkIndex(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, ids, docs, parentIds);
+        profiler.stop();
+      }
+      return ids;
+    } catch (IOException e) {
+      throw new IllegalStateException("Unable to index active rules", e);
+    }
+  }
+
+  public void save(ActiveRuleDto activeRule, Collection<ActiveRuleParamDto> params) {
+    try {
+      esIndex.putSynchronous(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, Long.toString(activeRule.getId()), activeRuleDocument(activeRule, params), Long.toString(activeRule.getRulId()));
+    } catch (IOException ioexception) {
+      throw new IllegalStateException("Unable to index active rule with id=" + activeRule.getId(), ioexception);
+    }
+  }
+
+  public void deleteActiveRules(List<Integer> activeRuleIds) {
+    List<String> indexIds = newArrayList();
+    for (Integer ruleId : activeRuleIds) {
+      indexIds.add(ruleId.toString());
+    }
+    bulkDeleteActiveRules(indexIds);
+  }
+
+  protected void bulkDeleteActiveRules(List<String> indexIds) {
+    if (!indexIds.isEmpty()) {
+      esIndex.bulkDelete(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, indexIds.toArray(new String[0]));
+    }
+  }
+
+  private void bulkIndexActiveRules(List<ActiveRuleDto> activeRules, SqlSession session) {
+    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
+    List<Integer> activeRulesIdList = newArrayList(Iterables.transform(activeRules, new Function<ActiveRuleDto, Integer>() {
+      @Override
+      public Integer apply(ActiveRuleDto input) {
+        return input.getId();
+      }
+    }));
+    for (ActiveRuleParamDto param : activeRuleDao.selectParamsByActiveRuleIds(activeRulesIdList, session)) {
+      paramsByActiveRule.put(param.getActiveRuleId(), param);
+    }
+    bulkIndexActiveRules(activeRules, paramsByActiveRule);
+  }
+
+  private void removeDeletedActiveRules(String[] ids) {
+    TimeProfiler profiler = new TimeProfiler();
+    List<String> indexIds = esIndex.findDocumentIds(SearchQuery.create().index(RuleRegistry.INDEX_RULES).type(ESActiveRule.TYPE_ACTIVE_RULE));
+    indexIds.removeAll(newArrayList(ids));
+    profiler.start("Remove deleted active rule documents");
+    bulkDeleteActiveRules(indexIds);
+    profiler.stop();
+  }
+
+  private XContentBuilder activeRuleDocument(ActiveRuleDto activeRule, Collection<ActiveRuleParamDto> params) throws IOException {
+    XContentBuilder document = XContentFactory.jsonBuilder()
+      .startObject()
+      .field(ActiveRuleDocument.FIELD_ID, activeRule.getId())
+      .field(ActiveRuleDocument.FIELD_ACTIVE_RULE_PARENT_ID, activeRule.getParentId())
+      .field(ActiveRuleDocument.FIELD_SEVERITY, activeRule.getSeverityString())
+      .field(ActiveRuleDocument.FIELD_PROFILE_ID, activeRule.getProfileId())
+      .field(ActiveRuleDocument.FIELD_INHERITANCE, activeRule.getInheritance());
+    if (activeRule.getNoteData() != null || activeRule.getNoteUserLogin() != null) {
+      document.startObject(RuleDocument.FIELD_NOTE)
+        .field(ActiveRuleDocument.FIELD_NOTE_DATA, activeRule.getNoteData())
+        .field(ActiveRuleDocument.FIELD_NOTE_USER_LOGIN, activeRule.getNoteUserLogin())
+        .field(ActiveRuleDocument.FIELD_NOTE_CREATED_AT, activeRule.getNoteCreatedAt())
+        .field(ActiveRuleDocument.FIELD_NOTE_UPDATED_AT, activeRule.getNoteUpdatedAt())
+        .endObject();
+    }
+    if (!params.isEmpty()) {
+      document.startArray(ActiveRuleDocument.FIELD_PARAMS);
+      for (ActiveRuleParamDto param : params) {
+        document.startObject()
+          .field(ActiveRuleDocument.FIELD_PARAM_KEY, param.getKey())
+          .field(ActiveRuleDocument.FIELD_PARAM_VALUE, param.getValue())
+          .endObject();
+      }
+      document.endArray();
+    }
+    document.endObject();
+    return document;
+  }
+
+}
index a78a5488a6217fd7f97484bc99d8045a7fc3b1f2..877e108b7ef49ea59d19e62dace0f53b234990fd 100644 (file)
@@ -33,18 +33,22 @@ import org.sonar.api.server.rule.RuleParamType;
 import org.sonar.api.utils.System2;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
 import org.sonar.core.rule.RuleDao;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleParamDto;
 import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.UserSession;
 import org.sonar.server.util.TypeValidations;
 
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
+
 import java.util.Date;
 import java.util.List;
 
@@ -56,25 +60,25 @@ public class QProfileActiveRuleOperations implements ServerComponent {
   private final ActiveRuleDao activeRuleDao;
   private final RuleDao ruleDao;
   private final QualityProfileDao profileDao;
-  private final RuleRegistry ruleRegistry;
+  private final ESActiveRule esActiveRule;
   private final ProfilesManager profilesManager;
 
   private final System2 system;
   private final TypeValidations typeValidations;
 
-  public QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, RuleRegistry ruleRegistry,
+  public QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, ESActiveRule esActiveRule,
                                       ProfilesManager profilesManager, TypeValidations typeValidations) {
-    this(myBatis, activeRuleDao, ruleDao, profileDao, ruleRegistry, profilesManager, typeValidations, System2.INSTANCE);
+    this(myBatis, activeRuleDao, ruleDao, profileDao, esActiveRule, profilesManager, typeValidations, System2.INSTANCE);
   }
 
   @VisibleForTesting
-  QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, RuleRegistry ruleRegistry,
+  QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, ESActiveRule esActiveRule,
                                ProfilesManager profilesManager, TypeValidations typeValidations, System2 system) {
     this.myBatis = myBatis;
     this.activeRuleDao = activeRuleDao;
     this.ruleDao = ruleDao;
     this.profileDao = profileDao;
-    this.ruleRegistry = ruleRegistry;
+    this.esActiveRule = esActiveRule;
     this.profilesManager = profilesManager;
     this.typeValidations = typeValidations;
     this.system = system;
@@ -103,7 +107,7 @@ public class QProfileActiveRuleOperations implements ServerComponent {
     ActiveRuleDto activeRule = new ActiveRuleDto()
       .setProfileId(profileId)
       .setRuleId(ruleId)
-      .setSeverity(getSeverityOrdinal(severity));
+      .setSeverity(severity);
     activeRuleDao.insert(activeRule, session);
 
     List<RuleParamDto> ruleParams = ruleDao.selectParameters(ruleId, session);
@@ -124,12 +128,12 @@ public class QProfileActiveRuleOperations implements ServerComponent {
   }
 
   private void updateSeverity(ActiveRuleDto activeRule, String newSeverity, UserSession userSession, SqlSession session) {
-    Integer oldSeverity = activeRule.getSeverity();
-    activeRule.setSeverity(getSeverityOrdinal(newSeverity));
+    String oldSeverity = activeRule.getSeverityString();
+    activeRule.setSeverity(newSeverity);
     activeRuleDao.update(activeRule, session);
     session.commit();
 
-    notifySeverityChanged(activeRule, newSeverity, getSeverityFromOrdinal(oldSeverity), session, userSession);
+    notifySeverityChanged(activeRule, newSeverity, oldSeverity, session, userSession);
   }
 
   public void activateRules(int profileId, List<Integer> ruleIdsToActivate, UserSession userSession) {
@@ -139,7 +143,7 @@ public class QProfileActiveRuleOperations implements ServerComponent {
     try {
       for (Integer ruleId : ruleIdsToActivate) {
         RuleDto rule = findRuleNotNull(ruleId, session);
-        createActiveRule(profileId, ruleId, getSeverityFromOrdinal(rule.getSeverity()), userSession, session);
+        createActiveRule(profileId, ruleId, rule.getSeverityString(), userSession, session);
       }
     } finally {
       MyBatis.closeQuietly(session);
@@ -330,14 +334,14 @@ public class QProfileActiveRuleOperations implements ServerComponent {
 
   private void restoreSeverityFromActiveRuleParent(ActiveRuleDto activeRule, ActiveRuleDto parent, ProfilesManager.RuleInheritanceActions actions,
                                                    UserSession userSession, SqlSession session) {
-    Integer oldSeverity = activeRule.getSeverity();
-    Integer newSeverity = parent.getSeverity();
+    String oldSeverity = activeRule.getSeverityString();
+    String newSeverity = parent.getSeverityString();
     if (!oldSeverity.equals(newSeverity)) {
       activeRule.setSeverity(newSeverity);
       activeRuleDao.update(activeRule, session);
       session.commit();
       actions.add(profilesManager.ruleSeverityChanged(activeRule.getProfileId(), activeRule.getId(),
-        RulePriority.valueOf(getSeverityFromOrdinal(oldSeverity)), RulePriority.valueOf(getSeverityFromOrdinal(newSeverity)), getLoggedName(userSession)));
+        RulePriority.valueOf(oldSeverity), RulePriority.valueOf(newSeverity), getLoggedName(userSession)));
     }
   }
 
@@ -396,8 +400,8 @@ public class QProfileActiveRuleOperations implements ServerComponent {
   }
 
   private void reindexInheritanceResult(ProfilesManager.RuleInheritanceActions actions, SqlSession session) {
-    ruleRegistry.deleteActiveRules(actions.idsToDelete());
-    ruleRegistry.bulkIndexActiveRuleIds(actions.idsToIndex(), session);
+    esActiveRule.deleteActiveRules(actions.idsToDelete());
+    esActiveRule.bulkIndexActiveRuleIds(actions.idsToIndex(), session);
   }
 
   private void reindexActiveRule(ActiveRuleDto activeRuleDto, SqlSession session) {
@@ -405,7 +409,7 @@ public class QProfileActiveRuleOperations implements ServerComponent {
   }
 
   private void reindexActiveRule(ActiveRuleDto activeRuleDto, List<ActiveRuleParamDto> params) {
-    ruleRegistry.save(activeRuleDto, params);
+    esActiveRule.save(activeRuleDto, params);
   }
 
   private void validatePermission(UserSession userSession) {
@@ -482,9 +486,4 @@ public class QProfileActiveRuleOperations implements ServerComponent {
   private static String getSeverityFromOrdinal(int ordinal) {
     return Severity.ALL.get(ordinal);
   }
-
-  private static int getSeverityOrdinal(String severity) {
-    return Severity.ALL.indexOf(severity);
-  }
-
 }
index ccdb1a29608dc77bbff37435d0cbf8ff95bd0045..d52c1166671810ed02568f76fe0bd0d504ef5b49 100644 (file)
@@ -50,18 +50,18 @@ public class QProfileBackup implements ServerComponent {
 
   private final MyBatis myBatis;
   private final QProfileLookup qProfileLookup;
-  private final RuleRegistry ruleRegistry;
+  private final ESActiveRule esActiveRule;
   private final PreviewCache dryRunCache;
 
   public QProfileBackup(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, XMLProfileSerializer xmlProfileSerializer, MyBatis myBatis,
-                        QProfileLookup qProfileLookup, RuleRegistry ruleRegistry, PreviewCache dryRunCache) {
+                        QProfileLookup qProfileLookup, ESActiveRule esActiveRule, PreviewCache dryRunCache) {
 
     this.sessionFactory = sessionFactory;
     this.xmlProfileParser = xmlProfileParser;
     this.xmlProfileSerializer = xmlProfileSerializer;
     this.myBatis = myBatis;
     this.qProfileLookup = qProfileLookup;
-    this.ruleRegistry = ruleRegistry;
+    this.esActiveRule = esActiveRule;
     this.dryRunCache = dryRunCache;
   }
 
@@ -96,7 +96,7 @@ public class QProfileBackup implements ServerComponent {
         if (newProfile == null) {
           throw new BadRequestException("Restore of the profile has failed.");
         }
-        ruleRegistry.bulkIndexProfile(newProfile.id(), session);
+        esActiveRule.bulkIndexProfile(newProfile.id(), session);
         dryRunCache.reportGlobalModification(session);
         session.commit();
         result.setProfile(newProfile);
@@ -116,7 +116,7 @@ public class QProfileBackup implements ServerComponent {
       // Warning, profile with children can be deleted as no check is done!
       hibernateSession.removeWithoutFlush(existingProfile);
       hibernateSession.commit();
-      ruleRegistry.deleteActiveRulesFromProfile(existingProfile.getId());
+      esActiveRule.deleteActiveRulesFromProfile(existingProfile.getId());
     }
   }
 
index cec9fb5ca360f347dc2a74639adf989f3f6e38c9..93e4cf1b18d06f3d0244fd8f8611607402f756da 100644 (file)
@@ -33,7 +33,6 @@ import org.sonar.core.qualityprofile.db.QualityProfileDao;
 import org.sonar.core.qualityprofile.db.QualityProfileDto;
 import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.UserSession;
 
 import javax.annotation.CheckForNull;
@@ -52,19 +51,19 @@ public class QProfileOperations implements ServerComponent {
   private final PropertiesDao propertiesDao;
   private final QProfilePluginExporter exporter;
   private final PreviewCache dryRunCache;
-  private final RuleRegistry ruleRegistry;
+  private final ESActiveRule esActiveRule;
   private final QProfileLookup profileLookup;
   private final ProfilesManager profilesManager;
 
   public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
-                            QProfilePluginExporter exporter, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
+                            QProfilePluginExporter exporter, PreviewCache dryRunCache, ESActiveRule esActiveRule, QProfileLookup profileLookup, ProfilesManager profilesManager) {
     this.myBatis = myBatis;
     this.dao = dao;
     this.activeRuleDao = activeRuleDao;
     this.propertiesDao = propertiesDao;
     this.exporter = exporter;
     this.dryRunCache = dryRunCache;
-    this.ruleRegistry = ruleRegistry;
+    this.esActiveRule = esActiveRule;
     this.profileLookup = profileLookup;
     this.profilesManager = profilesManager;
   }
@@ -149,7 +148,7 @@ public class QProfileOperations implements ServerComponent {
       activeRuleDao.deleteFromProfile(profile.getId(), session);
       dao.delete(profile.getId(), session);
       propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
-      ruleRegistry.deleteActiveRulesFromProfile(profile.getId());
+      esActiveRule.deleteActiveRulesFromProfile(profile.getId());
       dryRunCache.reportGlobalModification(session);
     }
   }
@@ -185,8 +184,8 @@ public class QProfileOperations implements ServerComponent {
       dao.update(profile, session);
       session.commit();
 
-      ruleRegistry.deleteActiveRules(actions.idsToDelete());
-      ruleRegistry.bulkIndexActiveRuleIds(actions.idsToIndex(), session);
+      esActiveRule.deleteActiveRules(actions.idsToDelete());
+      esActiveRule.bulkIndexActiveRuleIds(actions.idsToIndex(), session);
     } finally {
       MyBatis.closeQuietly(session);
     }
@@ -200,7 +199,7 @@ public class QProfileOperations implements ServerComponent {
       checkNotAlreadyExists(copyProfileName, profileDto.getLanguage(), session);
       int copyProfileId = profilesManager.copyProfile(profileId, copyProfileName);
       session.commit();
-      ruleRegistry.bulkIndexProfile(copyProfileId, session);
+      esActiveRule.bulkIndexProfile(copyProfileId, session);
     } finally {
       MyBatis.closeQuietly(session);
     }
index bcc632ca8b518f7bd31c13a2171bd7bc3352cd51..44e3de35c33dc801fbbd87f0c7c6c721691195c7 100644 (file)
@@ -41,7 +41,6 @@ import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
 import org.sonar.jpa.session.DatabaseSessionFactory;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.rule.RuleRegistry;
 
 import java.io.StringReader;
 import java.io.StringWriter;
@@ -55,22 +54,22 @@ public class QProfilePluginExporter implements ServerComponent {
 
   private final DatabaseSessionFactory sessionFactory;
   private final ActiveRuleDao activeRuleDao;
-  private final RuleRegistry ruleRegistry;
+  private final ESActiveRule ruleRegistry;
   private final List<ProfileExporter> exporters;
   private final List<ProfileImporter> importers;
 
   /**
    * Used by pico when no plugin provide profile exporter / importer
    */
-  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry) {
-    this(sessionFactory, activeRuleDao, ruleRegistry, Lists.<ProfileImporter>newArrayList(), Lists.<ProfileExporter>newArrayList());
+  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, ESActiveRule esActiveRule) {
+    this(sessionFactory, activeRuleDao, esActiveRule, Lists.<ProfileImporter>newArrayList(), Lists.<ProfileExporter>newArrayList());
   }
 
-  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry,
+  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, ESActiveRule esActiveRule,
                                 List<ProfileImporter> importers, List<ProfileExporter> exporters) {
     this.sessionFactory = sessionFactory;
     this.activeRuleDao = activeRuleDao;
-    this.ruleRegistry = ruleRegistry;
+    this.ruleRegistry = esActiveRule;
     this.importers = importers;
     this.exporters = exporters;
   }
@@ -136,8 +135,8 @@ public class QProfilePluginExporter implements ServerComponent {
       .setSeverity(toSeverityLevel(activeRule.getSeverity()));
   }
 
-  private Integer toSeverityLevel(RulePriority rulePriority) {
-    return rulePriority.ordinal();
+  private String toSeverityLevel(RulePriority rulePriority) {
+    return rulePriority.name();
   }
 
   private ActiveRuleParamDto toActiveRuleParamDto(ActiveRuleParam activeRuleParam, ActiveRuleDto activeRuleDto) {
index 2d5e79f957750982aa50755060ce7373c125502d..4f0b3c3bca538bb4bed8fa30061ba7f880201fb5 100644 (file)
  */
 package org.sonar.server.qualityprofile;
 
-import org.sonar.server.rule.ActiveRuleDocument;
-import org.sonar.server.rule.ProfileRuleQuery;
-import org.sonar.server.rule.RuleDocument;
-
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang.StringUtils;
@@ -39,6 +35,9 @@ import org.elasticsearch.search.sort.SortOrder;
 import org.sonar.api.ServerExtension;
 import org.sonar.api.rules.Rule;
 import org.sonar.server.es.ESIndex;
+import org.sonar.server.rule.ActiveRuleDocument;
+import org.sonar.server.rule.ProfileRuleQuery;
+import org.sonar.server.rule.RuleDocument;
 
 import javax.annotation.CheckForNull;
 
@@ -47,10 +46,14 @@ import java.util.List;
 import java.util.Map;
 
 import static com.google.common.collect.Lists.newArrayList;
-import static org.elasticsearch.index.query.FilterBuilders.*;
+import static org.elasticsearch.index.query.FilterBuilders.boolFilter;
+import static org.elasticsearch.index.query.FilterBuilders.hasChildFilter;
+import static org.elasticsearch.index.query.FilterBuilders.hasParentFilter;
+import static org.elasticsearch.index.query.FilterBuilders.queryFilter;
+import static org.elasticsearch.index.query.FilterBuilders.termFilter;
+import static org.elasticsearch.index.query.FilterBuilders.termsFilter;
 import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
 import static org.sonar.server.rule.RuleRegistry.INDEX_RULES;
-import static org.sonar.server.rule.RuleRegistry.TYPE_ACTIVE_RULE;
 import static org.sonar.server.rule.RuleRegistry.TYPE_RULE;
 
 public class QProfileRuleLookup implements ServerExtension {
@@ -68,7 +71,7 @@ public class QProfileRuleLookup implements ServerExtension {
 
   @CheckForNull
   public QProfileRule findByActiveRuleId(int activeRuleId) {
-    GetResponse activeRuleResponse = index.client().prepareGet(INDEX_RULES, TYPE_ACTIVE_RULE, Integer.toString(activeRuleId))
+    GetResponse activeRuleResponse = index.client().prepareGet(INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, Integer.toString(activeRuleId))
       .setFields(FIELD_SOURCE, FIELD_PARENT)
       .execute().actionGet();
     Map<String, Object> activeRuleSource = activeRuleResponse.getSourceAsMap();
@@ -111,7 +114,7 @@ public class QProfileRuleLookup implements ServerExtension {
   }
 
   public QProfileRuleResult search(ProfileRuleQuery query, Paging paging) {
-    SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(TYPE_ACTIVE_RULE, activeRuleFilter(query))));
+    SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, activeRuleFilter(query))));
     List<Integer> ruleIds = Lists.newArrayList();
     for (SearchHit ruleHit : ruleHits) {
       ruleIds.add(Integer.valueOf(ruleHit.id()));
@@ -144,7 +147,7 @@ public class QProfileRuleLookup implements ServerExtension {
       @Override
       public int search(int currentPage) {
         Paging paging = Paging.create(pageSize, currentPage);
-        SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(TYPE_ACTIVE_RULE, activeRuleFilter(query))));
+        SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, activeRuleFilter(query))));
         List<Integer> ruleIds = Lists.newArrayList();
         for (SearchHit ruleHit : ruleHits) {
           ruleIds.add(Integer.valueOf(ruleHit.id()));
@@ -166,7 +169,7 @@ public class QProfileRuleLookup implements ServerExtension {
     return index.executeCount(
       index.client()
         .prepareCount(INDEX_RULES)
-        .setTypes(TYPE_ACTIVE_RULE)
+        .setTypes(ESActiveRule.TYPE_ACTIVE_RULE)
         .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
           activeRuleFilter(query).must(hasParentFilter(TYPE_RULE, ruleFilterForActiveRuleSearch(query)))))
     );
@@ -218,7 +221,7 @@ public class QProfileRuleLookup implements ServerExtension {
   }
 
   private SearchHits searchActiveRules(ProfileRuleQuery query, List<Integer> ruleIds, String... fields) {
-    SearchRequestBuilder activeRuleBuilder = index.client().prepareSearch(INDEX_RULES).setTypes(TYPE_ACTIVE_RULE)
+    SearchRequestBuilder activeRuleBuilder = index.client().prepareSearch(INDEX_RULES).setTypes(ESActiveRule.TYPE_ACTIVE_RULE)
       .setPostFilter(boolFilter()
         .must(
           termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId()),
@@ -275,7 +278,7 @@ public class QProfileRuleLookup implements ServerExtension {
 
   private BoolFilterBuilder ruleFilterForInactiveRuleSearch(ProfileRuleQuery query) {
     BoolFilterBuilder filter = ruleFilterForActiveRuleSearch(query)
-      .mustNot(hasChildFilter(TYPE_ACTIVE_RULE, termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId())));
+      .mustNot(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId())));
     addMustTermOrTerms(filter, RuleDocument.FIELD_SEVERITY, query.severities());
 
     for (String tag: query.tags()) {
index 69c5202c4c4e1e3aa3a8b5cd352cd5327698de05..75e2fa7c06804ebdfc66c10dd8d68177dbd033bb 100644 (file)
@@ -29,7 +29,6 @@ import com.google.common.collect.Sets;
 import org.apache.commons.lang.StringUtils;
 import org.apache.ibatis.session.SqlSession;
 import org.sonar.api.ServerComponent;
-import org.sonar.api.rule.Severity;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.utils.System2;
 import org.sonar.check.Cardinality;
@@ -37,7 +36,12 @@ import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDao;
 import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.rule.*;
+import org.sonar.core.rule.RuleDao;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.core.rule.RuleRuleTagDto;
+import org.sonar.core.rule.RuleTagDao;
+import org.sonar.core.rule.RuleTagType;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.rule.RuleRegistry;
@@ -58,23 +62,25 @@ public class QProfileRuleOperations implements ServerComponent {
   private final RuleDao ruleDao;
   private final RuleTagDao ruleTagDao;
   private final RuleTagOperations ruleTagOperations;
+  private final ESActiveRule esActiveRule;
   private final RuleRegistry ruleRegistry;
 
   private final System2 system;
 
   public QProfileRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, RuleTagDao ruleTagDao, RuleTagOperations ruleTagOperations,
-    RuleRegistry ruleRegistry) {
-    this(myBatis, activeRuleDao, ruleDao, ruleTagDao, ruleTagOperations, ruleRegistry, System2.INSTANCE);
+    ESActiveRule esActiveRule, RuleRegistry ruleRegistry) {
+    this(myBatis, activeRuleDao, ruleDao, ruleTagDao, ruleTagOperations, esActiveRule, ruleRegistry, System2.INSTANCE);
   }
 
   @VisibleForTesting
-  QProfileRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, RuleTagDao ruleTagDao, RuleTagOperations ruleTagOperations, RuleRegistry ruleRegistry,
-    System2 system) {
+  QProfileRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, RuleTagDao ruleTagDao, RuleTagOperations ruleTagOperations, ESActiveRule esActiveRule,
+    RuleRegistry ruleRegistry, System2 system) {
     this.myBatis = myBatis;
     this.activeRuleDao = activeRuleDao;
     this.ruleDao = ruleDao;
     this.ruleTagDao = ruleTagDao;
     this.ruleTagOperations = ruleTagOperations;
+    this.esActiveRule = esActiveRule;
     this.ruleRegistry = ruleRegistry;
     this.system = system;
   }
@@ -127,7 +133,7 @@ public class QProfileRuleOperations implements ServerComponent {
         .setParentId(templateRule.getId())
         .setName(name)
         .setDescription(description)
-        .setSeverity(getSeverityOrdinal(severity))
+        .setSeverity(severity)
         .setRepositoryKey(templateRule.getRepositoryKey())
         .setConfigKey(templateRule.getConfigKey())
         .setRuleKey(templateRule.getRuleKey() + "_" + system.now())
@@ -181,7 +187,7 @@ public class QProfileRuleOperations implements ServerComponent {
     try {
       rule.setName(name)
         .setDescription(description)
-        .setSeverity(getSeverityOrdinal(severity))
+        .setSeverity(severity)
         .setUpdatedAt(new Date(system.now()));
       ruleDao.update(rule, session);
 
@@ -217,7 +223,7 @@ public class QProfileRuleOperations implements ServerComponent {
       }
       activeRuleDao.deleteFromRule(rule.getId(), session);
       session.commit();
-      ruleRegistry.deleteActiveRules(newArrayList(Iterables.transform(activeRules, new Function<ActiveRuleDto, Integer>() {
+      esActiveRule.deleteActiveRules(newArrayList(Iterables.transform(activeRules, new Function<ActiveRuleDto, Integer>() {
         @Override
         public Integer apply(ActiveRuleDto input) {
           return input.getId();
@@ -312,8 +318,4 @@ public class QProfileRuleOperations implements ServerComponent {
     }
     return login;
   }
-
-  private static int getSeverityOrdinal(String severity) {
-    return Severity.ALL.indexOf(severity);
-  }
 }
index d8712a9a95867894f6fa984c06fee86cba07858d..361263858e5f63d98afe070b70cdd1d0e8b75762 100644 (file)
  */
 package org.sonar.server.rule;
 
-import com.google.common.collect.*;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Sets;
 import org.apache.commons.lang.ObjectUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.ibatis.session.SqlSession;
@@ -35,12 +40,22 @@ import org.sonar.api.utils.TimeProfiler;
 import org.sonar.check.Cardinality;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDao;
-import org.sonar.core.rule.*;
+import org.sonar.core.rule.RuleDao;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.core.rule.RuleRuleTagDto;
+import org.sonar.core.rule.RuleTagDao;
+import org.sonar.core.rule.RuleTagDto;
+import org.sonar.core.rule.RuleTagType;
 import org.sonar.server.configuration.ProfilesManager;
 
 import javax.annotation.CheckForNull;
 
-import java.util.*;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 /**
  * Register rules at server startup
@@ -155,7 +170,7 @@ public class RuleRegistration implements Startable {
         .setName(ruleDef.name())
         .setRepositoryKey(ruleDef.repository().key())
         .setRuleKey(ruleDef.key())
-        .setSeverity(RulePriority.valueOf(ruleDef.defaultSeverity()).ordinal())
+        .setSeverity(RulePriority.valueOf(ruleDef.defaultSeverity()).name())
         .setCreatedAt(buffer.now())
         .setUpdatedAt(buffer.now())
         .setStatus(ruleDef.status().name());
@@ -199,8 +214,8 @@ public class RuleRegistration implements Startable {
       dto.setConfigKey(def.metadata());
       changed = true;
     }
-    int severity = RulePriority.valueOf(def.defaultSeverity()).ordinal();
-    if (!ObjectUtils.equals(dto.getSeverity(), severity)) {
+    String severity = RulePriority.valueOf(def.defaultSeverity()).name();
+    if (!ObjectUtils.equals(dto.getSeverityString(), severity)) {
       dto.setSeverity(severity);
       changed = true;
     }
index 18f445a5bfe2712fee87abcaf7841bc4269df135..a93b15025b08148f9abc1fac307165231a757667 100644 (file)
 
 package org.sonar.server.rule;
 
-import com.google.common.base.Function;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Iterables;
 import com.google.common.collect.Multimap;
-import org.apache.ibatis.session.SqlSession;
 import org.elasticsearch.ElasticSearchException;
 import org.elasticsearch.common.collect.Lists;
 import org.elasticsearch.common.collect.Maps;
 import org.elasticsearch.common.io.BytesStream;
 import org.elasticsearch.common.xcontent.XContentBuilder;
 import org.elasticsearch.common.xcontent.XContentFactory;
-import org.elasticsearch.index.query.FilterBuilders;
-import org.elasticsearch.index.query.QueryBuilders;
-import org.sonar.api.rule.Severity;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.utils.TimeProfiler;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.qualityprofile.db.ActiveRuleDao;
-import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
-import org.sonar.core.rule.*;
+import org.sonar.core.rule.RuleDao;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.core.rule.RuleRuleTagDto;
+import org.sonar.core.rule.RuleTagType;
 import org.sonar.server.es.ESIndex;
 import org.sonar.server.es.SearchQuery;
 
@@ -61,26 +54,19 @@ public class RuleRegistry {
 
   public static final String INDEX_RULES = "rules";
   public static final String TYPE_RULE = "rule";
-  public static final String TYPE_ACTIVE_RULE = "active_rule";
-
   private static final String PARAM_NAMEORKEY = "nameOrKey";
   private static final String PARAM_STATUS = "status";
 
   private final ESIndex searchIndex;
   private final RuleDao ruleDao;
-  private final ActiveRuleDao activeRuleDao;
-  private final MyBatis myBatis;
 
-  public RuleRegistry(ESIndex searchIndex, RuleDao ruleDao, ActiveRuleDao activeRuleDao, MyBatis myBatis) {
+  public RuleRegistry(ESIndex searchIndex, RuleDao ruleDao) {
     this.searchIndex = searchIndex;
     this.ruleDao = ruleDao;
-    this.activeRuleDao = activeRuleDao;
-    this.myBatis = myBatis;
   }
 
   public void start() {
     searchIndex.addMappingFromClasspath(INDEX_RULES, TYPE_RULE, "/org/sonar/server/es/config/mappings/rule_mapping.json");
-    searchIndex.addMappingFromClasspath(INDEX_RULES, TYPE_ACTIVE_RULE, "/org/sonar/server/es/config/mappings/active_rule_mapping.json");
   }
 
   public void bulkRegisterRules(Collection<RuleDto> rules, Multimap<Integer, RuleParamDto> paramsByRule, Multimap<Integer, RuleRuleTagDto> tagsByRule) {
@@ -88,28 +74,6 @@ public class RuleRegistry {
     removeDeletedRules(ids);
   }
 
-  public void bulkRegisterActiveRules() {
-    SqlSession session = myBatis.openSession();
-    try {
-      TimeProfiler profiler = new TimeProfiler();
-      profiler.start("Rebuilding active rules index - query");
-
-      List<ActiveRuleDto> activeRules = activeRuleDao.selectAll(session);
-      List<ActiveRuleParamDto> activeRuleParams = activeRuleDao.selectAllParams(session);
-      profiler.stop();
-
-      Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
-      for (ActiveRuleParamDto param : activeRuleParams) {
-        paramsByActiveRule.put(param.getActiveRuleId(), param);
-      }
-
-      String[] ids = bulkIndexActiveRules(activeRules, paramsByActiveRule);
-      removeDeletedActiveRules(ids);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   /**
    * <p>Find rule IDs matching the given criteria.</p>
    *
@@ -170,14 +134,6 @@ public class RuleRegistry {
     }
   }
 
-  public void save(ActiveRuleDto activeRule, Collection<ActiveRuleParamDto> params) {
-    try {
-      searchIndex.putSynchronous(INDEX_RULES, TYPE_ACTIVE_RULE, Long.toString(activeRule.getId()), activeRuleDocument(activeRule, params), Long.toString(activeRule.getRulId()));
-    } catch (IOException ioexception) {
-      throw new IllegalStateException("Unable to index active rule with id=" + activeRule.getId(), ioexception);
-    }
-  }
-
   private String[] bulkIndexRules(Collection<RuleDto> rules, Multimap<Integer, RuleParamDto> paramsByRule, Multimap<Integer, RuleRuleTagDto> tagsByRule) {
     try {
       String[] ids = new String[rules.size()];
@@ -214,96 +170,6 @@ public class RuleRegistry {
     }
   }
 
-  public void deleteActiveRules(List<Integer> activeRuleIds) {
-    List<String> indexIds = newArrayList();
-    for (Integer ruleId : activeRuleIds) {
-      indexIds.add(ruleId.toString());
-    }
-    bulkDeleteActiveRules(indexIds);
-  }
-
-  protected void bulkDeleteActiveRules(List<String> indexIds) {
-    if (!indexIds.isEmpty()) {
-      searchIndex.bulkDelete(INDEX_RULES, TYPE_ACTIVE_RULE, indexIds.toArray(new String[0]));
-    }
-  }
-
-  public void deleteActiveRulesFromProfile(int profileId) {
-    searchIndex.client().prepareDeleteByQuery(INDEX_RULES).setTypes(TYPE_ACTIVE_RULE)
-      .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
-        FilterBuilders.termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, profileId)))
-      .execute().actionGet();
-  }
-
-  public String[] bulkIndexActiveRules(List<ActiveRuleDto> activeRules, Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule) {
-    try {
-      int size = activeRules.size();
-      String[] ids = new String[size];
-      BytesStream[] docs = new BytesStream[size];
-      String[] parentIds = new String[size];
-      int index = 0;
-
-      TimeProfiler profiler = new TimeProfiler();
-      profiler.start("Build active rules documents");
-      for (ActiveRuleDto activeRule : activeRules) {
-        ids[index] = activeRule.getId().toString();
-        docs[index] = activeRuleDocument(activeRule, paramsByActiveRule.get(activeRule.getId()));
-        parentIds[index] = activeRule.getRulId().toString();
-        index++;
-      }
-      profiler.stop();
-
-      if (!activeRules.isEmpty()) {
-        profiler.start("Index active rules");
-        searchIndex.bulkIndex(INDEX_RULES, TYPE_ACTIVE_RULE, ids, docs, parentIds);
-        profiler.stop();
-      }
-      return ids;
-    } catch (IOException e) {
-      throw new IllegalStateException("Unable to index active rules", e);
-    }
-  }
-
-  public void bulkIndexProfile(int profileId, SqlSession session) {
-    bulkIndexActiveRules(activeRuleDao.selectByProfileId(profileId, session), session);
-  }
-
-  public void bulkIndexActiveRuleIds(List<Integer> activeRulesIds, SqlSession session) {
-    bulkIndexActiveRules(activeRuleDao.selectByIds(activeRulesIds, session), session);
-  }
-
-  private void bulkIndexActiveRules(List<ActiveRuleDto> activeRules, SqlSession session) {
-    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
-    List<Integer> activeRulesIdList = newArrayList(Iterables.transform(activeRules, new Function<ActiveRuleDto, Integer>() {
-      @Override
-      public Integer apply(ActiveRuleDto input) {
-        return input.getId();
-      }
-    }));
-    for (ActiveRuleParamDto param : activeRuleDao.selectParamsByActiveRuleIds(activeRulesIdList, session)) {
-      paramsByActiveRule.put(param.getActiveRuleId(), param);
-    }
-    bulkIndexActiveRules(activeRules, paramsByActiveRule);
-  }
-
-  public void bulkIndexActiveRules(List<Integer> ids) {
-    SqlSession session = myBatis.openSession();
-    try {
-      bulkIndexActiveRuleIds(ids, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  private void removeDeletedActiveRules(String[] ids) {
-    TimeProfiler profiler = new TimeProfiler();
-    List<String> indexIds = searchIndex.findDocumentIds(SearchQuery.create().index(INDEX_RULES).type(TYPE_ACTIVE_RULE));
-    indexIds.removeAll(newArrayList(ids));
-    profiler.start("Remove deleted active rule documents");
-    bulkDeleteActiveRules(indexIds);
-    profiler.stop();
-  }
-
   private XContentBuilder ruleDocument(RuleDto rule, Collection<RuleParamDto> params, Collection<RuleRuleTagDto> tags) throws IOException {
     XContentBuilder document = XContentFactory.jsonBuilder()
       .startObject()
@@ -314,7 +180,7 @@ public class RuleRegistry {
       .field(RuleDocument.FIELD_DESCRIPTION, rule.getDescription())
       .field(RuleDocument.FIELD_TEMPLATE_ID, rule.getParentId() == null ? null : rule.getParentId())
       .field(RuleDocument.FIELD_REPOSITORY_KEY, rule.getRepositoryKey())
-      .field(RuleDocument.FIELD_SEVERITY, getSeverityFromOrdinal(rule.getSeverity()))
+      .field(RuleDocument.FIELD_SEVERITY, rule.getSeverityString())
       .field(RuleDocument.FIELD_STATUS, rule.getStatus())
       .field(RuleDocument.FIELD_CARDINALITY, rule.getCardinality())
       .field(RuleDocument.FIELD_CREATED_AT, rule.getCreatedAt())
@@ -359,39 +225,4 @@ public class RuleRegistry {
     document.endObject();
     return document;
   }
-
-  private XContentBuilder activeRuleDocument(ActiveRuleDto activeRule, Collection<ActiveRuleParamDto> params) throws IOException {
-    XContentBuilder document = XContentFactory.jsonBuilder()
-      .startObject()
-      .field(ActiveRuleDocument.FIELD_ID, activeRule.getId())
-      .field(ActiveRuleDocument.FIELD_ACTIVE_RULE_PARENT_ID, activeRule.getParentId())
-      .field(ActiveRuleDocument.FIELD_SEVERITY, getSeverityFromOrdinal(activeRule.getSeverity()))
-      .field(ActiveRuleDocument.FIELD_PROFILE_ID, activeRule.getProfileId())
-      .field(ActiveRuleDocument.FIELD_INHERITANCE, activeRule.getInheritance());
-    if (activeRule.getNoteData() != null || activeRule.getNoteUserLogin() != null) {
-      document.startObject(RuleDocument.FIELD_NOTE)
-        .field(ActiveRuleDocument.FIELD_NOTE_DATA, activeRule.getNoteData())
-        .field(ActiveRuleDocument.FIELD_NOTE_USER_LOGIN, activeRule.getNoteUserLogin())
-        .field(ActiveRuleDocument.FIELD_NOTE_CREATED_AT, activeRule.getNoteCreatedAt())
-        .field(ActiveRuleDocument.FIELD_NOTE_UPDATED_AT, activeRule.getNoteUpdatedAt())
-        .endObject();
-    }
-    if (!params.isEmpty()) {
-      document.startArray(ActiveRuleDocument.FIELD_PARAMS);
-      for (ActiveRuleParamDto param : params) {
-        document.startObject()
-          .field(ActiveRuleDocument.FIELD_PARAM_KEY, param.getKey())
-          .field(ActiveRuleDocument.FIELD_PARAM_VALUE, param.getValue())
-          .endObject();
-      }
-      document.endArray();
-    }
-    document.endObject();
-    return document;
-  }
-
-  private static String getSeverityFromOrdinal(int ordinal) {
-    return Severity.ALL.get(ordinal);
-  }
-
 }
index 3f28d90a22633d7678e25abd21c12b6c5e9fc30e..256ecf53f255962b8270b350f740db2bb1b9af2d 100644 (file)
@@ -30,7 +30,11 @@ import org.slf4j.LoggerFactory;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.profiles.ProfileDefinition;
 import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.*;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleFinder;
+import org.sonar.api.rules.RuleParam;
+import org.sonar.api.rules.RuleQuery;
 import org.sonar.api.utils.SonarException;
 import org.sonar.api.utils.TimeProfiler;
 import org.sonar.api.utils.ValidationMessages;
@@ -38,10 +42,14 @@ import org.sonar.core.template.LoadedTemplateDao;
 import org.sonar.core.template.LoadedTemplateDto;
 import org.sonar.jpa.session.DatabaseSessionFactory;
 import org.sonar.server.platform.PersistentSettings;
+import org.sonar.server.qualityprofile.ESActiveRule;
 import org.sonar.server.rule.RuleRegistration;
-import org.sonar.server.rule.RuleRegistry;
 
-import java.util.*;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 public class RegisterNewProfiles {
 
@@ -51,7 +59,7 @@ public class RegisterNewProfiles {
   private final List<ProfileDefinition> definitions;
   private final LoadedTemplateDao loadedTemplateDao;
   private final RuleFinder ruleFinder;
-  private final RuleRegistry ruleRegistry;
+  private final ESActiveRule esActiveRule;
   private final DatabaseSessionFactory sessionFactory;
   private final PersistentSettings settings;
   private DatabaseSession session = null;
@@ -59,13 +67,13 @@ public class RegisterNewProfiles {
   public RegisterNewProfiles(List<ProfileDefinition> definitions,
                              PersistentSettings settings,
                              RuleFinder ruleFinder,
-                             RuleRegistry ruleRegistry,
+                             ESActiveRule esActiveRule,
                              LoadedTemplateDao loadedTemplateDao,
                              DatabaseSessionFactory sessionFactory,
                              RuleRegistration registerRulesBefore) {
     this.settings = settings;
     this.ruleFinder = ruleFinder;
-    this.ruleRegistry = ruleRegistry;
+    this.esActiveRule = esActiveRule;
     this.definitions = definitions;
     this.loadedTemplateDao = loadedTemplateDao;
     this.sessionFactory = sessionFactory;
@@ -73,11 +81,11 @@ public class RegisterNewProfiles {
 
   public RegisterNewProfiles(PersistentSettings settings,
                              RuleFinder ruleFinder,
-                             RuleRegistry ruleRegistry,
+                             ESActiveRule esActiveRule,
                              LoadedTemplateDao loadedTemplateDao,
                              DatabaseSessionFactory sessionFactory,
                              RuleRegistration registerRulesBefore) {
-    this(Collections.<ProfileDefinition>emptyList(), settings, ruleFinder, ruleRegistry, loadedTemplateDao, sessionFactory, registerRulesBefore);
+    this(Collections.<ProfileDefinition>emptyList(), settings, ruleFinder, esActiveRule, loadedTemplateDao, sessionFactory, registerRulesBefore);
   }
 
   public void start() {
@@ -100,7 +108,7 @@ public class RegisterNewProfiles {
     session.commit();
     profiler.stop();
 
-    ruleRegistry.bulkRegisterActiveRules();
+    esActiveRule.bulkRegisterActiveRules();
   }
 
   private void setDefault(String language, List<RulesProfile> profiles) {
diff --git a/sonar-server/src/test/java/org/sonar/server/qualityprofile/ESActiveRuleTest.java b/sonar-server/src/test/java/org/sonar/server/qualityprofile/ESActiveRuleTest.java
new file mode 100644 (file)
index 0000000..999306d
--- /dev/null
@@ -0,0 +1,203 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with 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 org.sonar.server.rule.RuleRegistry;
+
+import com.github.tlrx.elasticsearch.test.EsSetup;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
+import org.apache.commons.io.IOUtils;
+import org.apache.ibatis.session.SqlSession;
+import org.elasticsearch.client.Requests;
+import org.elasticsearch.common.settings.ImmutableSettings;
+import org.elasticsearch.search.SearchHit;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.sonar.api.config.Settings;
+import org.sonar.api.rule.Severity;
+import org.sonar.core.persistence.MyBatis;
+import org.sonar.core.profiling.Profiling;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.server.es.ESIndex;
+import org.sonar.server.es.ESNode;
+import org.sonar.test.TestUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+import static org.elasticsearch.index.query.FilterBuilders.hasChildFilter;
+import static org.elasticsearch.index.query.FilterBuilders.hasParentFilter;
+import static org.elasticsearch.index.query.FilterBuilders.termFilter;
+import static org.fest.assertions.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ESActiveRuleTest {
+
+  EsSetup esSetup;
+
+  ESIndex searchIndex;
+
+  ESActiveRule esActiveRule;
+
+  @Mock
+  MyBatis myBatis;
+
+  @Mock
+  SqlSession session;
+
+  @Mock
+  ActiveRuleDao activeRuleDao;
+
+  @Before
+  public void setUp() throws Exception {
+    when(myBatis.openSession()).thenReturn(session);
+
+    esSetup = new EsSetup(ImmutableSettings.builder().loadFromUrl(ESNode.class.getResource("config/elasticsearch.json")).build());
+    esSetup.execute(EsSetup.deleteAll());
+
+    ESNode node = mock(ESNode.class);
+    when(node.client()).thenReturn(esSetup.client());
+
+    Settings settings = new Settings();
+    settings.setProperty("sonar.log.profilingLevel", "FULL");
+    Profiling profiling = new Profiling(settings);
+    searchIndex = new ESIndex(node, profiling);
+    searchIndex.start();
+
+    RuleRegistry esRule = new RuleRegistry(searchIndex, null);
+    esRule.start();
+    esActiveRule = new ESActiveRule(searchIndex, activeRuleDao, myBatis);
+    esActiveRule.start();
+
+    esSetup.execute(
+      EsSetup.index("rules", "rule", "1").withSource(testFileAsString("shared/rule1.json")),
+      EsSetup.index("rules", "rule", "2").withSource(testFileAsString("shared/rule2.json")),
+      EsSetup.index("rules", "rule", "3").withSource(testFileAsString("shared/rule3.json"))
+    );
+  }
+
+  @Test
+  public void should_register_mapping_at_startup() {
+    assertThat(esSetup.exists("rules")).isTrue();
+    assertThat(esSetup.client().admin().indices().prepareTypesExists("rules").setTypes("rule").execute().actionGet().isExists()).isTrue();
+  }
+
+
+  @Test
+  public void bulk_index_active_rules() throws IOException {
+    List<ActiveRuleDto> activeRules = newArrayList(new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(Severity.MAJOR).setParentId(5));
+    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
+    paramsByActiveRule.putAll(1, newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters")));
+
+    esActiveRule.bulkIndexActiveRules(activeRules, paramsByActiveRule);
+    assertThat(esSetup.exists("rules", "active_rule", "1"));
+
+    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasChildFilter("active_rule", termFilter("profileId", 10))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(parentHit).hasSize(1);
+    assertThat(parentHit[0].getId()).isEqualTo("1");
+
+    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(childHit).hasSize(1);
+    assertThat(childHit[0].getId()).isEqualTo("1");
+  }
+
+  @Test
+  public void bulk_index_active_rules_from_ids() throws IOException {
+    when(myBatis.openSession()).thenReturn(session);
+
+    List<Integer> ids = newArrayList(1);
+    when(activeRuleDao.selectByIds(ids, session)).thenReturn(
+      newArrayList(new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(Severity.MAJOR).setParentId(5)));
+    when(activeRuleDao.selectParamsByActiveRuleIds(ids, session)).thenReturn(
+      newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters")));
+
+    esActiveRule.bulkIndexActiveRules(ids);
+    assertThat(esSetup.exists("rules", "active_rule", "1"));
+
+    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasChildFilter("active_rule", termFilter("profileId", 10))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(parentHit).hasSize(1);
+    assertThat(parentHit[0].getId()).isEqualTo("1");
+
+    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(childHit).hasSize(1);
+    assertThat(childHit[0].getId()).isEqualTo("1");
+  }
+
+  @Test
+  public void save_active_rule() throws IOException {
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(Severity.MAJOR);
+    ArrayList<ActiveRuleParamDto> params = newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters"));
+
+    esActiveRule.save(activeRule, params);
+    assertThat(esSetup.exists("rules", "active_rule", "1"));
+
+    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasChildFilter("active_rule", termFilter("profileId", 10))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(parentHit).hasSize(1);
+    assertThat(parentHit[0].getId()).isEqualTo("1");
+
+    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
+      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
+    ).execute().actionGet().getHits().getHits();
+    assertThat(childHit).hasSize(1);
+    assertThat(childHit[0].getId()).isEqualTo("1");
+  }
+
+  @Test
+  public void delete_active_rules_from_profile() throws Exception {
+    esSetup.client().prepareBulk()
+      // On profile 1
+      .add(Requests.indexRequest().index("rules").type("active_rule").parent("1").source(testFileAsString("delete_from_profile/active_rule25.json")))
+      .add(Requests.indexRequest().index("rules").type("active_rule").parent("3").source(testFileAsString("delete_from_profile/active_rule2702.json")))
+        // On profile 2
+      .add(Requests.indexRequest().index("rules").type("active_rule").parent("2").source(testFileAsString("delete_from_profile/active_rule523.json")))
+      .setRefresh(true)
+      .execute().actionGet();
+
+    esActiveRule.deleteActiveRulesFromProfile(1);
+    assertThat(!esSetup.exists("rules", "active_rule", "25"));
+    assertThat(!esSetup.exists("rules", "active_rule", "2702"));
+    assertThat(esSetup.exists("rules", "active_rule", "523"));
+  }
+
+  private String testFileAsString(String testFile) throws Exception {
+    return IOUtils.toString(TestUtils.getResource(getClass(), testFile).toURI());
+  }
+
+}
index 1bb56618b8d226a502eab8d8253ebfe22812b245..a2d5f6dd452e46fcde4ee6b7683be012fb09bdbb 100644 (file)
@@ -37,14 +37,17 @@ import org.sonar.api.utils.DateUtils;
 import org.sonar.api.utils.System2;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
 import org.sonar.core.rule.RuleDao;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleParamDto;
 import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.MockUserSession;
 import org.sonar.server.user.UserSession;
 import org.sonar.server.util.TypeValidations;
@@ -57,10 +60,17 @@ import static org.fest.assertions.Assertions.assertThat;
 import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyList;
+import static org.mockito.Matchers.anyListOf;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.anyList;
-import static org.mockito.Mockito.anyListOf;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class QProfileActiveRuleOperationsTest {
@@ -81,7 +91,7 @@ public class QProfileActiveRuleOperationsTest {
   QualityProfileDao profileDao;
 
   @Mock
-  RuleRegistry ruleRegistry;
+  ESActiveRule esActiveRule;
 
   @Mock
   ProfilesManager profilesManager;
@@ -113,7 +123,7 @@ public class QProfileActiveRuleOperationsTest {
       }
     }).when(activeRuleDao).insert(any(ActiveRuleDto.class), any(SqlSession.class));
 
-    operations = new QProfileActiveRuleOperations(myBatis, activeRuleDao, ruleDao, profileDao, ruleRegistry, profilesManager, typeValidations, system);
+    operations = new QProfileActiveRuleOperations(myBatis, activeRuleDao, ruleDao, profileDao, esActiveRule, profilesManager, typeValidations, system);
   }
 
   @Test
@@ -147,7 +157,7 @@ public class QProfileActiveRuleOperationsTest {
     ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
     verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
     assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
-    assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(3);
+    assertThat(activeRuleArgument.getValue().getSeverityString()).isEqualTo(Severity.CRITICAL);
 
     ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
     verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
@@ -156,15 +166,15 @@ public class QProfileActiveRuleOperationsTest {
 
     verify(session).commit();
     verify(profilesManager).activated(eq(1), anyInt(), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(eq(newArrayList(idActiveRuleToDelete)));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(eq(newArrayList(idActiveRuleToUpdate)), eq(session));
+    verify(esActiveRule).deleteActiveRules(eq(newArrayList(idActiveRuleToDelete)));
+    verify(esActiveRule).bulkIndexActiveRuleIds(eq(newArrayList(idActiveRuleToUpdate)), eq(session));
   }
 
   @Test
   public void update_severity() throws Exception {
     when(profileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));
     when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10));
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectByProfileAndRule(1, 10, session)).thenReturn(activeRule);
 
     when(profilesManager.ruleSeverityChanged(eq(1), eq(5), eq(RulePriority.MINOR), eq(RulePriority.MAJOR), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
@@ -174,15 +184,15 @@ public class QProfileActiveRuleOperationsTest {
     verify(activeRuleDao).update(eq(activeRule), eq(session));
     verify(session).commit();
     verify(profilesManager).ruleSeverityChanged(eq(1), eq(5), eq(RulePriority.MINOR), eq(RulePriority.MAJOR), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void fail_to_update_severity_on_invalid_severity() throws Exception {
     when(profileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));
     when(ruleDao.selectById(10)).thenReturn(new RuleDto().setId(10));
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectByProfileAndRule(1, 10)).thenReturn(activeRule);
 
     try {
@@ -198,7 +208,7 @@ public class QProfileActiveRuleOperationsTest {
   @Test
   public void activate_rules() throws Exception {
     when(profileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));
-    when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10).setSeverity(3));
+    when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10).setSeverity(Severity.CRITICAL));
 
     when(ruleDao.selectParameters(eq(10), eq(session))).thenReturn(newArrayList(new RuleParamDto().setId(20).setName("max").setDefaultValue("10")));
     final int idActiveRuleToUpdate = 42;
@@ -213,7 +223,7 @@ public class QProfileActiveRuleOperationsTest {
     ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
     verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
     assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
-    assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(3);
+    assertThat(activeRuleArgument.getValue().getSeverityString()).isEqualTo(Severity.CRITICAL);
 
     ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
     verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
@@ -222,15 +232,15 @@ public class QProfileActiveRuleOperationsTest {
 
     verify(session).commit();
     verify(profilesManager).activated(eq(1), anyInt(), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(eq(newArrayList(idActiveRuleToDelete)));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(eq(newArrayList(idActiveRuleToUpdate)), eq(session));
+    verify(esActiveRule).deleteActiveRules(eq(newArrayList(idActiveRuleToDelete)));
+    verify(esActiveRule).bulkIndexActiveRuleIds(eq(newArrayList(idActiveRuleToUpdate)), eq(session));
   }
 
   @Test
   public void deactivate_rule() throws Exception {
     when(profileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));
     when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10));
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectByProfileAndRule(1, 10, session)).thenReturn(activeRule);
     when(profilesManager.deactivated(eq(1), anyInt(), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
 
@@ -241,15 +251,15 @@ public class QProfileActiveRuleOperationsTest {
     verify(activeRuleDao).deleteParameters(eq(5), eq(session));
     verify(session).commit();
     verify(profilesManager).deactivated(eq(1), anyInt(), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void not_deactivate_rule_if_inheritance() throws Exception {
     when(profileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));
     when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10));
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.INHERITED);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.INHERITED);
     when(activeRuleDao.selectByProfileAndRule(1, 10, session)).thenReturn(activeRule);
     when(profilesManager.deactivated(eq(1), anyInt(), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
 
@@ -260,13 +270,13 @@ public class QProfileActiveRuleOperationsTest {
     verify(activeRuleDao, never()).deleteParameters(anyInt(), eq(session));
     verify(session, never()).commit();
     verifyZeroInteractions(profilesManager);
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
   }
 
   @Test
   public void deactivate_rules() throws Exception {
     when(ruleDao.selectById(10, session)).thenReturn(new RuleDto().setId(10));
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     when(profilesManager.deactivated(eq(1), anyInt(), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
 
@@ -277,13 +287,13 @@ public class QProfileActiveRuleOperationsTest {
     verify(activeRuleDao).deleteParameters(eq(5), eq(session));
     verify(session).commit();
     verify(profilesManager).deactivated(eq(1), anyInt(), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void create_active_rule_param() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     RuleParamDto ruleParam = new RuleParamDto().setRuleId(10).setName("max").setDefaultValue("20").setType(PropertyType.INTEGER.name());
     when(ruleDao.selectParamByRuleAndKey(10, "max", session)).thenReturn(ruleParam);
@@ -300,13 +310,13 @@ public class QProfileActiveRuleOperationsTest {
     verify(typeValidations).validate(eq("30"), eq("INTEGER"), anyList());
     verify(session).commit();
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("max"), eq((String) null), eq("30"), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void fail_to_create_active_rule_if_no_rule_param() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     when(ruleDao.selectParamByRuleAndKey(10, "max", session)).thenReturn(null);
 
@@ -322,7 +332,7 @@ public class QProfileActiveRuleOperationsTest {
 
   @Test
   public void update_active_rule_param() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     RuleParamDto ruleParam = new RuleParamDto().setRuleId(10).setName("max").setDefaultValue("20").setType(PropertyType.INTEGER.name());
     when(ruleDao.selectParamByRuleAndKey(10, "max", session)).thenReturn(ruleParam);
@@ -341,13 +351,13 @@ public class QProfileActiveRuleOperationsTest {
     verify(typeValidations).validate(eq("30"), eq("INTEGER"), anyList());
     verify(session).commit();
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("max"), eq("20"), eq("30"), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void update_active_rule_param_with_single_select_list_type() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     RuleParamDto ruleParam = new RuleParamDto().setRuleId(10).setName("max").setDefaultValue("20").setType(RuleParamType.multipleListOfValues("30", "31", "32", "33").toString());
     when(ruleDao.selectParamByRuleAndKey(10, "max", session)).thenReturn(ruleParam);
@@ -362,7 +372,7 @@ public class QProfileActiveRuleOperationsTest {
 
   @Test
   public void remove_active_rule_param() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     RuleParamDto ruleParam = new RuleParamDto().setRuleId(10).setName("max").setDefaultValue("20").setType(PropertyType.INTEGER.name());
     when(ruleDao.selectParamByRuleAndKey(10, "max", session)).thenReturn(ruleParam);
@@ -376,15 +386,15 @@ public class QProfileActiveRuleOperationsTest {
     verify(session).commit();
     verify(activeRuleDao).deleteParameter(100, session);
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("max"), eq("20"), eq((String) null), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
   public void revert_active_rule_with_severity_to_update() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
-    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(2);
+    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(Severity.MAJOR);
     when(activeRuleDao.selectById(4, session)).thenReturn(parent);
 
     when(profilesManager.ruleSeverityChanged(eq(1), eq(5), eq(RulePriority.MINOR), eq(RulePriority.MAJOR), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
@@ -394,19 +404,19 @@ public class QProfileActiveRuleOperationsTest {
     ArgumentCaptor<ActiveRuleDto> argumentCaptor = ArgumentCaptor.forClass(ActiveRuleDto.class);
     verify(activeRuleDao, times(2)).update(argumentCaptor.capture(), eq(session));
     List<ActiveRuleDto> activeRulesChanged = argumentCaptor.getAllValues();
-    assertThat(activeRulesChanged.get(0).getSeverity()).isEqualTo(2);
+    assertThat(activeRulesChanged.get(0).getSeverityString()).isEqualTo(Severity.MAJOR);
     assertThat(activeRulesChanged.get(1).getInheritance()).isEqualTo(ActiveRuleDto.INHERITED);
 
     verify(session, times(2)).commit();
     verify(profilesManager).ruleSeverityChanged(eq(1), eq(5), eq(RulePriority.MINOR), eq(RulePriority.MAJOR), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
-    verify(ruleRegistry).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
   }
 
   @Test
   public void fail_to_revert_active_rule_if_no_parent() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     when(activeRuleDao.selectById(4, session)).thenReturn(null);
 
@@ -420,13 +430,13 @@ public class QProfileActiveRuleOperationsTest {
 
   @Test
   public void revert_active_rule_with_param_to_update() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     when(activeRuleDao.selectParamsByActiveRuleId(eq(5), eq(session))).thenReturn(newArrayList(
       new ActiveRuleParamDto().setId(102).setActiveRuleId(5).setKey("max").setValue("20")
     ));
 
-    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(4, session)).thenReturn(parent);
     when(activeRuleDao.selectParamsByActiveRuleId(eq(4), eq(session))).thenReturn(newArrayList(
       new ActiveRuleParamDto().setId(100).setActiveRuleId(5).setKey("max").setValue("15")
@@ -448,20 +458,20 @@ public class QProfileActiveRuleOperationsTest {
 
     verify(session, times(2)).commit();
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("max"), eq("20"), eq("15"), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
-    verify(ruleRegistry).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
   }
 
   @Test
   public void revert_active_rule_with_param_to_delete() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
     when(activeRuleDao.selectParamsByActiveRuleId(eq(5), eq(session))).thenReturn(newArrayList(
       new ActiveRuleParamDto().setId(103).setActiveRuleId(5).setKey("format").setValue("abc"))
     );
 
-    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(4, session)).thenReturn(parent);
 
     when(profilesManager.ruleParamChanged(eq(1), eq(5), eq("format"), eq("abc"), eq((String) null), eq("Nicolas"))).thenReturn(new ProfilesManager.RuleInheritanceActions());
@@ -476,17 +486,17 @@ public class QProfileActiveRuleOperationsTest {
 
     verify(session, times(2)).commit();
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("format"), eq("abc"), eq((String) null), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
-    verify(ruleRegistry).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
   }
 
   @Test
   public void revert_active_rule_with_param_to_create() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(ActiveRuleDto.OVERRIDES).setParentId(4);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
 
-    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(1);
+    ActiveRuleDto parent = new ActiveRuleDto().setId(4).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectById(4, session)).thenReturn(parent);
     when(activeRuleDao.selectParamsByActiveRuleId(eq(4), eq(session))).thenReturn(newArrayList(
       new ActiveRuleParamDto().setId(101).setActiveRuleId(5).setKey("minimum").setValue("2"))
@@ -507,14 +517,14 @@ public class QProfileActiveRuleOperationsTest {
 
     verify(session, times(2)).commit();
     verify(profilesManager).ruleParamChanged(eq(1), eq(5), eq("minimum"), eq((String) null), eq("2"), eq("Nicolas"));
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
-    verify(ruleRegistry).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).save(eq(activeRule), anyListOf(ActiveRuleParamDto.class));
   }
 
   @Test
   public void no_revert_when_active_rule_do_not_override() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setInheritance(null);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setInheritance(null);
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
 
     when(activeRuleDao.selectById(5, session)).thenReturn(activeRule);
@@ -522,12 +532,12 @@ public class QProfileActiveRuleOperationsTest {
     verifyZeroInteractions(activeRuleDao);
     verifyZeroInteractions(session);
     verifyZeroInteractions(profilesManager);
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
   }
 
   @Test
   public void update_active_rule_note_when_no_existing_note() throws Exception {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1).setNoteCreatedAt(null).setNoteData(null);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR).setNoteCreatedAt(null).setNoteData(null);
 
     List<ActiveRuleParamDto> activeRuleParams = newArrayList(new ActiveRuleParamDto());
     when(activeRuleDao.selectParamsByActiveRuleId(eq(5), eq(session))).thenReturn(activeRuleParams);
@@ -545,13 +555,13 @@ public class QProfileActiveRuleOperationsTest {
     assertThat(argumentCaptor.getValue().getNoteUpdatedAt().getTime()).isEqualTo(now);
 
     verify(session).commit();
-    verify(ruleRegistry).save(eq(activeRule), eq(activeRuleParams));
+    verify(esActiveRule).save(eq(activeRule), eq(activeRuleParams));
   }
 
   @Test
   public void update_active_rule_note_when_already_note() throws Exception {
     Date createdAt = DateUtils.parseDate("2013-12-20");
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1)
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR)
       .setNoteCreatedAt(createdAt).setNoteData("My previous note").setNoteUserLogin("nicolas");
 
     List<ActiveRuleParamDto> activeRuleParams = newArrayList(new ActiveRuleParamDto());
@@ -570,13 +580,13 @@ public class QProfileActiveRuleOperationsTest {
     assertThat(argumentCaptor.getValue().getNoteUpdatedAt().getTime()).isEqualTo(now);
 
     verify(session).commit();
-    verify(ruleRegistry).save(eq(activeRule), eq(activeRuleParams));
+    verify(esActiveRule).save(eq(activeRule), eq(activeRuleParams));
   }
 
   @Test
   public void delete_active_rule_note() throws Exception {
     Date createdAt = DateUtils.parseDate("2013-12-20");
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(1)
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(5).setProfileId(1).setRuleId(10).setSeverity(Severity.MINOR)
       .setNoteData("My note").setNoteUserLogin("nicolas").setNoteCreatedAt(createdAt).setNoteUpdatedAt(createdAt);
 
     List<ActiveRuleParamDto> activeRuleParams = newArrayList(new ActiveRuleParamDto());
@@ -595,7 +605,7 @@ public class QProfileActiveRuleOperationsTest {
     assertThat(argumentCaptor.getValue().getNoteUpdatedAt()).isNull();
 
     verify(session).commit();
-    verify(ruleRegistry).save(eq(activeRule), eq(activeRuleParams));
+    verify(esActiveRule).save(eq(activeRule), eq(activeRuleParams));
   }
 
 }
index 6f8a7573d81a5e94c69727e2e11e3e64b608949d..908e2797ba187ddd0a08498460bfa50ab05224de 100644 (file)
@@ -39,7 +39,6 @@ import org.sonar.core.preview.PreviewCache;
 import org.sonar.jpa.session.DatabaseSessionFactory;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.MockUserSession;
 import org.sonar.server.user.UserSession;
 
@@ -51,7 +50,12 @@ import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class QProfileBackupTest {
@@ -78,7 +82,7 @@ public class QProfileBackupTest {
   QProfileLookup qProfileLookup;
 
   @Mock
-  RuleRegistry ruleRegistry;
+  ESActiveRule esActiveRule;
 
   @Mock
   PreviewCache dryRunCache;
@@ -92,7 +96,7 @@ public class QProfileBackupTest {
     when(myBatis.openSession()).thenReturn(session);
     when(sessionFactory.getSession()).thenReturn(hibernateSession);
 
-    backup = new QProfileBackup(sessionFactory, xmlProfileParser, xmlProfileSerializer, myBatis, qProfileLookup, ruleRegistry, dryRunCache);
+    backup = new QProfileBackup(sessionFactory, xmlProfileParser, xmlProfileSerializer, myBatis, qProfileLookup, esActiveRule, dryRunCache);
   }
 
   @Test
@@ -120,7 +124,7 @@ public class QProfileBackupTest {
 
     assertThat(result.profile()).isNotNull();
     verify(hibernateSession).saveWithoutFlush(profile);
-    verify(ruleRegistry).bulkIndexProfile(anyInt(), eq(session));
+    verify(esActiveRule).bulkIndexProfile(anyInt(), eq(session));
     verify(dryRunCache).reportGlobalModification(session);
     verify(session).commit();
   }
@@ -134,7 +138,7 @@ public class QProfileBackupTest {
       assertThat(e).isInstanceOf(ForbiddenException.class);
     }
     verify(hibernateSession, never()).saveWithoutFlush(any(RulesProfile.class));
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
     verifyZeroInteractions(dryRunCache);
   }
 
@@ -155,7 +159,7 @@ public class QProfileBackupTest {
     }
 
     verify(hibernateSession, never()).saveWithoutFlush(any(RulesProfile.class));
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
     verifyZeroInteractions(dryRunCache);
   }
 
@@ -176,8 +180,8 @@ public class QProfileBackupTest {
 
     assertThat(result.profile()).isNotNull();
     verify(hibernateSession).removeWithoutFlush(eq(existingProfile));
-    verify(ruleRegistry).deleteActiveRulesFromProfile(eq(1));
-    verify(ruleRegistry).bulkIndexProfile(anyInt(), eq(session));
+    verify(esActiveRule).deleteActiveRulesFromProfile(eq(1));
+    verify(esActiveRule).bulkIndexProfile(anyInt(), eq(session));
     verify(dryRunCache).reportGlobalModification(session);
     verify(session).commit();
   }
@@ -237,7 +241,7 @@ public class QProfileBackupTest {
     }
 
     verify(hibernateSession, never()).saveWithoutFlush(any(RulesProfile.class));
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
     verifyZeroInteractions(dryRunCache);
   }
 
@@ -251,7 +255,7 @@ public class QProfileBackupTest {
 
     assertThat(result.profile()).isNull();
     verify(hibernateSession, never()).saveWithoutFlush(any(RulesProfile.class));
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
     verifyZeroInteractions(dryRunCache);
   }
 
@@ -273,7 +277,7 @@ public class QProfileBackupTest {
       assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("Restore of the profile has failed.");
     }
 
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
     verifyZeroInteractions(dryRunCache);
   }
 }
index 3f390d217534d1fee501fdb3cd99a217c75b0d1a..7033449b4efb9acb56cd660cc64ded7ccbdc164b 100644 (file)
@@ -43,7 +43,6 @@ import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.MockUserSession;
 import org.sonar.server.user.UserSession;
 
@@ -53,11 +52,17 @@ import static org.elasticsearch.common.collect.Lists.newArrayList;
 import static org.fest.assertions.Assertions.assertThat;
 import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyListOf;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class QProfileOperationsTest {
@@ -81,7 +86,7 @@ public class QProfileOperationsTest {
   PreviewCache dryRunCache;
 
   @Mock
-  RuleRegistry ruleRegistry;
+  ESActiveRule esActiveRule;
 
   @Mock
   QProfileLookup profileLookup;
@@ -121,7 +126,7 @@ public class QProfileOperationsTest {
       }
     }).when(qualityProfileDao).insert(any(QualityProfileDto.class), any(SqlSession.class));
 
-    operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, exporter, dryRunCache, ruleRegistry, profileLookup, profilesManager);
+    operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, exporter, dryRunCache, esActiveRule, profileLookup, profilesManager);
   }
 
   @Test
@@ -257,8 +262,8 @@ public class QProfileOperationsTest {
 
     verify(session).commit();
     verify(profilesManager).profileParentChanged(1, "Parent", "Nicolas");
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
@@ -277,8 +282,8 @@ public class QProfileOperationsTest {
 
     verify(session).commit();
     verify(profilesManager).profileParentChanged(1, "Parent", "Nicolas");
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
@@ -298,8 +303,8 @@ public class QProfileOperationsTest {
 
     verify(session).commit();
     verify(profilesManager).profileParentChanged(1, null, "Nicolas");
-    verify(ruleRegistry).deleteActiveRules(anyListOf(Integer.class));
-    verify(ruleRegistry).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
+    verify(esActiveRule).deleteActiveRules(anyListOf(Integer.class));
+    verify(esActiveRule).bulkIndexActiveRuleIds(anyListOf(Integer.class), eq(session));
   }
 
   @Test
@@ -361,7 +366,7 @@ public class QProfileOperationsTest {
     verify(activeRuleDao).deleteFromProfile(1, session);
     verify(qualityProfileDao).delete(1, session);
     verify(propertiesDao).deleteProjectProperties("sonar.profile.java", "Default", session);
-    verify(ruleRegistry).deleteActiveRulesFromProfile(1);
+    verify(esActiveRule).deleteActiveRulesFromProfile(1);
     verify(dryRunCache).reportGlobalModification(session);
   }
 
@@ -381,7 +386,7 @@ public class QProfileOperationsTest {
     verifyZeroInteractions(activeRuleDao);
     verify(qualityProfileDao, never()).delete(anyInt(), eq(session));
     verifyZeroInteractions(propertiesDao);
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
   }
 
   @Test
@@ -393,7 +398,7 @@ public class QProfileOperationsTest {
 
     verify(profilesManager).copyProfile(1, "Copy Default");
     verify(session).commit();
-    verify(ruleRegistry).bulkIndexProfile(2, session);
+    verify(esActiveRule).bulkIndexProfile(2, session);
   }
 
   @Test
@@ -410,7 +415,7 @@ public class QProfileOperationsTest {
 
     verifyZeroInteractions(profilesManager);
     verify(session, never()).commit();
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
   }
 
   @Test
@@ -428,7 +433,7 @@ public class QProfileOperationsTest {
 
     verifyZeroInteractions(profilesManager);
     verify(session, never()).commit();
-    verifyZeroInteractions(ruleRegistry);
+    verifyZeroInteractions(esActiveRule);
   }
 
 }
index c2207ddf8f04ebdbd8954854235e4335617a4d57..d69c982fff534aa4915d7ea916d75d6bbc9d4f39 100644 (file)
@@ -34,6 +34,7 @@ import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.profiles.ProfileExporter;
 import org.sonar.api.profiles.ProfileImporter;
 import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rule.Severity;
 import org.sonar.api.rules.ActiveRule;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.RulePriority;
@@ -43,7 +44,6 @@ import org.sonar.core.qualityprofile.db.ActiveRuleDto;
 import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
 import org.sonar.jpa.session.DatabaseSessionFactory;
 import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.rule.RuleRegistry;
 
 import java.io.Reader;
 import java.io.Writer;
@@ -55,7 +55,11 @@ import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyListOf;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class QProfilePluginExporterTest {
@@ -73,7 +77,7 @@ public class QProfilePluginExporterTest {
   ActiveRuleDao activeRuleDao;
 
   @Mock
-  RuleRegistry ruleRegistry;
+  ESActiveRule esActiveRule;
 
   List<ProfileImporter> importers = newArrayList();
   List<ProfileExporter> exporters = newArrayList();
@@ -96,7 +100,7 @@ public class QProfilePluginExporterTest {
       }
     }).when(activeRuleDao).insert(any(ActiveRuleDto.class), any(SqlSession.class));
 
-    operations = new QProfilePluginExporter(sessionFactory, activeRuleDao, ruleRegistry, importers, exporters);
+    operations = new QProfilePluginExporter(sessionFactory, activeRuleDao, esActiveRule, importers, exporters);
   }
 
   @Test
@@ -120,14 +124,14 @@ public class QProfilePluginExporterTest {
     ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
     verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
     assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
-    assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(4);
+    assertThat(activeRuleArgument.getValue().getSeverityString()).isEqualTo(Severity.BLOCKER);
 
     ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
     verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
     assertThat(activeRuleParamArgument.getValue().getKey()).isEqualTo("max");
     assertThat(activeRuleParamArgument.getValue().getValue()).isEqualTo("10");
 
-    verify(ruleRegistry).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
+    verify(esActiveRule).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
   }
 
   @Test
index ff7380812704a03fa80c08f86c3a4b9a0d10efbf..8194cd8a0fad39abf693ccda74bcda2282678533 100644 (file)
  */
 package org.sonar.server.qualityprofile;
 
-import org.sonar.server.rule.ProfileRuleQuery;
-import org.sonar.server.rule.RuleRegistry;
-
-import org.sonar.server.qualityprofile.QProfileRuleLookup;
 import com.github.tlrx.elasticsearch.test.EsSetup;
 import org.apache.commons.io.IOUtils;
 import org.elasticsearch.client.Requests;
@@ -35,8 +31,8 @@ import org.sonar.api.rule.Severity;
 import org.sonar.core.profiling.Profiling;
 import org.sonar.server.es.ESIndex;
 import org.sonar.server.es.ESNode;
-import org.sonar.server.qualityprofile.Paging;
-import org.sonar.server.qualityprofile.QProfileRule;
+import org.sonar.server.rule.ProfileRuleQuery;
+import org.sonar.server.rule.RuleRegistry;
 import org.sonar.test.TestUtils;
 
 import java.util.List;
@@ -65,8 +61,10 @@ public class QProfileRuleLookupTest {
     settings.setProperty("sonar.log.profilingLevel", "FULL");
     ESIndex index = new ESIndex(searchNode, new Profiling(settings));
     index.start();
-    RuleRegistry registry = new RuleRegistry(index, null, null, null);
+    RuleRegistry registry = new RuleRegistry(index, null);
     registry.start();
+    ESActiveRule esActiveRule = new ESActiveRule(index, null, null);
+    esActiveRule.start();
     profileRules = new QProfileRuleLookup(index);
 
     esSetup.client().prepareBulk()
index df2f10868ffb877dd604d9d1017b592e74cce715..9bc796d2f4ef764379999dbd7855ab3e3884687a 100644 (file)
@@ -40,7 +40,12 @@ import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDao;
 import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.rule.*;
+import org.sonar.core.rule.RuleDao;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.core.rule.RuleRuleTagDto;
+import org.sonar.core.rule.RuleTagDao;
+import org.sonar.core.rule.RuleTagType;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.rule.RuleRegistry;
@@ -58,7 +63,14 @@ import static org.fest.assertions.Assertions.assertThat;
 import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
 
 @RunWith(MockitoJUnitRunner.class)
 public class QProfileRuleOperationsTest {
@@ -81,6 +93,9 @@ public class QProfileRuleOperationsTest {
   @Mock
   RuleTagOperations ruleTagOperations;
 
+  @Mock
+  ESActiveRule esActiveRule;
+
   @Mock
   RuleRegistry ruleRegistry;
 
@@ -108,7 +123,7 @@ public class QProfileRuleOperationsTest {
       }
     }).when(activeRuleDao).insert(any(ActiveRuleDto.class), any(SqlSession.class));
 
-    operations = new QProfileRuleOperations(myBatis, activeRuleDao, ruleDao, ruleTagDao, ruleTagOperations, ruleRegistry, system);
+    operations = new QProfileRuleOperations(myBatis, activeRuleDao, ruleDao, ruleTagDao, ruleTagOperations, esActiveRule, ruleRegistry, system);
   }
 
   @Test
@@ -217,7 +232,7 @@ public class QProfileRuleOperationsTest {
     assertThat(ruleArgument.getValue().getParentId()).isEqualTo(10);
     assertThat(ruleArgument.getValue().getName()).isEqualTo("My New Rule");
     assertThat(ruleArgument.getValue().getDescription()).isEqualTo("Rule Description");
-    assertThat(ruleArgument.getValue().getSeverity()).isEqualTo(4);
+    assertThat(ruleArgument.getValue().getSeverityString()).isEqualTo(Severity.BLOCKER);
     assertThat(ruleArgument.getValue().getConfigKey()).isEqualTo("Xpath");
     assertThat(ruleArgument.getValue().getRepositoryKey()).isEqualTo("squid");
     assertThat(ruleArgument.getValue().getRuleKey()).startsWith("AvoidCycle");
@@ -252,7 +267,7 @@ public class QProfileRuleOperationsTest {
     verify(ruleDao).update(ruleArgument.capture(), eq(session));
     assertThat(ruleArgument.getValue().getName()).isEqualTo("Updated Rule");
     assertThat(ruleArgument.getValue().getDescription()).isEqualTo("Updated Description");
-    assertThat(ruleArgument.getValue().getSeverity()).isEqualTo(2);
+    assertThat(ruleArgument.getValue().getSeverityString()).isEqualTo(Severity.MAJOR);
 
     ArgumentCaptor<RuleParamDto> ruleParamArgument = ArgumentCaptor.forClass(RuleParamDto.class);
     verify(ruleDao).update(ruleParamArgument.capture(), eq(session));
@@ -272,7 +287,7 @@ public class QProfileRuleOperationsTest {
     when(ruleDao.selectTags(eq(ruleId), eq(session))).thenReturn(ruleTags);
 
     final int activeRuleId = 5;
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(activeRuleId).setProfileId(1).setRuleId(ruleId).setSeverity(1);
+    ActiveRuleDto activeRule = new ActiveRuleDto().setId(activeRuleId).setProfileId(1).setRuleId(ruleId).setSeverity(Severity.MINOR);
     when(activeRuleDao.selectByRuleId(ruleId)).thenReturn(newArrayList(activeRule));
 
     long now = System.currentTimeMillis();
@@ -289,7 +304,7 @@ public class QProfileRuleOperationsTest {
     verify(activeRuleDao).deleteParameters(eq(activeRuleId), eq(session));
     verify(activeRuleDao).deleteFromRule(eq(ruleId), eq(session));
     verify(session, times(2)).commit();
-    verify(ruleRegistry).deleteActiveRules(newArrayList(activeRuleId));
+    verify(esActiveRule).deleteActiveRules(newArrayList(activeRuleId));
   }
 
   @Test(expected = ForbiddenException.class)
index 067fc94b13e17ff395c4d227ccc59f11951e1f2c..9ddb7bed82ab18969a81cffd8c9bacc639ae279d 100644 (file)
@@ -27,10 +27,8 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Multimap;
 import org.apache.commons.io.IOUtils;
 import org.apache.ibatis.session.SqlSession;
-import org.elasticsearch.client.Requests;
 import org.elasticsearch.common.collect.Lists;
 import org.elasticsearch.common.settings.ImmutableSettings;
-import org.elasticsearch.search.SearchHit;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -38,24 +36,22 @@ import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.runners.MockitoJUnitRunner;
 import org.sonar.api.config.Settings;
+import org.sonar.api.rule.Severity;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.profiling.Profiling;
-import org.sonar.core.qualityprofile.db.ActiveRuleDao;
-import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
-import org.sonar.core.rule.*;
+import org.sonar.core.rule.RuleDao;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.core.rule.RuleRuleTagDto;
+import org.sonar.core.rule.RuleTagType;
 import org.sonar.server.es.ESIndex;
 import org.sonar.server.es.ESNode;
 import org.sonar.test.TestUtils;
 
-import java.io.IOException;
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import static com.google.common.collect.Lists.newArrayList;
-import static org.elasticsearch.index.query.FilterBuilders.*;
 import static org.fest.assertions.Assertions.assertThat;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
@@ -71,9 +67,6 @@ public class RuleRegistryTest {
   @Mock
   RuleDao ruleDao;
 
-  @Mock
-  ActiveRuleDao activeRuleDao;
-
   @Mock
   MyBatis myBatis;
 
@@ -98,7 +91,7 @@ public class RuleRegistryTest {
     searchIndex = new ESIndex(node, profiling);
     searchIndex.start();
 
-    registry = new RuleRegistry(searchIndex, ruleDao, activeRuleDao, myBatis);
+    registry = new RuleRegistry(searchIndex, ruleDao);
     registry.start();
 
     esSetup.execute(
@@ -117,7 +110,7 @@ public class RuleRegistryTest {
   @Test
   public void should_register_mapping_at_startup() {
     assertThat(esSetup.exists("rules")).isTrue();
-    assertThat(esSetup.client().admin().indices().prepareTypesExists("rules").setTypes("rule", "active_rule").execute().actionGet().isExists()).isTrue();
+    assertThat(esSetup.client().admin().indices().prepareTypesExists("rules").setTypes("rule").execute().actionGet().isExists()).isTrue();
   }
 
   @Test
@@ -179,7 +172,7 @@ public class RuleRegistryTest {
     rule1.setRepositoryKey("repo");
     rule1.setRuleKey("key1");
     rule1.setId(ruleId1);
-    rule1.setSeverity(1);
+    rule1.setSeverity(Severity.MINOR);
     rule1.setNoteData("noteData");
     rule1.setNoteUserLogin("userLogin");
     int ruleId2 = 4;
@@ -187,7 +180,7 @@ public class RuleRegistryTest {
     rule2.setRepositoryKey("repo");
     rule2.setRuleKey("key2");
     rule2.setId(ruleId2);
-    rule2.setSeverity(2);
+    rule2.setSeverity(Severity.MAJOR);
     rule2.setParentId(ruleId1);
     List<RuleDto> rules = ImmutableList.of(rule1, rule2);
 
@@ -228,7 +221,7 @@ public class RuleRegistryTest {
     RuleDto rule = new RuleDto();
     rule.setRepositoryKey("repo");
     rule.setRuleKey("key");
-    rule.setSeverity(1);
+    rule.setSeverity(Severity.MINOR);
     int id = 3;
     rule.setId(id);
     when(ruleDao.selectById(id)).thenReturn(rule);
@@ -246,14 +239,14 @@ public class RuleRegistryTest {
     rule1.setRepositoryKey("xoo");
     rule1.setRuleKey("key1");
     rule1.setId(ruleId1);
-    rule1.setSeverity(1);
+    rule1.setSeverity(Severity.MINOR);
     int ruleId2 = 2;
     RuleDto rule2 = new RuleDto();
     rule2.setRepositoryKey("xoo");
     rule2.setRuleKey("key2");
     rule2.setId(ruleId2);
     rule2.setParentId(ruleId1);
-    rule2.setSeverity(1);
+    rule2.setSeverity(Severity.MINOR);
     List<RuleDto> rules = ImmutableList.of(rule1, rule2);
 
     assertThat(esSetup.exists("rules", "rule", "3")).isTrue();
@@ -268,92 +261,6 @@ public class RuleRegistryTest {
     assertThat(esSetup.exists("rules", "rule", "3")).isFalse();
   }
 
-  @Test
-  public void bulk_index_active_rules() throws IOException {
-    List<ActiveRuleDto> activeRules = newArrayList(new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(2).setParentId(5));
-    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
-    paramsByActiveRule.putAll(1, newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters")));
-
-    registry.bulkIndexActiveRules(activeRules, paramsByActiveRule);
-    assertThat(esSetup.exists("rules", "active_rule", "1"));
-
-    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasChildFilter("active_rule", termFilter("profileId", 10))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(parentHit).hasSize(1);
-    assertThat(parentHit[0].getId()).isEqualTo("1");
-
-    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(childHit).hasSize(1);
-    assertThat(childHit[0].getId()).isEqualTo("1");
-  }
-
-  @Test
-  public void bulk_index_active_rules_from_ids() throws IOException {
-    when(myBatis.openSession()).thenReturn(session);
-
-    List<Integer> ids = newArrayList(1);
-    when(activeRuleDao.selectByIds(ids, session)).thenReturn(
-      newArrayList(new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(2).setParentId(5)));
-    when(activeRuleDao.selectParamsByActiveRuleIds(ids, session)).thenReturn(
-      newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters")));
-
-    registry.bulkIndexActiveRules(ids);
-    assertThat(esSetup.exists("rules", "active_rule", "1"));
-
-    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasChildFilter("active_rule", termFilter("profileId", 10))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(parentHit).hasSize(1);
-    assertThat(parentHit[0].getId()).isEqualTo("1");
-
-    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(childHit).hasSize(1);
-    assertThat(childHit[0].getId()).isEqualTo("1");
-  }
-
-  @Test
-  public void save_active_rule() throws IOException {
-    ActiveRuleDto activeRule = new ActiveRuleDto().setId(1).setProfileId(10).setRuleId(1).setSeverity(2);
-    ArrayList<ActiveRuleParamDto> params = newArrayList(new ActiveRuleParamDto().setId(1).setActiveRuleId(1).setRulesParameterId(1).setKey("key").setValue("RuleWithParameters"));
-
-    registry.save(activeRule, params);
-    assertThat(esSetup.exists("rules", "active_rule", "1"));
-
-    SearchHit[] parentHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasChildFilter("active_rule", termFilter("profileId", 10))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(parentHit).hasSize(1);
-    assertThat(parentHit[0].getId()).isEqualTo("1");
-
-    SearchHit[] childHit = esSetup.client().prepareSearch("rules").setPostFilter(
-      hasParentFilter("rule", termFilter("key", "RuleWithParameters"))
-    ).execute().actionGet().getHits().getHits();
-    assertThat(childHit).hasSize(1);
-    assertThat(childHit[0].getId()).isEqualTo("1");
-  }
-
-  @Test
-  public void delete_active_rules_from_profile() throws Exception {
-    esSetup.client().prepareBulk()
-      // On profile 1
-      .add(Requests.indexRequest().index("rules").type("active_rule").parent("1").source(testFileAsString("delete_from_profile/active_rule25.json")))
-      .add(Requests.indexRequest().index("rules").type("active_rule").parent("3").source(testFileAsString("delete_from_profile/active_rule2702.json")))
-        // On profile 2
-      .add(Requests.indexRequest().index("rules").type("active_rule").parent("2").source(testFileAsString("delete_from_profile/active_rule523.json")))
-      .setRefresh(true)
-      .execute().actionGet();
-
-    registry.deleteActiveRulesFromProfile(1);
-    assertThat(!esSetup.exists("rules", "active_rule", "25"));
-    assertThat(!esSetup.exists("rules", "active_rule", "2702"));
-    assertThat(esSetup.exists("rules", "active_rule", "523"));
-  }
-
   private String testFileAsString(String testFile) throws Exception {
     return IOUtils.toString(TestUtils.getResource(getClass(), testFile).toURI());
   }
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule25.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule25.json
new file mode 100644 (file)
index 0000000..38c9040
--- /dev/null
@@ -0,0 +1,6 @@
+{
+  "id": 25,
+  "severity": "MINOR",
+  "profileId": 1,
+  "inheritance": "OVERRIDES"
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule2702.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule2702.json
new file mode 100644 (file)
index 0000000..2025fbe
--- /dev/null
@@ -0,0 +1,16 @@
+{
+  "id": 2702,
+  "severity": "CRITICAL",
+  "profileId": 1,
+  "inheritance": null,
+  "params": [
+    {
+      "key": "fromClasses",
+      "value": "**.core.**"
+    },
+    {
+      "key": "toClasses",
+      "value": "**.server.**"
+    }
+  ]
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule523.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/delete_from_profile/active_rule523.json
new file mode 100644 (file)
index 0000000..96af0f4
--- /dev/null
@@ -0,0 +1,6 @@
+{
+  "id": 523,
+  "severity": "MAJOR",
+  "profileId": 2,
+  "inheritance": null
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule1.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule1.json
new file mode 100644 (file)
index 0000000..38a50de
--- /dev/null
@@ -0,0 +1,46 @@
+{
+  "id": 1,
+  "key": "RuleWithParameters",
+  "language": "xoo",
+  "name": "Rule with parameters - No Issue",
+  "description": "Rule containing parameter of different types : boolean, integer, etc. For information, no issue will be linked to this rule.",
+  "parentKey": null,
+  "repositoryKey": "xoo",
+  "severity": "MAJOR",
+  "status": "READY",
+  "createdAt": "2013-10-28T13:07:26.329Z",
+  "updatedAt": "2013-11-08T10:52:53.473Z",
+  "params": [
+      {
+        "key": "string",
+        "type": "STRING",
+        "defaultValue": null,
+        "description": ""
+      },
+      {
+        "key": "text",
+        "type": "TEXT",
+        "defaultValue": null,
+        "description": ""
+      },
+      {
+        "key": "boolean",
+        "type": "BOOLEAN",
+        "defaultValue": null,
+        "description": ""
+      },
+      {
+        "key": "integer",
+        "type": "INTEGER",
+        "defaultValue": null,
+        "description": ""
+      },
+      {
+        "key": "float",
+        "type": "FLOAT",
+        "defaultValue": null,
+        "description": ""
+      }
+    ]
+  }
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule2.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule2.json
new file mode 100644 (file)
index 0000000..f1adc5e
--- /dev/null
@@ -0,0 +1,13 @@
+{
+  "id": 2,
+  "key": "OneIssuePerLine",
+  "language": "xoo",
+  "name": "One Issue Per Line",
+  "description": "Generate an issue on each line of a file. It requires the metric \"lines\".",
+  "parentKey": null,
+  "repositoryKey": "xoo",
+  "severity": "MAJOR",
+  "status": "BETA",
+  "createdAt": "2013-10-28T13:07:26.339Z",
+  "updatedAt": "2013-11-08T10:52:53.487Z"
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule3.json b/sonar-server/src/test/resources/org/sonar/server/qualityprofile/ESActiveRuleTest/shared/rule3.json
new file mode 100644 (file)
index 0000000..534591d
--- /dev/null
@@ -0,0 +1,19 @@
+{
+  "id": 1,
+  "key": "RemobedRule",
+  "language": "xoo",
+  "name": "Removed rule",
+  "description": "Removed rule that should be filtered out in default query",
+  "parentKey": null,
+  "repositoryKey": "xoo",
+  "severity": "CRITICAL",
+  "status": "REMOVED",
+  "createdAt": "2013-10-28T13:07:26.329Z",
+  "updatedAt": "2013-11-08T10:52:53.473Z",
+  "note": {
+    "userLogin": "freddy.mallet",
+    "data": "",
+    "createdAt": "2013-12-10T13:07:26.329Z",
+    "updatedAt": "2013-12-12T10:52:53.473Z"
+  }
+}
diff --git a/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule25.json b/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule25.json
deleted file mode 100644 (file)
index 38c9040..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-{
-  "id": 25,
-  "severity": "MINOR",
-  "profileId": 1,
-  "inheritance": "OVERRIDES"
-}
diff --git a/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule2702.json b/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule2702.json
deleted file mode 100644 (file)
index 2025fbe..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-{
-  "id": 2702,
-  "severity": "CRITICAL",
-  "profileId": 1,
-  "inheritance": null,
-  "params": [
-    {
-      "key": "fromClasses",
-      "value": "**.core.**"
-    },
-    {
-      "key": "toClasses",
-      "value": "**.server.**"
-    }
-  ]
-}
diff --git a/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule523.json b/sonar-server/src/test/resources/org/sonar/server/rule/RuleRegistryTest/delete_from_profile/active_rule523.json
deleted file mode 100644 (file)
index 96af0f4..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-{
-  "id": 523,
-  "severity": "MAJOR",
-  "profileId": 2,
-  "inheritance": null
-}