]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-5007 refactor DAO framework
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Wed, 7 May 2014 12:39:26 +0000 (14:39 +0200)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Wed, 7 May 2014 15:10:24 +0000 (17:10 +0200)
36 files changed:
sonar-core/src/main/java/org/sonar/core/db/Dao.java
sonar-core/src/main/java/org/sonar/core/qualityprofile/db/ActiveRuleDto.java
sonar-core/src/main/java/org/sonar/core/qualityprofile/db/ActiveRuleKey.java
sonar-core/src/main/java/org/sonar/core/qualityprofile/db/ActiveRuleMapper.java
sonar-core/src/main/java/org/sonar/core/qualityprofile/db/ActiveRuleParamDto.java
sonar-core/src/main/java/org/sonar/core/rule/RuleDto.java
sonar-core/src/main/java/org/sonar/core/rule/RuleMapper.java
sonar-core/src/main/java/org/sonar/core/rule/RuleParamDto.java
sonar-core/src/main/resources/org/sonar/core/qualityprofile/db/ActiveRuleMapper.xml
sonar-core/src/main/resources/org/sonar/core/rule/RuleMapper.xml
sonar-server/src/main/java/org/sonar/server/db/BaseDao.java
sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleChange.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/ProfilesManager.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivation.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContext.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContextFactory.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationService.java [deleted file]
sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java
sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java
sonar-server/src/main/java/org/sonar/server/rule2/ActiveRuleDao.java
sonar-server/src/main/java/org/sonar/server/rule2/ActiveRuleNormalizer.java
sonar-server/src/main/java/org/sonar/server/rule2/RuleDao.java
sonar-server/src/main/java/org/sonar/server/rule2/RuleNormalizer.java
sonar-server/src/main/java/org/sonar/server/rule2/RuleService.java
sonar-server/src/main/java/org/sonar/server/search/BaseNormalizer.java
sonar-server/src/main/java/org/sonar/server/search/IndexSynchronizer.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfileRecreateBuiltInActionTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsTest.java
sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java
sonar-server/src/test/java/org/sonar/server/rule2/ActiveRuleDaoTest.java [deleted file]
sonar-server/src/test/java/org/sonar/server/rule2/ActiveRuleIndexMediumTest.java
sonar-server/src/test/java/org/sonar/server/rule2/RuleDaoTest.java
sonar-server/src/test/java/org/sonar/server/rule2/RuleIndexMediumTest.java
sonar-server/src/test/java/org/sonar/server/rule2/RuleServiceMediumTest.java

index b52c873a592a48e0f8b1605bce810dd336d168ad..fc9a0a9734d51a39e9de6eb1784977a3daa12256 100644 (file)
@@ -21,28 +21,22 @@ package org.sonar.core.db;
 
 import org.sonar.core.persistence.DbSession;
 
+import javax.annotation.CheckForNull;
 import java.io.Serializable;
 
 public interface Dao<E extends Dto<K>, K extends Serializable> {
 
-  E getByKey(K key);
-
-  E update(E item);
+  @CheckForNull
+  E getByKey(K key, DbSession session);
 
   E update(E item, DbSession session);
 
-  E insert(E item);
-
   E insert(E item, DbSession session);
 
-  void delete(E item);
-
   void delete(E item, DbSession session);
 
-  void deleteByKey(K key);
-
   void deleteByKey(K key, DbSession session);
 
-  Iterable<K> keysOfRowsUpdatedAfter(long timestamp);
+  Iterable<K> keysOfRowsUpdatedAfter(long timestamp, DbSession session);
 
 }
index e1e3ca0deb9ff022635f5c5c626ee6016d6f1cb0..fe3a586c76d72cba1f16271fbbe14090a3f8e497 100644 (file)
 
 package org.sonar.core.qualityprofile.db;
 
+import com.google.common.base.Preconditions;
 import org.apache.commons.lang.StringUtils;
-import org.sonar.api.rule.RuleKey;
 import org.sonar.core.db.Dto;
+import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.SeverityUtil;
 
 import javax.annotation.CheckForNull;
@@ -45,13 +46,14 @@ public class ActiveRuleDto implements Dto<ActiveRuleKey> {
   private String noteUserLogin;
   private String noteData;
 
-  private ActiveRuleKey key;
+  private transient ActiveRuleKey key;
 
-  public void setKey(QualityProfileKey qKey, RuleKey rKey){
-    this.key = ActiveRuleKey.of(qKey, rKey);
+  public ActiveRuleDto setKey(@Nullable ActiveRuleKey key) {
+    this.key = key;
+    return this;
   }
 
-  public ActiveRuleKey getKey(){
+  public ActiveRuleKey getKey() {
     return this.key;
   }
 
@@ -72,6 +74,7 @@ public class ActiveRuleDto implements Dto<ActiveRuleKey> {
     return profileId;
   }
 
+  // TODO mark as private
   public ActiveRuleDto setProfileId(Integer profileId) {
     this.profileId = profileId;
     return this;
@@ -81,6 +84,7 @@ public class ActiveRuleDto implements Dto<ActiveRuleKey> {
     return ruleId;
   }
 
+  // TODO mark as private
   public ActiveRuleDto setRuleId(Integer ruleId) {
     this.ruleId = ruleId;
     return this;
@@ -173,5 +177,12 @@ public class ActiveRuleDto implements Dto<ActiveRuleKey> {
     return StringUtils.equals(OVERRIDES, inheritance);
   }
 
+  public static ActiveRuleDto createFor(QualityProfileDto profileDto, RuleDto ruleDto) {
+    ActiveRuleDto dto = new ActiveRuleDto();
+    dto.setProfileId(profileDto.getId());
+    dto.setRuleId(ruleDto.getId());
+    dto.setKey(ActiveRuleKey.of(QualityProfileKey.of(profileDto.getName(), profileDto.getLanguage()), ruleDto.getKey()));
+    return dto;
+  }
 
 }
index cb0fc39b55409658b6f3701b16f20f43ee729877..5d1f3ffe4b5f4e81f1d02db29708d55cb89fbfd2 100644 (file)
@@ -20,7 +20,6 @@
 package org.sonar.core.qualityprofile.db;
 
 import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
 import org.sonar.api.rule.RuleKey;
 
 import java.io.Serializable;
@@ -30,7 +29,7 @@ import java.io.Serializable;
  *
  * @since 4.4
  */
-public class ActiveRuleKey implements Serializable{
+public class ActiveRuleKey implements Serializable {
   private final QualityProfileKey qualityProfileKey;
   private final RuleKey ruleKey;
 
@@ -43,10 +42,8 @@ public class ActiveRuleKey implements Serializable{
    * Create a key. Parameters are NOT null.
    */
   public static ActiveRuleKey of(QualityProfileKey qualityProfileKey, RuleKey ruleKey) {
-    Preconditions.checkArgument(!Strings.isNullOrEmpty(qualityProfileKey.name()), "QProfile is missing name");
-    Preconditions.checkArgument(!Strings.isNullOrEmpty(qualityProfileKey.lang()), "QProfile is missing lang");
-    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey.repository()), "RuleKey is missing repository");
-    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey.rule()), "RuleKey is missing key");
+    Preconditions.checkArgument(qualityProfileKey != null, "QProfile is missing");
+    Preconditions.checkArgument(ruleKey != null, "RuleKey is missing key");
     return new ActiveRuleKey(qualityProfileKey, ruleKey);
   }
 
@@ -58,7 +55,7 @@ public class ActiveRuleKey implements Serializable{
     String[] split = s.split(":");
     Preconditions.checkArgument(split.length == 4, "Bad format of activeRule key: " + s);
     return ActiveRuleKey.of(QualityProfileKey.of(split[0], split[1]),
-                             RuleKey.of(split[2], split[3]));
+      RuleKey.of(split[2], split[3]));
   }
 
   /**
index 2378dfb79310def989ee7b753a109c9eade564dc..6160b21b43c169337e656c09cc806d65ca964f0b 100644 (file)
@@ -21,6 +21,7 @@
 package org.sonar.core.qualityprofile.db;
 
 import org.apache.ibatis.annotations.Param;
+import org.sonar.api.rule.RuleKey;
 
 import javax.annotation.CheckForNull;
 
@@ -74,5 +75,4 @@ public interface ActiveRuleMapper {
 
   List<ActiveRuleParamDto> selectAllParams();
 
-
 }
index 2062a1f3f04e01af168bf1fd891d70f8a802ec63..40d583ea26c3709d48bb0af2398ee38d1f752f82 100644 (file)
@@ -20,6 +20,8 @@
 
 package org.sonar.core.qualityprofile.db;
 
+import org.sonar.core.rule.RuleParamDto;
+
 public class ActiveRuleParamDto {
 
   private Integer id;
@@ -50,6 +52,7 @@ public class ActiveRuleParamDto {
     return rulesParameterId;
   }
 
+  // TODO set private or drop
   public ActiveRuleParamDto setRulesParameterId(Integer rulesParameterId) {
     this.rulesParameterId = rulesParameterId;
     return this;
@@ -73,4 +76,10 @@ public class ActiveRuleParamDto {
     return this;
   }
 
+  public static ActiveRuleParamDto createFor(RuleParamDto minParam) {
+    ActiveRuleParamDto dto = new ActiveRuleParamDto();
+    dto.setKey(minParam.getName());
+    dto.setRulesParameterId(minParam.getId());
+    return dto;
+  }
 }
index e7d871fa2a32532ccaaed5e8c3177fe72a3c0bc0..20e0b1888131c59bfae02f7285dfc47852dddd89 100644 (file)
  */
 package org.sonar.core.rule;
 
-import org.sonar.api.rule.RuleKey;
-
-import org.sonar.core.db.Dto;
 import org.apache.commons.lang.builder.EqualsBuilder;
 import org.apache.commons.lang.builder.HashCodeBuilder;
 import org.apache.commons.lang.builder.ReflectionToStringBuilder;
 import org.apache.commons.lang.builder.ToStringStyle;
+import org.sonar.api.rule.RuleKey;
 import org.sonar.check.Cardinality;
+import org.sonar.core.db.Dto;
 
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
-
 import java.util.Date;
 
-public final class RuleDto implements Dto<RuleKey>{
+public final class RuleDto implements Dto<RuleKey> {
 
   public static final Integer DISABLED_CHARACTERISTIC_ID = -1;
 
@@ -64,9 +62,14 @@ public final class RuleDto implements Dto<RuleKey>{
   private Date createdAt;
   private Date updatedAt;
 
+  private transient RuleKey key;
+
   @Override
   public RuleKey getKey() {
-    return RuleKey.of(this.getRepositoryKey(), this.getRuleKey());
+    if (key == null) {
+      key = RuleKey.of(getRepositoryKey(), getRuleKey());
+    }
+    return key;
   }
 
   public Integer getId() {
@@ -150,7 +153,6 @@ public final class RuleDto implements Dto<RuleKey>{
     return this;
   }
 
-
   public Cardinality getCardinality() {
     return cardinality;
   }
index d0d7975a9d00511f1598ea609eba212212f7770e..9ee3d44e23c26f9763d1ff5459626d1576526aca 100644 (file)
@@ -50,6 +50,8 @@ public interface RuleMapper {
 
   List<RuleParamDto> selectParamsByRuleIds(@Param("ruleIds") List<Integer> ruleIds);
 
+  List<RuleParamDto> selectParamsByRuleKey(RuleKey ruleKey);
+
   RuleParamDto selectParamByRuleAndKey(@Param("ruleId") Integer ruleId, @Param("key") String key);
 
   void insertParameter(RuleParamDto param);
index d37004215137b0ab63dd24ea343e218ce0dae3e8..666af08e6967a91b05916ccb8793d3a845e04468 100644 (file)
@@ -82,4 +82,5 @@ public class RuleParamDto {
     this.description = description;
     return this;
   }
+
 }
index a41353bf019691211bcb998745eb34ff94c8faaf..2a7835f9f7e895bc8dff9b27ebe6a2d480836803 100644 (file)
     SELECT <include refid="activeRuleParamColumns"/>
     FROM active_rule_parameters p
   </select>
-
 </mapper>
 
index ee7b13de0bd21cf054932cb05bcb6c8629cb81bc..e27be96abb07988b5ffcada10b8736a4b690c309 100644 (file)
   </delete>
 
   <sql id="paramColumns">
-    id, rule_id as "ruleId", name, param_type as "type", default_value as "defaultValue", description
+    p.id as "id", p.rule_id as "ruleId", p.name as "name", p.param_type as "type", p.default_value as "defaultValue",
+    p.description as "description"
   </sql>
 
   <select id="selectAllParams" resultType="RuleParam">
     select <include refid="paramColumns"/>
-    from rules_parameters
+    from rules_parameters p
   </select>
 
   <select id="selectParamsByRuleIds" resultType="RuleParam">
     SELECT <include refid="paramColumns"/>
-    FROM rules_parameters
+    FROM rules_parameters p
     <where>
-      AND (<foreach item="id" index="index" collection="ruleIds" open="(" separator=" or " close=")">rule_id=#{id}</foreach>)
+      AND (<foreach item="id" index="index" collection="ruleIds" open="(" separator=" or " close=")">p.rule_id=#{id}</foreach>)
     </where>
   </select>
 
+  <select id="selectParamsByRuleKey" resultType="RuleParam" parameterType="org.sonar.api.rule.RuleKey">
+    SELECT <include refid="paramColumns"/>
+    FROM rules_parameters p, rules r
+    WHERE p.rule_id=r.id
+    AND r.PLUGIN_NAME=#{repository} AND r.PLUGIN_RULE_KEY=#{rule}
+  </select>
+
   <select id="selectParamByRuleAndKey" resultType="RuleParam">
     SELECT <include refid="paramColumns"/>
-    FROM rules_parameters
+    FROM rules_parameters p
     <where>
-      AND rule_id=#{ruleId}
-      AND name=#{key}
+      AND p.rule_id=#{ruleId}
+      AND p.name=#{key}
     </where>
   </select>
 
index 0c40a2e4b4c888f313dbe301416fb7df35322b92..b09cadc04b8eb7eb8926953f32a296de378013c0 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.db;
 
+import com.google.common.base.Preconditions;
 import org.sonar.core.db.Dao;
 import org.sonar.core.db.Dto;
 import org.sonar.core.persistence.DbSession;
@@ -30,21 +31,82 @@ import org.sonar.server.search.KeyIndexAction;
 
 import java.io.Serializable;
 
-public abstract class BaseDao<T, E extends Dto<K>, K extends Serializable>
-  implements Dao<E, K> {
+/**
+ * naming convention for DAO
+ * =========================
+ * <p/>
+ * The DAO manages a Business Domain for a set of DTO. There is a Main DTO (i.e. RuleDto)
+ * that has a few nested/child DTOs. The DAO supports nested DTOs for 1-to-1 and 1-to-many
+ * relations. Many-to-many relations are handled by their own DAO classes (i.e. ActiveRuleDao)
+ * <p/>
+ * Main DTO
+ * -------------------------
+ * <p/>
+ * * GET Methods
+ * - returns a single DTO
+ * - DTO is fully loaded (no field will return null)
+ * - returns null (and not empty)
+ * - examples:
+ * - RuleDto = ruleDao.getByKey(dto.getKey());
+ * <p/>
+ * * FIND Methods
+ * - returns a List of DTO.
+ * - Returns an empty list id no match
+ * - method name is FULLY-NOMINATIVE
+ * - examples:
+ * - List<RuleDto> rules findByQualityProfile(QualityProfile qprofile)
+ * - List<RuleDto> rules findByQualityProfile(QualityProfileKey qprofileKey)
+ * - List<RuleDto> rules findByQualityProfileAndCreatedAfter(QualityProfileKey qprofileKey, Date date)
+ * <p/>
+ * * CRUD Methods
+ * - insert(DTO)
+ * - udpate(DTO)
+ * - delete(DTO)
+ * <p/>
+ * Nested DTO
+ * -------------------------
+ * <p/>
+ * Some DAO implementations also manage nested DTO. RuleTag for example is managed by the RuleDao class
+ * Nested DTO are accessible following a similar convention for the Main DTO:
+ * <p/>
+ * * GET Methods
+ * - returns a single DTO
+ * - DTO is fully loaded (no field will return null)
+ * - returns null (and not empty)
+ * - prefixed with DTO type
+ * - examples:
+ * - RuleTagDto = ruleDao.getTagByKey(tagDto.getKey());
+ * <p/>
+ * * FIND Methods
+ * - returns a List of DTO.
+ * - Returns an empty list id no match
+ * - method name is FULLY-NOMINATIVE
+ * - prefixed with DTO type
+ * - examples:
+ * - List<RuleTagDto> tags findRuleTagByRuleKey(RuleKey key)
+ * - List<RuleTagDto> tags findRuleTagByRepositoryAndLanguage(RepositoryKey key, String language)
+ * <p/>
+ * * CRUD Methods are slightly different because they REQUIRE the main DTO to be valid
+ * - Nested dto methods MUST have the Main DTO or it's key as param
+ * - add
+ * - remove
+ * - update
+ * - examples:
+ * - RuleTagDto tag add(RuleTagDto tag, RuleKey key)
+ * - RuleParamDto param add(RuleParamDto param, RuleDto rule)
+ *
+ * @param <M> iBatis Mapper class
+ * @param <E> Produced DTO class from this dao
+ * @param <K> DTO Key class
+ */
+public abstract class BaseDao<M, E extends Dto<K>, K extends Serializable> implements Dao<E, K> {
 
-  protected final MyBatis mybatis;
-  private Class<T> mapperClass;
   protected final IndexDefinition indexDefinition;
+  private Class<M> mapperClass;
 
-  protected BaseDao(IndexDefinition indexDefinition, Class<T> mapperClass, MyBatis myBatis) {
+  protected BaseDao(IndexDefinition indexDefinition, Class<M> mapperClass) {
     this.indexDefinition = indexDefinition;
     this.mapperClass = mapperClass;
-    this.mybatis = myBatis;
-  }
-
-  public String getIndexName() {
-    return this.indexDefinition.getIndexName();
   }
 
   public String getIndexType() {
@@ -53,105 +115,46 @@ public abstract class BaseDao<T, E extends Dto<K>, K extends Serializable>
 
   protected abstract E doGetByKey(K key, DbSession session);
 
+  protected abstract K getKey(E item, DbSession session);
+
   protected abstract E doInsert(E item, DbSession session);
 
   protected abstract E doUpdate(E item, DbSession session);
 
-  protected abstract void doDelete(E item, DbSession session);
-
   protected abstract void doDeleteByKey(K key, DbSession session);
 
-  protected T getMapper(DbSession session) {
+  protected M mapper(DbSession session) {
     return session.getMapper(mapperClass);
   }
 
-  protected MyBatis getMyBatis() {
-    return this.mybatis;
-  }
-
-  @Override
-  public E getByKey(K key) {
-    DbSession session = getMyBatis().openSession(false);
-    try {
-      return this.doGetByKey(key, session);
-    } finally {
-      session.close();
-    }
+  public E getByKey(K key, DbSession session) {
+    return doGetByKey(key, session);
   }
 
   @Override
   public E update(E item, DbSession session) {
     this.doUpdate(item, session);
-    session.enqueue(new DtoIndexAction<E>(this.getIndexType(),
-      IndexAction.Method.UPDATE, item));
+    session.enqueue(new DtoIndexAction<E>(this.getIndexType(), IndexAction.Method.UPDATE, item));
     return item;
   }
 
-  @Override
-  public E update(E item) {
-    DbSession session = getMyBatis().openSession(false);
-    try {
-      this.update(item, session);
-      session.commit();
-      return item;
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @Override
   public E insert(E item, DbSession session) {
     this.doInsert(item, session);
-    session.enqueue(new DtoIndexAction<E>(this.getIndexType(),
-      IndexAction.Method.INSERT, item));
+    session.enqueue(new DtoIndexAction<E>(this.getIndexType(), IndexAction.Method.INSERT, item));
     return item;
   }
 
-  @Override
-  public E insert(E item) {
-    DbSession session = getMyBatis().openSession(false);
-    try {
-      this.insert(item, session);
-      session.commit();
-      return item;
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @Override
   public void delete(E item, DbSession session) {
-    this.doDelete(item, session);
-    session.enqueue(new DtoIndexAction<E>(this.getIndexType(),
-      IndexAction.Method.DELETE, item));
-  }
-
-  @Override
-  public void delete(E item) {
-    DbSession session = getMyBatis().openSession(false);
-    try {
-      this.delete(item, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+    deleteByKey(getKey(item, session), session);
   }
 
   @Override
   public void deleteByKey(K key, DbSession session) {
-    this.doDeleteByKey(key, session);
-    session.enqueue(new KeyIndexAction<K>(this.getIndexType(),
-      IndexAction.Method.DELETE, key));
+    Preconditions.checkNotNull(key);
+    doDeleteByKey(key, session);
+    session.enqueue(new KeyIndexAction<K>(this.getIndexType(), IndexAction.Method.DELETE, key));
   }
 
-  @Override
-  public void deleteByKey(K key) {
-    DbSession session = getMyBatis().openSession(false);
-    try {
-      this.doDeleteByKey(key, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
 }
index e61d52791cd4c2ecad93b021d34e3873115578b6..b0a27ede95e73143b6bb5c3b42fcbcee1f6b01fa 100644 (file)
@@ -288,7 +288,8 @@ class ServerComponents {
     pico.addSingleton(QProfilesWs.class);
     pico.addSingleton(ProfilesWs.class);
     pico.addSingleton(ActivateRuleAction.class);
-    pico.addSingleton(RuleActivationService.class);
+    pico.addSingleton(ActiveRuleService.class);
+    pico.addSingleton(RuleActivationContextFactory.class);
 
     // rule
     pico.addSingleton(AnnotationRuleParser.class);
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleChange.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleChange.java
new file mode 100644 (file)
index 0000000..8630a01
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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 com.google.common.collect.Maps;
+import org.apache.commons.lang.ObjectUtils;
+import org.sonar.core.qualityprofile.db.ActiveRuleKey;
+
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+import java.util.Map;
+
+public class ActiveRuleChange {
+
+  static enum Type {
+    ACTIVATED, DEACTIVATED, UPDATED
+  }
+
+  private final Type type;
+  private final ActiveRuleKey key;
+  private boolean inheritedChange = false;
+  private String previousSeverity = null, severity = null;
+  private Map<String, String> previousParameters = null, parameters = null;
+
+  ActiveRuleChange(Type type, ActiveRuleKey key) {
+    this.type = type;
+    this.key = key;
+  }
+
+  public ActiveRuleKey getKey() {
+    return key;
+  }
+
+  public Type getType() {
+    return type;
+  }
+
+  public boolean isInheritedChange() {
+    return inheritedChange;
+  }
+
+  public void setInheritedChange(boolean b) {
+    this.inheritedChange = b;
+  }
+
+  @CheckForNull
+  public String getPreviousSeverity() {
+    return previousSeverity;
+  }
+
+  public void setPreviousSeverity(@Nullable String s) {
+    this.previousSeverity = s;
+  }
+
+  @CheckForNull
+  public String getSeverity() {
+    return severity;
+  }
+
+  public void setSeverity(@Nullable String severity) {
+    this.severity = severity;
+  }
+
+  @CheckForNull
+  public Map<String, String> getPreviousParameters() {
+    return previousParameters;
+  }
+
+  public void setPreviousParameters(@Nullable Map<String, String> previousParameters) {
+    this.previousParameters = previousParameters;
+  }
+
+  @CheckForNull
+  public Map<String, String> getParameters() {
+    return parameters;
+  }
+
+  public void setParameters(@Nullable Map<String, String> parameters) {
+    this.parameters = parameters;
+  }
+
+  boolean hasDifferences() {
+    if (!ObjectUtils.equals(severity, previousSeverity)) {
+      return true;
+    }
+    if (!ObjectUtils.equals(parameters, previousParameters)) {
+      return parameters == null || previousParameters != null || !Maps.difference(parameters, previousParameters).areEqual();
+    }
+    return false;
+  }
+}
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java
new file mode 100644 (file)
index 0000000..d732e9e
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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 com.google.common.base.Splitter;
+import com.google.common.collect.Lists;
+import org.apache.commons.lang.StringUtils;
+import org.sonar.api.ServerComponent;
+import org.sonar.api.server.rule.RuleParamType;
+import org.sonar.core.permission.GlobalPermissions;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.core.persistence.MyBatis;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleKey;
+import org.sonar.core.rule.RuleParamDto;
+import org.sonar.server.rule2.ActiveRuleDao;
+import org.sonar.server.user.UserSession;
+import org.sonar.server.util.TypeValidations;
+
+import java.util.Collection;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+public class ActiveRuleService implements ServerComponent {
+
+  private final MyBatis myBatis;
+  private final ActiveRuleDao activeRuleDao;
+  private final TypeValidations typeValidations;
+  private final RuleActivationContextFactory contextFactory;
+
+  public ActiveRuleService(MyBatis myBatis, ActiveRuleDao activeRuleDao,
+                           RuleActivationContextFactory contextFactory, TypeValidations typeValidations) {
+    this.myBatis = myBatis;
+    this.activeRuleDao = activeRuleDao;
+    this.contextFactory = contextFactory;
+    this.typeValidations = typeValidations;
+  }
+
+  /**
+   * Activate a rule on a Quality profile. Update configuration (severity/parameters) if the rule is already
+   * activated.
+   */
+  public List<ActiveRuleChange> activate(RuleActivation activation, UserSession userSession) {
+    verifyPermission(userSession);
+
+    DbSession dbSession = myBatis.openSession(false);
+    List<ActiveRuleChange> changes = Lists.newArrayList();
+    try {
+      RuleActivationContext context = contextFactory.create(activation.getKey(), dbSession);
+      ActiveRuleChange change;
+      if (context.activeRule() == null) {
+        change = new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, activation.getKey());
+      } else {
+        change = new ActiveRuleChange(ActiveRuleChange.Type.UPDATED, activation.getKey());
+      }
+      change.setSeverity(StringUtils.defaultIfEmpty(activation.getSeverity(), context.defaultSeverity()));
+      // TODO params
+      changes.add(change);
+
+      // TODO apply changes to children
+
+      persist(changes, dbSession);
+      dbSession.commit();
+
+      // TODO filter changes without any differences
+      return changes;
+
+    } finally {
+      dbSession.close();
+    }
+  }
+
+  private void persist(Collection<ActiveRuleChange> changes, DbSession dbSession) {
+    for (ActiveRuleChange change : changes) {
+      if (change.getType() == ActiveRuleChange.Type.ACTIVATED) {
+        ActiveRuleDto activeRule = ActiveRuleDto.createFor(null, null /* TODO */)
+          .setKey(change.getKey())
+          .setSeverity(change.getSeverity());
+        activeRuleDao.insert(activeRule, dbSession);
+
+        // TODO insert activeruelparams
+
+      } else if (change.getType() == ActiveRuleChange.Type.DEACTIVATED) {
+        activeRuleDao.deleteByKey(change.getKey(), dbSession);
+
+      } else if (change.getType() == ActiveRuleChange.Type.UPDATED) {
+
+      }
+    }
+  }
+
+  /**
+   * Deactivate a rule on a Quality profile. Does nothing if the rule is not activated.
+   */
+  public List<ActiveRuleChange> deactivate(ActiveRuleKey key, UserSession userSession) {
+    verifyPermission(userSession);
+    throw new UnsupportedOperationException("TODO");
+  }
+
+  public List<ActiveRuleChange> bulkActivate(BulkRuleActivation activation, UserSession userSession) {
+    verifyPermission(userSession);
+    throw new UnsupportedOperationException("TODO");
+  }
+
+
+  private void verifyPermission(UserSession userSession) {
+    userSession.checkLoggedIn();
+    userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
+  }
+
+  private void verifyParam(RuleParamDto ruleParam, String value) {
+    RuleParamType ruleParamType = RuleParamType.parse(ruleParam.getType());
+    if (ruleParamType.multiple()) {
+      List<String> values = newArrayList(Splitter.on(",").split(value));
+      typeValidations.validate(values, ruleParamType.type(), ruleParamType.values());
+    } else {
+      typeValidations.validate(value, ruleParamType.type(), ruleParamType.values());
+    }
+  }
+}
index f67b3ff88a773960f7ad0fee3769806354abe744..27f32a4f516d1dea56f88ecfb219099448a29217 100644 (file)
@@ -27,6 +27,7 @@ import org.sonar.api.profiles.RulesProfile;
 import org.sonar.api.rules.*;
 import org.sonar.core.preview.PreviewCache;
 import org.sonar.jpa.dao.BaseDao;
+import org.sonar.api.rules.ActiveRuleChange;
 import org.sonar.jpa.dao.RulesDao;
 
 import javax.annotation.CheckForNull;
index 65cae48c06643d5e9ed8e3506bf007dd23a24f24..e83a71f62fd66d99d831c86b384072eeae5b8418 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.qualityprofile;
 
+import com.google.common.base.Strings;
 import com.google.common.collect.Maps;
 import org.sonar.api.rule.Severity;
 import org.sonar.core.qualityprofile.db.ActiveRuleKey;
@@ -48,10 +49,11 @@ public class RuleActivation {
   }
 
   public RuleActivation setParam(String key, @Nullable String value) {
+    String sanitizedValue = Strings.emptyToNull(value);
     if (value == null) {
       parameters.remove(key);
     } else {
-      parameters.put(key, value);
+      parameters.put(key, sanitizedValue);
     }
     return this;
   }
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContext.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContext.java
new file mode 100644 (file)
index 0000000..2cc2714
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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 com.google.common.collect.Maps;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.core.rule.RuleParamDto;
+
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+import java.util.Collection;
+import java.util.Map;
+
+class RuleActivationContext {
+
+  private RuleDto rule;
+  private Map<String, RuleParamDto> ruleParams;
+  private QualityProfileDto profile, parentProfile;
+  private ActiveRuleDto activeRule, parentActiveRule;
+  private Map<String, ActiveRuleParamDto> activeRuleParams, parentActiveRuleParams;
+
+  RuleDto rule() {
+    return rule;
+  }
+
+  RuleActivationContext setRule(RuleDto rule) {
+    this.rule = rule;
+    return this;
+  }
+
+  Map<String, RuleParamDto> ruleParamsByKeys() {
+    return ruleParams;
+  }
+
+  Collection<RuleParamDto> ruleParams() {
+    return ruleParams.values();
+  }
+
+  RuleActivationContext setRuleParams(Collection<RuleParamDto> ruleParams) {
+    this.ruleParams = Maps.newHashMap();
+    for (RuleParamDto ruleParam : ruleParams) {
+      this.ruleParams.put(ruleParam.getName(), ruleParam);
+    }
+    return this;
+  }
+
+  QualityProfileDto profile() {
+    return profile;
+  }
+
+  RuleActivationContext setProfile(QualityProfileDto profile) {
+    this.profile = profile;
+    return this;
+  }
+
+  @CheckForNull
+  QualityProfileDto parentProfile() {
+    return parentProfile;
+  }
+
+  RuleActivationContext setParentProfile(@Nullable QualityProfileDto p) {
+    this.parentProfile = p;
+    return this;
+  }
+
+  @CheckForNull
+  ActiveRuleDto activeRule() {
+    return activeRule;
+  }
+
+  RuleActivationContext setActiveRule(@Nullable ActiveRuleDto a) {
+    this.activeRule = a;
+    return this;
+  }
+
+  @CheckForNull
+  ActiveRuleDto parentActiveRule() {
+    return parentActiveRule;
+  }
+
+  RuleActivationContext setParentActiveRule(@Nullable ActiveRuleDto a) {
+    this.parentActiveRule = a;
+    return this;
+  }
+
+  @CheckForNull
+  Map<String, ActiveRuleParamDto> activeRuleParamsAsMap() {
+    return activeRuleParams;
+  }
+
+  @CheckForNull
+  Collection<ActiveRuleParamDto> activeRuleParams() {
+    return activeRuleParams != null ? activeRuleParams.values() : null;
+  }
+
+  RuleActivationContext setActiveRuleParams(@Nullable Collection<ActiveRuleParamDto> a) {
+    if (a == null) {
+      this.activeRuleParams = null;
+    } else {
+      this.activeRuleParams = Maps.newHashMap();
+      for (ActiveRuleParamDto ar : a) {
+        this.activeRuleParams.put(ar.getKey(), ar);
+      }
+    }
+    return this;
+  }
+
+  @CheckForNull
+  Map<String, ActiveRuleParamDto> parentActiveRuleParams() {
+    return parentActiveRuleParams;
+  }
+
+  RuleActivationContext setParentActiveRuleParams(@Nullable Collection<ActiveRuleParamDto> a) {
+    if (a == null) {
+      this.parentActiveRuleParams = null;
+    } else {
+      this.parentActiveRuleParams = Maps.newHashMap();
+      for (ActiveRuleParamDto ar : a) {
+        this.parentActiveRuleParams.put(ar.getKey(), ar);
+      }
+    }
+    return this;
+  }
+
+  String defaultSeverity() {
+    return parentActiveRule != null ? parentActiveRule.getSeverityString() : rule.getSeverityString();
+  }
+}
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContextFactory.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationContextFactory.java
new file mode 100644 (file)
index 0000000..8d6240f
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.api.ServerComponent;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rule.RuleStatus;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleKey;
+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.qualityprofile.db.QualityProfileKey;
+import org.sonar.core.rule.RuleDto;
+import org.sonar.server.rule2.ActiveRuleDao;
+import org.sonar.server.rule2.RuleDao;
+
+import java.util.Collection;
+
+public class RuleActivationContextFactory implements ServerComponent {
+
+  private final ActiveRuleDao activeRuleDao;
+  private final RuleDao ruleDao;
+  private final QualityProfileDao profileDao;
+
+  public RuleActivationContextFactory(ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao) {
+    this.activeRuleDao = activeRuleDao;
+    this.ruleDao = ruleDao;
+    this.profileDao = profileDao;
+  }
+
+  public RuleActivationContext create(ActiveRuleKey key, DbSession session) {
+    RuleActivationContext context = new RuleActivationContext();
+
+    RuleDto rule = initRule(key.ruleKey(), context, session);
+
+    QualityProfileDto profile = initProfile(key, context, session, false);
+    initActiveRules(key, context, session, false);
+    if (!profile.getLanguage().equals(rule.getLanguage())) {
+      throw new IllegalArgumentException(String.format("Rule %s and profile %s have different languages", rule.getKey(), profile));
+    }
+
+    if (profile.getParent() != null) {
+      ActiveRuleKey parentKey = ActiveRuleKey.of(
+        QualityProfileKey.of(profile.getParent(), profile.getLanguage()), rule.getKey());
+      initProfile(parentKey, context, session, true);
+      initActiveRules(parentKey, context, session, true);
+    }
+    return context;
+  }
+
+  private RuleDto initRule(RuleKey ruleKey, RuleActivationContext context, DbSession dbSession) {
+    RuleDto rule = ruleDao.getByKey(ruleKey, dbSession);
+    if (rule == null) {
+      throw new IllegalArgumentException("Rule not found: " + ruleKey);
+    }
+    if (RuleStatus.REMOVED == RuleStatus.valueOf(rule.getStatus())) {
+      throw new IllegalArgumentException("Rule was removed: " + ruleKey);
+    }
+    context.setRule(rule);
+    context.setRuleParams(ruleDao.findRuleParamsByRuleKey(rule.getKey(), dbSession));
+    return rule;
+  }
+
+  private QualityProfileDto initProfile(ActiveRuleKey key, RuleActivationContext context, DbSession session, boolean parent) {
+    QualityProfileDto profile = profileDao.selectByNameAndLanguage(
+      key.qProfile().name(), key.qProfile().lang());
+    if (profile == null) {
+      throw new IllegalArgumentException("Quality profile not found: " + key.qProfile());
+    }
+    if (parent) {
+      context.setParentProfile(profile);
+    } else {
+      context.setProfile(profile);
+    }
+    return profile;
+  }
+
+  private void initActiveRules(ActiveRuleKey key, RuleActivationContext context, DbSession session, boolean parent) {
+    ActiveRuleDto activeRule = activeRuleDao.getByKey(key, session);
+    Collection<ActiveRuleParamDto> activeRuleParams = null;
+    if (activeRule != null) {
+      context.setActiveRuleParams(activeRuleDao.findParamsByActiveRule(activeRule, session));
+    }
+    if (parent) {
+      context.setParentActiveRule(activeRule);
+      context.setParentActiveRuleParams(activeRuleParams);
+    } else {
+      context.setActiveRule(activeRule);
+      context.setActiveRuleParams(activeRuleParams);
+    }
+  }
+}
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationService.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivationService.java
deleted file mode 100644 (file)
index f1d91b5..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 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.api.ServerComponent;
-import org.sonar.core.permission.GlobalPermissions;
-import org.sonar.core.persistence.DbSession;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.qualityprofile.db.ActiveRuleKey;
-import org.sonar.server.rule2.ActiveRuleDao;
-import org.sonar.server.user.UserSession;
-
-public class RuleActivationService implements ServerComponent {
-
-  private final MyBatis myBatis;
-  private final ActiveRuleDao activeRuleDao;
-
-  public RuleActivationService(MyBatis myBatis, ActiveRuleDao activeRuleDao) {
-    this.myBatis = myBatis;
-    this.activeRuleDao = activeRuleDao;
-  }
-
-  /**
-   * Activate a rule on a Quality profile. Update configuration (severity/parameters) if the rule is already
-   * activated.
-   */
-  public RuleActivation activate(RuleActivation activation, UserSession userSession) {
-    verifyPermission(userSession);
-    DbSession session = myBatis.openSession(false);
-    try {
-      ActiveRuleDto dto = activeRuleDao.getByKey(activation.getKey());
-      if (dto == null) {
-        // insert -> verify profile and parameters
-
-      } else {
-        // update -> verify parameters
-      }
-
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-
-    throw new UnsupportedOperationException("TODO");
-  }
-
-  /**
-   * Deactivate a rule on a Quality profile. Does nothing if the rule is not activated.
-   */
-  public boolean deactivate(ActiveRuleKey key, UserSession userSession) {
-    verifyPermission(userSession);
-    throw new UnsupportedOperationException("TODO");
-  }
-
-  /**
-   * Only for rules inherited from parent profile
-   */
-  public RuleActivation revert(ActiveRuleKey key, UserSession userSession) {
-    verifyPermission(userSession);
-    throw new UnsupportedOperationException("TODO");
-  }
-
-  public void bulkActivate(BulkRuleActivation activation, UserSession userSession) {
-    verifyPermission(userSession);
-    throw new UnsupportedOperationException("TODO");
-  }
-
-  private void verifyPermission(UserSession userSession) {
-    userSession.checkLoggedIn();
-    userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
-  }
-}
index a621f400f249686e2b84b502160ddf782148f7e9..0b49d506377113377391ce9aa2a0078a9e9a8aa8 100644 (file)
@@ -24,13 +24,13 @@ import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.RequestHandler;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
-import org.sonar.server.qualityprofile.RuleActivationService;
+import org.sonar.server.qualityprofile.ActiveRuleService;
 
 public class ActivateRuleAction implements RequestHandler {
 
-  private final RuleActivationService service;
+  private final ActiveRuleService service;
 
-  public ActivateRuleAction(RuleActivationService service) {
+  public ActivateRuleAction(ActiveRuleService service) {
     this.service = service;
   }
 
index 6c0ef81c719ec7441270f16a1972dc01188438ce..6a995d683e58beb6673e9387d2304553628a1135 100644 (file)
@@ -44,7 +44,7 @@ import org.sonar.check.Cardinality;
 import org.sonar.core.persistence.DbSession;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDao;
-import org.sonar.server.rule2.RuleDao;
+import org.sonar.core.rule.RuleDao;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleParamDto;
 import org.sonar.core.rule.RuleRuleTagDto;
@@ -58,7 +58,6 @@ import org.sonar.server.startup.RegisterDebtModel;
 
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
-
 import java.util.Collection;
 import java.util.Date;
 import java.util.List;
@@ -294,7 +293,7 @@ public class RegisterRules implements Startable {
       hasDebt ? def.effortToFixDescription() : null);
   }
 
-  private boolean mergeDebtDefinitions(RulesDefinition.Rule def, RuleDto dto,@Nullable  Integer characteristicId, @Nullable String remediationFunction,
+  private boolean mergeDebtDefinitions(RulesDefinition.Rule def, RuleDto dto, @Nullable Integer characteristicId, @Nullable String remediationFunction,
                                        @Nullable String remediationCoefficient, @Nullable String remediationOffset, @Nullable String effortToFixDescription) {
     boolean changed = false;
 
@@ -571,7 +570,7 @@ public class RegisterRules implements Startable {
       unprocessedRuleIds.remove(ruleDto.getId());
     }
 
-    CharacteristicDto characteristic(@Nullable String subCharacteristic, String repo, String ruleKey, @Nullable Integer overridingCharacteristicId){
+    CharacteristicDto characteristic(@Nullable String subCharacteristic, String repo, String ruleKey, @Nullable Integer overridingCharacteristicId) {
       // Rule is not linked to a default characteristic or characteristic has been disabled by user
       if (subCharacteristic == null) {
         return null;
index 1c21797d3dcfc2a67c810ae759b0bf6d573fb3ae..58f6cb771a8ee4eec1d0fc0483d45d4b62400a42 100644 (file)
 
 package org.sonar.server.rule2;
 
-import com.google.common.collect.Lists;
-import org.hibernate.cfg.NotYetImplementedException;
-import org.sonar.api.ServerComponent;
+import com.google.common.base.Preconditions;
+import org.sonar.api.rule.RuleKey;
 import org.sonar.core.persistence.DbSession;
-import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDto;
 import org.sonar.core.qualityprofile.db.ActiveRuleKey;
 import org.sonar.core.qualityprofile.db.ActiveRuleMapper;
@@ -37,377 +35,104 @@ import org.sonar.server.db.BaseDao;
 import org.sonar.server.search.EmbeddedIndexAction;
 import org.sonar.server.search.IndexAction;
 
-import javax.annotation.CheckForNull;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.List;
 
-import static com.google.common.collect.Lists.newArrayList;
+public class ActiveRuleDao extends BaseDao<ActiveRuleMapper, ActiveRuleDto, ActiveRuleKey> {
 
-public class ActiveRuleDao extends BaseDao<ActiveRuleMapper, ActiveRuleDto, ActiveRuleKey>
-  implements ServerComponent {
+  private final RuleDao ruleDao;
+  private final QualityProfileDao profileDao;
 
-  /** this is temporary to build RuleKey and QProfileKey */
-  private RuleDao ruleDao;
-  private QualityProfileDao qDao;
-
-  public ActiveRuleDao(MyBatis mybatis, QualityProfileDao qDao, RuleDao ruleDao) {
-    super(new ActiveRuleIndexDefinition(), ActiveRuleMapper.class, mybatis);
+  public ActiveRuleDao(QualityProfileDao profileDao, RuleDao ruleDao) {
+    super(new ActiveRuleIndexDefinition(), ActiveRuleMapper.class);
     this.ruleDao = ruleDao;
-    this.qDao = qDao;
+    this.profileDao = profileDao;
   }
 
   @Override
-  public Iterable<ActiveRuleKey> keysOfRowsUpdatedAfter(long timestamp) {
-    throw new NotYetImplementedException("Need to implement ActiveRuleDto.doGetByKey() method");
+  public ActiveRuleKey getKey(ActiveRuleDto item, DbSession session) {
+    if (item.getKey() != null) {
+      return item.getKey();
+    }
+    fixIdsAndKeys(item, session);
+    return item.getKey();
   }
 
   @Override
-  protected ActiveRuleDto doGetByKey(ActiveRuleKey key, DbSession session) {
-    QualityProfileDto qDto = qDao.selectByNameAndLanguage(key.qProfile().name(), key.qProfile().lang(), session);
-    RuleDto ruleDto = ruleDao.selectByKey(key.ruleKey());
-    return this.selectByProfileAndRule(qDto.getId(), ruleDto.getId(), session);
+  public Iterable<ActiveRuleKey> keysOfRowsUpdatedAfter(long timestamp, DbSession session) {
+    throw new UnsupportedOperationException("Need to implement ActiveRuleDto.doGetByKey() method");
   }
 
   @Override
-  protected ActiveRuleDto doInsert(ActiveRuleDto item, DbSession session) {
-    getMapper(session).insert(item);
-    return setActiveRuleKey(item, session);
+  protected ActiveRuleDto doGetByKey(ActiveRuleKey key, DbSession session) {
+    QualityProfileDto qDto = profileDao.selectByNameAndLanguage(key.qProfile().name(), key.qProfile().lang(), session);
+    RuleDto ruleDto = ruleDao.getByKey(key.ruleKey(), session);
+    return mapper(session).selectByProfileAndRule(qDto.getId(), ruleDto.getId());
   }
 
   @Override
-  protected ActiveRuleDto doUpdate(ActiveRuleDto item, DbSession session) {
-    getMapper(session).update(item);
-    return setActiveRuleKey(item, session);
+  protected ActiveRuleDto doInsert(ActiveRuleDto item, DbSession session) {
+    Preconditions.checkArgument(item.getProfileId() != null, "Quality profile is not persisted (missing id)");
+    Preconditions.checkArgument(item.getRulId() != null, "Rule is not persisted (missing id)");
+    Preconditions.checkArgument(item.getId() == null, "ActiveRule is already persisted");
+    mapper(session).insert(item);
+    return item;
+  }
+
+  private void fixIdsAndKeys(ActiveRuleDto item, DbSession session) {
+    if (item.getKey() != null) {
+      if (item.getProfileId() == null) {
+        QualityProfileDto profile = profileDao.selectByNameAndLanguage(item.getKey().qProfile().name(), item.getKey().qProfile().lang(), session);
+        // TODO fail if profile not found
+        item.setProfileId(profile.getId());
+      }
+      if (item.getRulId() == null) {
+        RuleDto rule = ruleDao.getByKey(item.getKey().ruleKey(), session);
+        // TODO fail if rule not found
+        item.setRuleId(rule.getId());
+      }
+    } else {
+      // key is null
+      if (item.getProfileId() != null && item.getRulId() != null) {
+        QualityProfileDto profile = profileDao.selectById(item.getProfileId(), session);
+        RuleDto rule = ruleDao.getById(item.getRulId(), session);
+        RuleKey ruleKey = ruleDao.getKey(rule, session);
+        item.setKey(ActiveRuleKey.of(QualityProfileKey.of(profile.getName(), profile.getLanguage()), ruleKey));
+      }
+    }
   }
 
   @Override
-  protected void doDelete(ActiveRuleDto item, DbSession session) {
-    getMapper(session).delete(item.getId());
+  protected ActiveRuleDto doUpdate(ActiveRuleDto item, DbSession session) {
+    Preconditions.checkArgument(item.getProfileId() != null, "Quality profile is not persisted (missing id)");
+    Preconditions.checkArgument(item.getRulId() != null, "Rule is not persisted (missing id)");
+    Preconditions.checkArgument(item.getId() != null, "ActiveRule is not persisted");
+    mapper(session).update(item);
+    return item;
   }
 
   @Override
   protected void doDeleteByKey(ActiveRuleKey key, DbSession session) {
-    throw new NotYetImplementedException("Need to implement ActiveRuleDto.doDeleteByKey() method");
-  }
-
-  /** Helper methods to get the RuleKey and QualityProfileKey -- Temporary */
-
-  private ActiveRuleDto setActiveRuleKey(ActiveRuleDto dto, DbSession session){
-    RuleDto ruleDto = ruleDao.selectById(dto.getRulId(), session);
-    QualityProfileDto qDto = qDao.selectById(dto.getProfileId(), session);
-    if(qDto != null && ruleDto != null) {
-      dto.setKey(QualityProfileKey.of(qDto.getName(), qDto.getLanguage()), ruleDto.getKey());
-    } else {
-      session.close();
-      throw new IllegalStateException("ActiveRule needs to have a valid Key!!!");
-    }
-    return dto;
-  }
-
-  private List<ActiveRuleDto> setActiveRuleKey(List<ActiveRuleDto> dtos, DbSession session){
-    for(ActiveRuleDto dto:dtos) {
-      setActiveRuleKey(dto, session);
-    }
-    return dtos;
-  }
-
-
-  public void delete(int activeRuleId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).delete(activeRuleId);
-  }
-
-  public void delete(int activeRuleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      delete(activeRuleId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void deleteFromRule(int ruleId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteFromRule(ruleId);
-  }
-
-  public void deleteFromRule(int ruleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      deleteFromRule(ruleId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void deleteFromProfile(int profileId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteFromProfile(profileId);
-  }
-
-  public void deleteFromProfile(int profileId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      deleteFromProfile(profileId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleDto> selectByIds(List<Integer> ids) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectByIds(ids, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleDto> selectByIds(Collection<Integer> ids, DbSession session) {
-    if (ids.isEmpty()) {
-      return Collections.emptyList();
-    }
-    List<ActiveRuleDto> dtosList = newArrayList();
-    List<List<Integer>> idsPartitionList = Lists.partition(newArrayList(ids), 1000);
-    for (List<Integer> idsPartition : idsPartitionList) {
-      List<ActiveRuleDto> dtos = session.selectList("org.sonar.core.qualityprofile.db.ActiveRuleMapper.selectByIds", newArrayList(idsPartition));
-      dtosList.addAll(dtos);
-    }
-    return setActiveRuleKey(dtosList, session);
-  }
-
-  public List<ActiveRuleDto> selectAll() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectAll(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleDto> selectAll(DbSession session) {
-    return setActiveRuleKey(session.getMapper(ActiveRuleMapper.class).selectAll(), session);
-  }
-
-  public List<ActiveRuleDto> selectByRuleId(int ruleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectByRuleId(ruleId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleDto> selectByRuleId(int ruleId, DbSession session) {
-    return setActiveRuleKey(session.getMapper(ActiveRuleMapper.class).selectByRuleId(ruleId), session);
-  }
-
-  public List<ActiveRuleDto> selectByProfileId(int profileId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectByProfileId(profileId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleDto> selectByProfileId(int profileId, DbSession session) {
-    return setActiveRuleKey(session.getMapper(ActiveRuleMapper.class).selectByProfileId(profileId), session);
-  }
-
-
-  @CheckForNull
-  public ActiveRuleDto selectById(int id) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectById(id, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  @CheckForNull
-  public ActiveRuleDto selectById(int id, DbSession session) {
-    return setActiveRuleKey(session.getMapper(ActiveRuleMapper.class).selectById(id), session);
-  }
-
-  @CheckForNull
-  public ActiveRuleDto selectByProfileAndRule(int profileId, int ruleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectByProfileAndRule(profileId, ruleId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  @CheckForNull
-  public ActiveRuleDto selectByProfileAndRule(int profileId, int ruleId, DbSession session) {
-    return setActiveRuleKey(session.getMapper(ActiveRuleMapper.class).selectByProfileAndRule(profileId, ruleId), session);
-  }
-
-  public void insert(ActiveRuleParamDto param, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).insertParameter(param);
-    ActiveRuleDto dto = this.selectById(param.getActiveRuleId(), session);
-    if(dto != null) {
-      session.enqueue(new EmbeddedIndexAction<ActiveRuleKey>(this.getIndexType(),
-        IndexAction.Method.UPDATE, param, dto.getKey()));
-    }
-  }
-
-  public void insert(ActiveRuleParamDto dto) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      insert(dto, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void update(ActiveRuleParamDto param, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).updateParameter(param);
-    ActiveRuleDto dto = this.selectById(param.getActiveRuleId(), session);
-    if(dto != null) {
-      session.enqueue(new EmbeddedIndexAction<ActiveRuleKey>(this.getIndexType(),
-        IndexAction.Method.UPDATE, param, dto.getKey()));
-    }
-  }
-
-  public void update(ActiveRuleParamDto dto) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      update(dto, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+    throw new UnsupportedOperationException("TODO");
   }
 
-
-  public void deleteParameter(int activeRuleParamId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteParameter(activeRuleParamId);
+  public List<ActiveRuleParamDto> findParamsByActiveRule(ActiveRuleDto dto, DbSession session) {
+    Preconditions.checkArgument(dto.getId()!=null, "ActiveRule is not persisted");
+    return mapper(session).selectParamsByActiveRuleId(dto.getId());
   }
 
-  public void deleteParameter(int activeRuleParamId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      deleteParameter(activeRuleParamId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
+  public ActiveRuleParamDto addParam(ActiveRuleDto activeRule, ActiveRuleParamDto paramDto, DbSession session) {
+    Preconditions.checkState(activeRule.getId() != null, "ActiveRule id is not yet persisted");
+    Preconditions.checkState(paramDto.getId() == null, "ActiveRuleParam is already persisted");
+    Preconditions.checkState(paramDto.getRulesParameterId() != null, "Rule param is not persisted");
 
-  public void deleteParameters(int activeRuleId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteParameters(activeRuleId);
+    paramDto.setActiveRuleId(activeRule.getId());
+    mapper(session).insertParameter(paramDto);
+    session.enqueue(new EmbeddedIndexAction<ActiveRuleKey>(this.getIndexType(), IndexAction.Method.INSERT, paramDto, activeRule.getKey()));
+    return paramDto;
   }
 
-  public void deleteParameters(int activeRuleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      deleteParameters(activeRuleId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void deleteParametersWithParamId(int id, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteParametersWithParamId(id);
-  }
-
-  public void deleteParametersFromProfile(int profileId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      deleteParametersFromProfile(profileId, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void deleteParametersFromProfile(int profileId, DbSession session) {
-    session.getMapper(ActiveRuleMapper.class).deleteParametersFromProfile(profileId);
-  }
-
-  public ActiveRuleParamDto selectParamById(Integer activeRuleParamId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return session.getMapper(ActiveRuleMapper.class).selectParamById(activeRuleParamId);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public ActiveRuleParamDto selectParamByActiveRuleAndKey(int activeRuleId, String key) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParamByActiveRuleAndKey(activeRuleId, key, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public ActiveRuleParamDto selectParamByActiveRuleAndKey(int activeRuleId, String key, DbSession session) {
-    return session.getMapper(ActiveRuleMapper.class).selectParamByActiveRuleAndKey(activeRuleId, key);
-  }
-
-  public List<ActiveRuleParamDto> selectParamsByActiveRuleId(int activeRuleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParamsByActiveRuleId(activeRuleId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleParamDto> selectParamsByActiveRuleId(int activeRuleId, DbSession session) {
-    return session.getMapper(ActiveRuleMapper.class).selectParamsByActiveRuleId(activeRuleId);
-  }
-
-  public List<ActiveRuleParamDto> selectParamsByActiveRuleIds(List<Integer> activeRuleIds) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParamsByActiveRuleIds(activeRuleIds, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleParamDto> selectParamsByActiveRuleIds(Collection<Integer> activeRuleIds, DbSession session) {
-    if (activeRuleIds.isEmpty()) {
-      return Collections.emptyList();
-    }
-    List<ActiveRuleParamDto> dtosList = newArrayList();
-    List<List<Integer>> idsPartitionList = Lists.partition(newArrayList(activeRuleIds), 1000);
-    for (List<Integer> idsPartition : idsPartitionList) {
-      List<ActiveRuleParamDto> dtos = session.selectList("org.sonar.core.qualityprofile.db.ActiveRuleMapper.selectParamsByActiveRuleIds", newArrayList(idsPartition));
-      dtosList.addAll(dtos);
-    }
-    return dtosList;
-  }
-
-  public List<ActiveRuleParamDto> selectAllParams() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectAllParams(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<ActiveRuleParamDto> selectAllParams(DbSession session) {
-    return session.getMapper(ActiveRuleMapper.class).selectAllParams();
-  }
-
-  public List<ActiveRuleParamDto> selectParamsByProfileId(int profileId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return session.getMapper(ActiveRuleMapper.class).selectParamsByProfileId(profileId);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public List<ActiveRuleDto> findByRule(RuleDto rule, DbSession dbSession) {
+    Preconditions.checkArgument(rule.getId()!=null, "Rule is not persisted");
+    return mapper(dbSession).selectByRuleId(rule.getId());
   }
 }
index 1768262bd765fc22dc1cba5df665f724abfb24c7..93849fecd1083d6dc80f37e0edba905eaa570294 100644 (file)
@@ -21,6 +21,8 @@ package org.sonar.server.rule2;
 
 import org.elasticsearch.action.update.UpdateRequest;
 import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDto;
 import org.sonar.core.qualityprofile.db.ActiveRuleKey;
 import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
@@ -30,7 +32,7 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 
 public class ActiveRuleNormalizer extends BaseNormalizer<ActiveRuleDto, ActiveRuleKey> {
 
-  ActiveRuleDao activeRuleDao;
+  private final ActiveRuleDao activeRuleDao;
 
   public static enum ActiveRuleField {
     OVERRIDE("override"),
@@ -76,13 +78,19 @@ public class ActiveRuleNormalizer extends BaseNormalizer<ActiveRuleDto, ActiveRu
     }
   }
 
-  public ActiveRuleNormalizer(ActiveRuleDao activeRuleDao) {
+  public ActiveRuleNormalizer(MyBatis mybatis, ActiveRuleDao activeRuleDao) {
+    super(mybatis);
     this.activeRuleDao = activeRuleDao;
   }
 
   @Override
   public UpdateRequest normalize(ActiveRuleKey key) {
-    return normalize(activeRuleDao.getByKey(key));
+    DbSession dbSession = getMyBatis().openSession(false);
+    try {
+      return normalize(activeRuleDao.getByKey(key, dbSession));
+    } finally {
+      dbSession.close();
+    }
   }
 
   public UpdateRequest normalize(ActiveRuleParamDto param, ActiveRuleKey key) {
index 2c57f127c764f4e628cee3cacc4b177e2f056557..b7cecd6116e2d4e3a33a95024c2d048adb9a719f 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.rule2;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import org.apache.ibatis.session.ResultContext;
 import org.apache.ibatis.session.ResultHandler;
@@ -26,13 +27,10 @@ import org.sonar.api.BatchComponent;
 import org.sonar.api.ServerComponent;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.core.persistence.DbSession;
-import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleMapper;
 import org.sonar.core.rule.RuleParamDto;
-import org.sonar.core.rule.RuleRuleTagDto;
 import org.sonar.server.db.BaseDao;
-import org.sonar.server.search.DtoIndexAction;
 import org.sonar.server.search.EmbeddedIndexAction;
 import org.sonar.server.search.IndexAction;
 
@@ -42,318 +40,80 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
-import static com.google.common.collect.Lists.newArrayList;
+public class RuleDao extends BaseDao<RuleMapper, RuleDto, RuleKey> implements BatchComponent, ServerComponent {
 
-public class RuleDao extends BaseDao<RuleMapper, RuleDto, RuleKey>
-  implements BatchComponent, ServerComponent {
-
-  public RuleDao(MyBatis mybatis) {
-    super(new RuleIndexDefinition(), RuleMapper.class, mybatis);
+  public RuleDao() {
+    super(new RuleIndexDefinition(), RuleMapper.class);
   }
 
   @CheckForNull
-  protected RuleDto doGetByKey(RuleKey key, DbSession session) {
-    return getMapper(session).selectByKey(key);
+  @Override
+  public RuleDto doGetByKey(RuleKey key, DbSession session) {
+    return mapper(session).selectByKey(key);
   }
 
   @Override
   protected RuleDto doInsert(RuleDto item, DbSession session) {
-    getMapper(session).insert(item);
+    mapper(session).insert(item);
     return item;
   }
 
   @Override
   protected RuleDto doUpdate(RuleDto item, DbSession session) {
-    getMapper(session).update(item);
+    mapper(session).update(item);
     return item;
   }
 
-  @Override
-  protected void doDelete(RuleDto item, DbSession session) {
-    throw new UnsupportedOperationException("Rules cannot be deleted");
-  }
-
   @Override
   protected void doDeleteByKey(RuleKey key, DbSession session) {
     throw new UnsupportedOperationException("Rules cannot be deleted");
   }
 
-  public List<RuleDto> selectAll() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectAll(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<RuleDto> selectAll(DbSession session) {
-    return getMapper(session).selectAll();
-  }
-
-  public List<RuleDto> selectEnablesAndNonManual() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectEnablesAndNonManual(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<RuleDto> selectEnablesAndNonManual(DbSession session) {
-    return getMapper(session).selectEnablesAndNonManual();
-  }
-
-  public List<RuleDto> selectNonManual(DbSession session) {
-    return getMapper(session).selectNonManual();
-  }
-
-  public List<RuleDto> selectBySubCharacteristicId(Integer characteristicOrSubCharacteristicId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectBySubCharacteristicId(characteristicOrSubCharacteristicId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  /**
-   * Return all rules (even the REMOVED ones) linked on to a sub characteristic
-   */
-  public List<RuleDto> selectBySubCharacteristicId(Integer subCharacteristicId, DbSession session) {
-    return getMapper(session).selectBySubCharacteristicId(subCharacteristicId);
-  }
-
-  @CheckForNull
-  public RuleDto selectById(Integer id, DbSession session) {
-    return getMapper(session).selectById(id);
-  }
-
-  @CheckForNull
-  public RuleDto selectById(Integer id) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectById(id, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  @CheckForNull
-  public RuleDto selectByKey(RuleKey ruleKey, DbSession session) {
-    return getMapper(session).selectByKey(ruleKey);
-  }
-
-
-  @CheckForNull
-  public RuleDto selectByKey(RuleKey ruleKey) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectByKey(ruleKey, session);
-    } finally {
-      MyBatis.closeQuietly(session);
+  @Override
+  public RuleKey getKey(RuleDto item, DbSession session) {
+    if (item.getKey() != null) {
+      return item.getKey();
     }
+    return RuleKey.of(item.getRepositoryKey(), item.getRuleKey());
   }
 
   @CheckForNull
-  public RuleDto selectByName(String name) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return getMapper(session).selectByName(name);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  @Deprecated
+  public RuleDto getById(int id, DbSession session) {
+    return mapper(session).selectById(id);
   }
 
-  public void insert(Collection<RuleDto> rules) {
-    DbSession session = mybatis.openSession(true);
-    try {
-      for (RuleDto rule : rules) {
-        session.enqueue(new DtoIndexAction<RuleDto>(this.getIndexType(),
-          IndexAction.Method.INSERT, rule));
-        getMapper(session).batchInsert(rule);
+  @Override
+  public Collection<RuleKey> keysOfRowsUpdatedAfter(long timestamp, DbSession session) {
+    final List<RuleKey> keys = Lists.newArrayList();
+    session.select("selectKeysOfRulesUpdatedSince", new Timestamp(timestamp), new ResultHandler() {
+      @Override
+      public void handleResult(ResultContext context) {
+        Map<String, String> map = (Map) context.getResultObject();
+        keys.add(RuleKey.of(map.get("repo"), map.get("rule")));
       }
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  // ******************************
-  // Methods for Rule Parameters
-  // ******************************
-
-  public List<RuleParamDto> selectParameters() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParameters(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
+    });
+    return keys;
 
-  public List<RuleParamDto> selectParameters(DbSession session) {
-    return getMapper(session).selectAllParams();
   }
 
-  public List<RuleParamDto> selectParametersByRuleId(Integer ruleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParametersByRuleId(ruleId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<RuleParamDto> selectParametersByRuleId(Integer ruleId, DbSession session) {
-    return selectParametersByRuleIds(newArrayList(ruleId));
-  }
-
-  public List<RuleParamDto> selectParametersByRuleIds(List<Integer> ruleIds) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectParametersByRuleIds(ruleIds, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public List<RuleParamDto> selectParametersByRuleIds(List<Integer> ruleIds, DbSession session) {
-    List<RuleParamDto> dtos = newArrayList();
-    List<List<Integer>> partitionList = Lists.partition(newArrayList(ruleIds), 1000);
-    for (List<Integer> partition : partitionList) {
-      dtos.addAll(getMapper(session).selectParamsByRuleIds(partition));
-    }
-    return dtos;
-  }
-
-  public void insert(RuleParamDto param, DbSession session) {
-    getMapper(session).insertParameter(param);
-    RuleDto dto = this.selectById(param.getRuleId(), session);
-    if(dto != null){
-      session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-        IndexAction.Method.INSERT, param,
-        dto.getKey()));
-    }
-  }
-
-  public void insert(RuleParamDto param) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      insert(param, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  public void update(RuleParamDto param, DbSession session) {
-    getMapper(session).updateParameter(param);
-    RuleDto dto = this.selectById(param.getRuleId(), session);
-    if(dto != null) {
-      session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-        IndexAction.Method.UPDATE, param,
-        dto.getKey()));
-    }
-  }
-
-  public void update(RuleParamDto param) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      update(param, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  @CheckForNull
-  public RuleParamDto selectParamByRuleAndKey(Integer ruleId, String key, DbSession session) {
-    return getMapper(session).selectParamByRuleAndKey(ruleId, key);
-  }
-
-  // ***************************
-  // Methods for Rule Tags
-  // ***************************
-
-  public void insert(RuleRuleTagDto newTag, DbSession session) {
-    getMapper(session).insertTag(newTag);
-    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-      IndexAction.Method.INSERT, newTag,
-      this.selectById(newTag.getRuleId(), session).getKey()));
-  }
-
-  public void deleteParam(RuleParamDto persistedParam, DbSession session) {
-    getMapper(session).deleteParameter(persistedParam.getId());
-    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-      IndexAction.Method.DELETE, persistedParam,
-      this.selectById(persistedParam.getRuleId(), session).getKey()));
-  }
-
-  public void deleteTag(RuleRuleTagDto tagToDelete, DbSession session) {
-    getMapper(session).deleteTag(tagToDelete.getId().intValue());
-    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-      IndexAction.Method.DELETE, tagToDelete,
-      this.selectById(tagToDelete.getRuleId(), session).getKey()));
-  }
-
-  public void update(RuleRuleTagDto existingTag, DbSession session) {
-    getMapper(session).updateTag(existingTag);
-    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(),
-      IndexAction.Method.UPDATE, existingTag,
-      this.selectById(existingTag.getRuleId(), session).getKey()));
+  public List<RuleParamDto> findRuleParamsByRuleKey(RuleKey ruleKey, DbSession dbSession) {
+    return mapper(dbSession).selectParamsByRuleKey(ruleKey);
   }
 
-  public List<RuleRuleTagDto> selectTags(DbSession session) {
-    return getMapper(session).selectAllTags();
-  }
-
-  public List<RuleRuleTagDto> selectTagsByRuleId(Integer ruleId) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectTagsByRuleIds(ruleId, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
 
-  public List<RuleRuleTagDto> selectTagsByRuleIds(Integer ruleId, DbSession session) {
-    return selectTagsByRuleIds(newArrayList(ruleId), session);
-  }
 
-  public List<RuleRuleTagDto> selectTagsByRuleIds(List<Integer> ruleIds) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectTagsByRuleIds(ruleIds, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public void addRuleParam(RuleDto rule, RuleParamDto paramDto, DbSession session) {
+    Preconditions.checkNotNull(rule.getId(), "Rule id must be set");
+    paramDto.setRuleId(rule.getId());
+    mapper(session).insertParameter(paramDto);
+    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(), IndexAction.Method.INSERT, paramDto, rule.getKey()));
   }
 
-  public List<RuleRuleTagDto> selectTagsByRuleIds(List<Integer> ruleIds, DbSession session) {
-    List<RuleRuleTagDto> dtos = newArrayList();
-    List<List<Integer>> partitionList = Lists.partition(newArrayList(ruleIds), 1000);
-    for (List<Integer> partition : partitionList) {
-      dtos.addAll(getMapper(session).selectTagsByRuleIds(partition));
-    }
-    return dtos;
-  }
-
-  @Override
-  public Collection<RuleKey> keysOfRowsUpdatedAfter(long timestamp) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      final List<RuleKey> keys = Lists.newArrayList();
-      session.select("selectKeysOfRulesUpdatedSince", new Timestamp(timestamp), new ResultHandler() {
-        @Override
-        public void handleResult(ResultContext context) {
-          Map<String, String> map = (Map) context.getResultObject();
-          keys.add(RuleKey.of(map.get("repo"), map.get("rule")));
-        }
-      });
-      return keys;
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public void updateRuleParam(RuleDto rule, RuleParamDto paramDto, DbSession session) {
+    Preconditions.checkNotNull(rule.getId(), "Rule id must be set");
+    paramDto.setRuleId(rule.getId());
+    mapper(session).updateParameter(paramDto);
+    session.enqueue(new EmbeddedIndexAction<RuleKey>(this.getIndexType(), IndexAction.Method.UPDATE, paramDto, rule.getKey()));
   }
 }
index 5aa1ec9500ac48aa312727054d88f5cd3709a094..65ccbe111535afac0b04356184696954d786dfbe 100644 (file)
@@ -23,6 +23,8 @@ import org.elasticsearch.action.update.UpdateRequest;
 import org.elasticsearch.common.xcontent.XContentBuilder;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.check.Cardinality;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleParamDto;
 import org.sonar.core.rule.RuleRuleTagDto;
@@ -90,13 +92,19 @@ public class RuleNormalizer extends BaseNormalizer<RuleDto, RuleKey> {
     }
   }
 
-  public RuleNormalizer(RuleDao ruleDao) {
+  public RuleNormalizer(MyBatis myBatis, RuleDao ruleDao) {
+    super(myBatis);
     this.ruleDao = ruleDao;
   }
 
   @Override
   public UpdateRequest normalize(RuleKey key) {
-    return normalize(ruleDao.getByKey(key));
+    DbSession dbSession = getMyBatis().openSession(false);
+    try {
+      return normalize(ruleDao.getByKey(key, dbSession));
+    } finally {
+      dbSession.close();
+    }
   }
 
   @Override
index 067d4de375ba25f7a313af350b90a722b9cfc2cd..84d4c1de835a498a5f39542ec156fff17b58c935 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.rule2;
 import org.sonar.api.ServerComponent;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.core.rule.RuleDao;
+import org.sonar.server.search.Hit;
 import org.sonar.server.search.QueryOptions;
 import org.sonar.server.search.Result;
 
@@ -33,11 +34,9 @@ import java.util.List;
  */
 public class RuleService implements ServerComponent {
 
-  private RuleDao dao;
   private RuleIndex index;
 
-  public RuleService(RuleDao dao, RuleIndex index) {
-    this.dao = dao;
+  public RuleService(RuleIndex index) {
     this.index = index;
   }
 
@@ -68,7 +67,7 @@ public class RuleService implements ServerComponent {
     throw new UnsupportedOperationException("TODO");
   }
 
-  public RuleService refresh(){
+  public RuleService refresh() {
     this.index.refresh();
     return this;
   }
index 12680137ec7735a0ea0d72d950cb639be6acc492..4b9329467b5e402b77e7700411c304e672c6f550 100644 (file)
@@ -24,12 +24,23 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.core.db.Dto;
+import org.sonar.core.persistence.MyBatis;
 
 import java.io.IOException;
 import java.io.Serializable;
 
 public abstract class BaseNormalizer<E extends Dto<K>, K extends Serializable> {
 
+  private MyBatis myBatis;
+
+  protected BaseNormalizer(MyBatis mybatis) {
+    this.myBatis = mybatis;
+  }
+
+  protected MyBatis getMyBatis() {
+    return myBatis;
+  }
+
   public boolean canNormalize(Class<?> objectClass, Class<?> keyClass) {
     try {
       return this.getClass().getMethod("normalize", objectClass, keyClass) != null;
@@ -61,4 +72,40 @@ public abstract class BaseNormalizer<E extends Dto<K>, K extends Serializable> {
       LOG.error("Could not set {} to {} in ESDocument", field, value);
     }
   }
+
+
+//  protected void indexField(Fields field, Object dto, XContentBuilder document) {
+//    try {
+//      document.field(field.key(), field.method.invoke(dto));
+//    } catch (IllegalArgumentException e) {
+//      // TODO Auto-generated catch block
+//      e.printStackTrace();
+//    } catch (IOException e) {
+//      // TODO Auto-generated catch block
+//      e.printStackTrace();
+//    } catch (IllegalAccessException e) {
+//      // TODO Auto-generated catch block
+//      e.printStackTrace();
+//    } catch (InvocationTargetException e) {
+//      // TODO Auto-generated catch block
+//      e.printStackTrace();
+//    }
+//  }
+//
+//
+//
+//private static Method getReadMethod(String method){
+//  try {
+//    return RuleDto.class.getDeclaredMethod(method);
+//  } catch (SecurityException e) {
+//    // TODO Auto-generated catch block
+//    e.printStackTrace();
+//  } catch (NoSuchMethodException e) {
+//    // TODO Auto-generated catch block
+//    e.printStackTrace();
+//  }
+//  return null;
+//}
+
+
 }
index 492eee5db673ea8360ff09f9a92d296913debe6c..0cdda8eb9749e06306ea5dd3e767328cb2ab7580 100644 (file)
@@ -42,17 +42,17 @@ public class IndexSynchronizer<K extends Serializable> {
 
   public IndexSynchronizer<K> start() {
 
-    LOG.info("Starting synchronization thread for ", index.getClass().getSimpleName());
-
-    Long since = index.getLastSynchronization();
-    index.setLastSynchronization(System.currentTimeMillis());
-
-    for (K key : dao.keysOfRowsUpdatedAfter(since)) {
-      if (LOG.isTraceEnabled()) {
-        LOG.trace("Adding {} to workQueue for {}", key, index.getClass().getSimpleName());
-      }
-      workQueue.enqueue(new KeyIndexAction<K>(index.getIndexName(), IndexAction.Method.INSERT, key));
-    }
+//    LOG.info("Starting synchronization thread for ", index.getClass().getSimpleName());
+//
+//    Long since = index.getLastSynchronization();
+//    index.setLastSynchronization(System.currentTimeMillis());
+//
+//    for (K key : dao.keysOfRowsUpdatedAfter(since)) {
+//      if (LOG.isTraceEnabled()) {
+//        LOG.trace("Adding {} to workQueue for {}", key, index.getClass().getSimpleName());
+//      }
+//      workQueue.enqueue(new KeyIndexAction<K>(index.getIndexName(), IndexAction.Method.INSERT, key));
+//    }
 
     return this;
   }
index 0c66654af1ec212491332516c81e8e7c1ca841c7..5426970eef9cc5aff07d6cf6fc4840aede6b36b9 100644 (file)
@@ -25,9 +25,9 @@ import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.runners.MockitoJUnitRunner;
+import org.sonar.server.qualityprofile.ActiveRuleService;
 import org.sonar.server.qualityprofile.QProfileBackup;
 import org.sonar.server.qualityprofile.QProfileResult;
-import org.sonar.server.qualityprofile.RuleActivationService;
 import org.sonar.server.ws.WsTester;
 
 import static com.google.common.collect.Lists.newArrayList;
@@ -46,7 +46,7 @@ public class QProfileRecreateBuiltInActionTest {
   public void setUp() throws Exception {
     tester = new WsTester(new QProfilesWs(
       new QProfileRecreateBuiltInAction(qProfileBackup),
-      new ActivateRuleAction(mock(RuleActivationService.class))));
+      new ActivateRuleAction(mock(ActiveRuleService.class))));
   }
 
   @Test
index d9d3feefd9b5bfcb753732d36c7f94b1cb68b9be..8bb83cb94513987c658f0d16a44ff7b6cef9151b 100644 (file)
@@ -23,8 +23,8 @@ package org.sonar.server.qualityprofile.ws;
 import org.junit.Before;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
+import org.sonar.server.qualityprofile.ActiveRuleService;
 import org.sonar.server.qualityprofile.QProfileBackup;
-import org.sonar.server.qualityprofile.RuleActivationService;
 import org.sonar.server.ws.WsTester;
 
 import static org.fest.assertions.Assertions.assertThat;
@@ -36,7 +36,7 @@ public class QProfilesWsTest {
 
   @Before
   public void setUp() {
-    controller = new WsTester(new QProfilesWs(new QProfileRecreateBuiltInAction(mock(QProfileBackup.class)), new ActivateRuleAction(mock(RuleActivationService.class))))
+    controller = new WsTester(new QProfilesWs(new QProfileRecreateBuiltInAction(mock(QProfileBackup.class)), new ActivateRuleAction(mock(ActiveRuleService.class))))
       .controller("api/qualityprofiles");
   }
 
index 9de7e55d24a6709491d9045856ede481b2f3e923..47c5d8aac165193631e4ead244e6176650179d8b 100644 (file)
@@ -38,7 +38,7 @@ import org.sonar.core.cluster.WorkQueue;
 import org.sonar.core.persistence.AbstractDaoTestCase;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.qualityprofile.db.ActiveRuleDao;
-import org.sonar.server.rule2.RuleDao;
+import org.sonar.core.rule.RuleDao;
 import org.sonar.core.rule.RuleDto;
 import org.sonar.core.rule.RuleTagDao;
 import org.sonar.core.rule.RuleTagDto;
diff --git a/sonar-server/src/test/java/org/sonar/server/rule2/ActiveRuleDaoTest.java b/sonar-server/src/test/java/org/sonar/server/rule2/ActiveRuleDaoTest.java
deleted file mode 100644 (file)
index 0224658..0000000
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 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.rule2;
-
-import com.google.common.base.Predicate;
-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.RuleKey;
-import org.sonar.api.rule.Severity;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-import org.sonar.core.qualityprofile.db.ActiveRuleDto;
-import org.sonar.core.qualityprofile.db.ActiveRuleKey;
-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.qualityprofile.db.QualityProfileKey;
-import org.sonar.core.rule.RuleDto;
-
-import java.util.List;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class ActiveRuleDaoTest extends AbstractDaoTestCase {
-
-  ActiveRuleDao dao;
-  RuleDao ruleDao;
-  QualityProfileDao qDao;
-
-  @Before
-  public void createDao() {
-
-    ruleDao = new RuleDao(getMyBatis());
-    qDao = new QualityProfileDao(getMyBatis());
-    dao = new ActiveRuleDao(getMyBatis(), qDao, ruleDao);
-  }
-
-  @Test
-  public void insert() {
-    setupData("empty");
-
-    ActiveRuleDto dto = new ActiveRuleDto()
-      .setProfileId(1)
-      .setRuleId(10)
-      .setSeverity(Severity.MAJOR)
-      .setInheritance("INHERITED");
-
-    dao.insert(dto);
-
-    checkTables("insert", "active_rules");
-  }
-
-  @Test
-  public void update() {
-    setupData("shared");
-
-    ActiveRuleDto dto = new ActiveRuleDto()
-      .setId(1)
-      .setProfileId(1)
-      .setRuleId(10)
-      .setSeverity(Severity.BLOCKER)
-      .setInheritance(null)
-      .setNoteData("text");
-
-    dao.update(dto);
-
-    checkTables("update", "active_rules");
-  }
-
-  @Test
-  public void delete() {
-    setupData("shared");
-
-    dao.delete(1);
-
-    checkTables("delete", "active_rules");
-  }
-
-  @Test
-  public void delete_from_rule() {
-    setupData("shared");
-
-    dao.deleteFromRule(11);
-
-    checkTables("delete_from_rule", "active_rules");
-  }
-
-  @Test
-  public void delete_from_profile() {
-    setupData("shared");
-
-    dao.deleteFromProfile(2);
-
-    checkTables("delete_from_profile", "active_rules");
-  }
-
-  @Test
-  public void select_by_id() {
-    setupData("shared");
-
-    ActiveRuleDto result = dao.selectById(1);
-    assertThat(result.getId()).isEqualTo(1);
-    assertThat(result.getProfileId()).isEqualTo(1);
-    assertThat(result.getRulId()).isEqualTo(10);
-    assertThat(result.getSeverityString()).isEqualTo(Severity.MAJOR);
-    assertThat(result.getInheritance()).isEqualTo("INHERITED");
-    assertThat(result.getNoteData()).isEqualTo("some note");
-    assertThat(result.getNoteUserLogin()).isEqualTo("henry");
-    assertThat(result.getNoteCreatedAt()).isEqualTo(DateUtils.parseDate("2013-12-18"));
-    assertThat(result.getNoteUpdatedAt()).isEqualTo(DateUtils.parseDate("2013-12-18"));
-  }
-
-  @Test
-  public void select_by_ids() {
-    setupData("shared");
-
-    List<ActiveRuleDto> result = dao.selectByIds(ImmutableList.of(1));
-    assertThat(result).hasSize(1);
-    assertThat(result.get(0).getParentId()).isEqualTo(2);
-
-    assertThat(dao.selectByIds(ImmutableList.of(1, 2))).hasSize(2);
-  }
-
-  @Test
-  public void select_by_profile_and_rule() {
-    setupData("shared");
-
-    ActiveRuleDto result = dao.selectByProfileAndRule(1, 10);
-    assertThat(result.getId()).isEqualTo(1);
-    assertThat(result.getProfileId()).isEqualTo(1);
-    assertThat(result.getRulId()).isEqualTo(10);
-    assertThat(result.getSeverityString()).isEqualTo(Severity.MAJOR);
-    assertThat(result.getInheritance()).isEqualTo("INHERITED");
-    assertThat(result.getNoteData()).isEqualTo("some note");
-    assertThat(result.getNoteUserLogin()).isEqualTo("henry");
-    assertThat(result.getNoteCreatedAt()).isEqualTo(DateUtils.parseDate("2013-12-18"));
-    assertThat(result.getNoteUpdatedAt()).isEqualTo(DateUtils.parseDate("2013-12-18"));
-  }
-
-  @Test
-  public void select_by_rule() {
-    setupData("shared");
-
-    List<ActiveRuleDto> result = dao.selectByRuleId(10);
-    assertThat(result).hasSize(2);
-  }
-
-  @Test
-  public void select_by_profile() {
-    setupData("shared");
-
-    List<ActiveRuleDto> result = dao.selectByProfileId(2);
-    assertThat(result).hasSize(2);
-  }
-
-  @Test
-  public void select_all() {
-    setupData("shared");
-
-    List<ActiveRuleDto> result = dao.selectAll();
-    assertThat(result).hasSize(3);
-
-    assertThat(find(1, result).getParentId()).isEqualTo(2);
-    assertThat(find(2, result).getParentId()).isNull();
-  }
-
-  @Test
-  public void insert_parameter() {
-    setupData("insert_parameter");
-
-    ActiveRuleParamDto dto = new ActiveRuleParamDto()
-      .setActiveRuleId(1)
-      .setRulesParameterId(1)
-      .setKey("max")
-      .setValue("20");
-
-    dao.insert(dto);
-
-    checkTables("insert_parameter", "active_rule_parameters");
-  }
-
-  @Test
-  public void update_parameter() {
-    setupData("shared");
-
-    ActiveRuleParamDto dto = new ActiveRuleParamDto()
-      .setId(1)
-      .setActiveRuleId(2)
-      .setRulesParameterId(3)
-      .setKey("newMax")
-      .setValue("30");
-
-    dao.update(dto);
-
-    checkTables("update_parameter", "active_rule_parameters");
-  }
-
-  @Test
-  public void delete_parameters() {
-    setupData("shared");
-
-    dao.deleteParameters(1);
-
-    checkTables("delete_parameters", "active_rule_parameters");
-  }
-
-  @Test
-  public void delete_parameter() {
-    setupData("shared");
-
-    dao.deleteParameter(1);
-
-    checkTables("delete_parameter", "active_rule_parameters");
-  }
-
-  @Test
-  public void delete_parameters_from_profile_id() {
-    setupData("delete_parameters_from_profile_id");
-
-    dao.deleteParametersFromProfile(2);
-
-    checkTables("delete_parameters_from_profile_id", "active_rule_parameters");
-  }
-
-  @Test
-  public void select_param_by_id() {
-    setupData("shared");
-
-    ActiveRuleParamDto result = dao.selectParamById(1);
-    assertThat(result.getId()).isEqualTo(1);
-    assertThat(result.getActiveRuleId()).isEqualTo(1);
-    assertThat(result.getRulesParameterId()).isEqualTo(1);
-    assertThat(result.getKey()).isEqualTo("max");
-    assertThat(result.getValue()).isEqualTo("20");
-  }
-
-  @Test
-  public void select_params_by_active_rule_id() {
-    setupData("shared");
-
-    assertThat(dao.selectParamsByActiveRuleId(1)).hasSize(2);
-    assertThat(dao.selectParamsByActiveRuleId(2)).hasSize(1);
-  }
-
-  @Test
-  public void select_param_by_active_rule_and_key() {
-    setupData("shared");
-
-    ActiveRuleParamDto result = dao.selectParamByActiveRuleAndKey(1, "max");
-    assertThat(result.getId()).isEqualTo(1);
-    assertThat(result.getActiveRuleId()).isEqualTo(1);
-    assertThat(result.getRulesParameterId()).isEqualTo(1);
-    assertThat(result.getKey()).isEqualTo("max");
-    assertThat(result.getValue()).isEqualTo("20");
-  }
-
-  @Test
-  public void select_params_by_active_rule_ids() {
-    setupData("shared");
-
-    assertThat(dao.selectParamsByActiveRuleIds(ImmutableList.of(1))).hasSize(2);
-    assertThat(dao.selectParamsByActiveRuleIds(ImmutableList.of(2))).hasSize(1);
-    assertThat(dao.selectParamsByActiveRuleIds(ImmutableList.of(1, 2))).hasSize(3);
-  }
-
-  @Test
-  public void select_params_by_profile_id() {
-    setupData("shared");
-
-    assertThat(dao.selectParamsByProfileId(1)).hasSize(2);
-  }
-
-  @Test
-  public void select_all_params() {
-    setupData("shared");
-
-    assertThat(dao.selectAllParams()).hasSize(3);
-  }
-
-  @Test
-  public void get_activeRuleKey() {
-    QualityProfileDto qdto = new QualityProfileDto()
-      .setName("name")
-      .setLanguage("lang");
-    qDao.insert(qdto);
-
-    RuleDto rdto = new RuleDto()
-      .setRuleKey("ruleKey")
-      .setRepositoryKey("repositoryKey");
-    ruleDao.insert(rdto);
-
-    ActiveRuleDto dto = new ActiveRuleDto()
-      .setProfileId(qdto.getId())
-      .setRuleId(rdto.getId())
-      .setSeverity(Severity.BLOCKER)
-      .setInheritance(null)
-      .setNoteData("text");
-    dao.insert(dto);
-
-    assertThat(dto.getKey()).isNotNull();
-
-    assertThat(dto.getKey().ruleKey()).isNotNull();
-    assertThat(dto.getKey().ruleKey().rule()).isEqualTo(rdto.getRuleKey());
-    assertThat(dto.getKey().ruleKey().repository()).isEqualTo(rdto.getRepositoryKey());
-
-    assertThat(dto.getKey().qProfile()).isNotNull();
-    assertThat(dto.getKey().qProfile().name()).isEqualTo(qdto.getName());
-    assertThat(dto.getKey().qProfile().lang()).isEqualTo(qdto.getLanguage());
-  }
-
-  @Test
-  public void select_by_activeRuleKey() {
-    QualityProfileDto qdto = new QualityProfileDto()
-      .setName("name")
-      .setLanguage("lang");
-    qDao.insert(qdto);
-
-    RuleDto rdto = new RuleDto()
-      .setRuleKey("ruleKey")
-      .setRepositoryKey("repositoryKey");
-    ruleDao.insert(rdto);
-
-    ActiveRuleDto dto = new ActiveRuleDto()
-      .setProfileId(qdto.getId())
-      .setRuleId(rdto.getId())
-      .setSeverity(Severity.BLOCKER)
-      .setInheritance(null)
-      .setNoteData("text");
-    dao.insert(dto);
-
-
-    ActiveRuleDto newDto = dao.getByKey(ActiveRuleKey.of(QualityProfileKey.of(qdto.getName(), qdto.getLanguage()),
-      RuleKey.of(rdto.getRepositoryKey(), rdto.getRuleKey())));
-
-    assertThat(newDto.getKey()).isNotNull();
-
-    assertThat(newDto.getKey().ruleKey()).isNotNull();
-    assertThat(newDto.getKey().ruleKey().rule()).isEqualTo(rdto.getRuleKey());
-    assertThat(newDto.getKey().ruleKey().repository()).isEqualTo(rdto.getRepositoryKey());
-
-    assertThat(newDto.getKey().qProfile()).isNotNull();
-    assertThat(newDto.getKey().qProfile().name()).isEqualTo(qdto.getName());
-    assertThat(newDto.getKey().qProfile().lang()).isEqualTo(qdto.getLanguage());
-
-    assertThat(newDto.getSeverityString()).isEqualTo(dto.getSeverityString());
-    assertThat(newDto.getNoteData()).isEqualTo(dto.getNoteData());
-  }
-
-
-
-  private ActiveRuleDto find(final Integer id, List<ActiveRuleDto> dtos){
-    return Iterables.find(dtos, new Predicate<ActiveRuleDto>(){
-      @Override
-      public boolean apply(ActiveRuleDto input) {
-        return input.getId().equals(id);
-      }
-    });
-  }
-
-}
index 5285ac3b022f1319a3f95884658563fa3d039ed7..537a21e178c2c470333be7c3f163ddb1648b2704 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.rule2;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Test;
@@ -46,22 +47,26 @@ public class ActiveRuleIndexMediumTest {
   @ClassRule
   public static ServerTester tester = new ServerTester();
 
-  RuleDao dao = tester.get(RuleDao.class);
-
+  MyBatis myBatis = tester.get(MyBatis.class);
   QualityProfileDao qualityProfileDao = tester.get(QualityProfileDao.class);
-
+  ActiveRuleDao activeRuleDao = tester.get(ActiveRuleDao.class);
+  RuleDao dao = tester.get(RuleDao.class);
   RuleIndex index = tester.get(RuleIndex.class);
+  DbSession dbSession;
 
   @Before
-  public void clear_data_store() {
+  public void before() {
     tester.clearDataStores();
+    dbSession = myBatis.openSession(false);
+  }
+
+  @After
+  public void after() {
+    dbSession.close();
   }
 
   @Test
   public void insert_and_index_activeRules() throws InterruptedException {
-    DbSession dbSession = tester.get(MyBatis.class).openSession(false);
-    ActiveRuleDao activeRuleDao = tester.get(ActiveRuleDao.class);
-
     QualityProfileDto profileDto = new QualityProfileDto()
       .setName("myprofile")
       .setLanguage("java");
@@ -71,21 +76,16 @@ public class ActiveRuleIndexMediumTest {
     RuleKey ruleKey = RuleKey.of("javascript", "S001");
     RuleDto ruleDto = newRuleDto(ruleKey);
     dao.insert(ruleDto, dbSession);
-    dbSession.commit();
 
-    ActiveRuleDto activeRule = new ActiveRuleDto()
+    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profileDto, ruleDto)
       .setInheritance("inherited")
-      .setProfileId(profileDto.getId())
-      .setRuleId(ruleDto.getId())
       .setSeverity(Severity.BLOCKER);
 
     activeRuleDao.insert(activeRule, dbSession);
     dbSession.commit();
 
-    dbSession.close();
-
     // verify that activeRules are persisted in db
-    List<ActiveRuleDto> persistedDtos = activeRuleDao.selectByRuleId(ruleDto.getId());
+    List<ActiveRuleDto> persistedDtos = activeRuleDao.findByRule(ruleDto, dbSession);
     assertThat(persistedDtos).hasSize(1);
 
     // verify that activeRules are indexed in es
@@ -102,9 +102,6 @@ public class ActiveRuleIndexMediumTest {
 
   @Test
   public void insert_and_index_activeRuleParams() throws InterruptedException {
-    DbSession dbSession = tester.get(MyBatis.class).openSession(false);
-    ActiveRuleDao activeRuleDao = tester.get(ActiveRuleDao.class);
-
     QualityProfileDto profileDto = new QualityProfileDto()
       .setName("myprofile")
       .setLanguage("java");
@@ -116,44 +113,33 @@ public class ActiveRuleIndexMediumTest {
     dao.insert(ruleDto, dbSession);
 
     RuleParamDto minParam = new RuleParamDto()
-      .setRuleId(ruleDto.getId())
       .setName("min")
       .setType("STRING");
-    dao.insert(minParam, dbSession);
+    dao.addRuleParam(ruleDto, minParam, dbSession);
 
     RuleParamDto maxParam = new RuleParamDto()
-      .setRuleId(ruleDto.getId())
       .setName("max")
       .setType("STRING");
-    dao.insert(maxParam, dbSession);
+    dao.addRuleParam(ruleDto, maxParam, dbSession);
 
 
-    ActiveRuleDto activeRule = new ActiveRuleDto()
+    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profileDto, ruleDto)
       .setInheritance("inherited")
-      .setProfileId(profileDto.getId())
-      .setRuleId(ruleDto.getId())
       .setSeverity(Severity.BLOCKER);
     activeRuleDao.insert(activeRule, dbSession);
 
-    ActiveRuleParamDto activeRuleMinParam = new ActiveRuleParamDto()
-      .setActiveRuleId(activeRule.getId())
-      .setKey(minParam.getName())
-      .setValue("minimum")
-      .setRulesParameterId(minParam.getId());
-    activeRuleDao.insert(activeRuleMinParam, dbSession);
+    ActiveRuleParamDto activeRuleMinParam = ActiveRuleParamDto.createFor(minParam)
+      .setValue("minimum");
+    activeRuleDao.addParam(activeRule, activeRuleMinParam, dbSession);
 
-    ActiveRuleParamDto activeRuleMaxParam = new ActiveRuleParamDto()
-      .setActiveRuleId(activeRule.getId())
-      .setKey(maxParam.getName())
-      .setValue("maximum")
-      .setRulesParameterId(maxParam.getId());
-    activeRuleDao.insert(activeRuleMaxParam, dbSession);
+    ActiveRuleParamDto activeRuleMaxParam = ActiveRuleParamDto.createFor(maxParam)
+      .setValue("maximum");
+    activeRuleDao.addParam(activeRule, activeRuleMaxParam, dbSession);
 
     dbSession.commit();
-    dbSession.close();
 
     // verify that activeRulesParams are persisted in db
-    List<ActiveRuleParamDto> persistedDtos = activeRuleDao.selectParamsByActiveRuleId(activeRule.getId());
+    List<ActiveRuleParamDto> persistedDtos = activeRuleDao.findParamsByActiveRule(activeRule, dbSession);
     assertThat(persistedDtos).hasSize(2);
 
     // verify that activeRulesParams are indexed in es
index 036a99769438777216cec9e4d8b5f4db58903a00..84baa4c4221742014597f21ce3bee80b822cb383 100644 (file)
  */
 package org.sonar.server.rule2;
 
-import com.google.common.base.Function;
-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.RuleKey;
-import org.sonar.api.rule.Severity;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.check.Cardinality;
 import org.sonar.core.persistence.AbstractDaoTestCase;
-import org.sonar.core.persistence.DbSession;
-import org.sonar.core.rule.RuleDto;
-import org.sonar.core.rule.RuleParamDto;
-
-import java.util.Arrays;
-import java.util.List;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static org.fest.assertions.Assertions.assertThat;
 
 public class RuleDaoTest extends AbstractDaoTestCase {
 
-  private static RuleDao dao;
-
-  @Before
-  public void createDao() throws Exception {
-    dao = new RuleDao(getMyBatis());
-  }
-
-  @Test
-  public void select_all() throws Exception {
-    setupData("selectAll");
-    List<RuleDto> ruleDtos = dao.selectAll();
-
-    assertThat(ruleDtos).hasSize(1);
-
-    RuleDto ruleDto = ruleDtos.get(0);
-    assertThat(ruleDto.getId()).isEqualTo(1);
-    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
-    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
-    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
-    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
-    assertThat(ruleDto.getNoteData()).isEqualTo("Rule note with accents \u00e9\u00e8\u00e0");
-    assertThat(ruleDto.getSubCharacteristicId()).isEqualTo(100);
-    assertThat(ruleDto.getDefaultSubCharacteristicId()).isEqualTo(101);
-    assertThat(ruleDto.getRemediationFunction()).isEqualTo("linear");
-    assertThat(ruleDto.getDefaultRemediationFunction()).isEqualTo("linear_offset");
-    assertThat(ruleDto.getRemediationCoefficient()).isEqualTo("1h");
-    assertThat(ruleDto.getDefaultRemediationCoefficient()).isEqualTo("5d");
-    assertThat(ruleDto.getRemediationOffset()).isEqualTo("5min");
-    assertThat(ruleDto.getDefaultRemediationOffset()).isEqualTo("10h");
-    assertThat(ruleDto.getEffortToFixDescription()).isEqualTo("squid.S115.effortToFix");
-  }
-
-  @Test
-  public void select_enables_and_non_manual() throws Exception {
-    setupData("select_enables_and_non_manual");
-    List<RuleDto> ruleDtos = dao.selectEnablesAndNonManual();
-
-    assertThat(ruleDtos.size()).isEqualTo(1);
-    RuleDto ruleDto = ruleDtos.get(0);
-    assertThat(ruleDto.getId()).isEqualTo(1);
-    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
-    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
-    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
-    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
-    assertThat(ruleDto.getNoteData()).isEqualTo("Rule note with accents \u00e9\u00e8\u00e0");
-    assertThat(ruleDto.getSubCharacteristicId()).isEqualTo(100);
-    assertThat(ruleDto.getDefaultSubCharacteristicId()).isEqualTo(101);
-    assertThat(ruleDto.getRemediationFunction()).isEqualTo("LINEAR");
-    assertThat(ruleDto.getDefaultRemediationFunction()).isEqualTo("LINEAR_OFFSET");
-    assertThat(ruleDto.getRemediationCoefficient()).isEqualTo("1h");
-    assertThat(ruleDto.getDefaultRemediationCoefficient()).isEqualTo("5d");
-    assertThat(ruleDto.getRemediationOffset()).isEqualTo("5min");
-    assertThat(ruleDto.getDefaultRemediationOffset()).isEqualTo("10h");
-    assertThat(ruleDto.getEffortToFixDescription()).isEqualTo("squid.S115.effortToFix");
-  }
-
-  @Test
-  public void select_by_id() throws Exception {
-    setupData("selectById");
-    RuleDto ruleDto = dao.selectById(2);
-
-    assertThat(ruleDto.getId()).isEqualTo(2);
-    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
-    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
-    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
-    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
-  }
-
-  @Test
-  public void select_by_rule_key() throws Exception {
-    setupData("select_by_rule_key");
-    assertThat(dao.selectByKey(RuleKey.of("checkstyle", "AvoidComparison"))).isNotNull();
-    assertThat(dao.selectByKey(RuleKey.of("checkstyle", "Unknown"))).isNull();
-    assertThat(dao.selectByKey(RuleKey.of("Unknown", "AvoidComparison"))).isNull();
-  }
-
-  @Test
-  public void select_by_name() throws Exception {
-    setupData("select_by_name");
-    RuleDto ruleDto = dao.selectByName("Avoid Null");
-
-    assertThat(ruleDto.getId()).isEqualTo(2);
-    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
-    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
-    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
-    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
-  }
-
-  @Test
-  public void select_non_manual() throws Exception {
-    setupData("selectNonManual");
-    DbSession session = getMyBatis().openSession(false);
-    List<RuleDto> ruleDtos = dao.selectNonManual(session);
-    session.commit();
-    session.close();
-
-    assertThat(ruleDtos.size()).isEqualTo(1);
-    RuleDto ruleDto = ruleDtos.get(0);
-    assertThat(ruleDto.getId()).isEqualTo(1);
-    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
-    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
-    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
-    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
-  }
-
-  @Test
-  public void select_by_sub_characteristic_id(){
-    setupData("select_by_sub_characteristic_id");
-
-    // Rules from sub characteristic (even REMOVED ones are returned)
-    List<RuleDto> ruleDtos = dao.selectBySubCharacteristicId(3);
-    assertThat(ruleDtos).hasSize(3);
-    assertThat(idsFromRuleDtos(ruleDtos)).containsExactly(2, 4, 5);
-
-    // Nothing on root characteristic
-    ruleDtos = dao.selectBySubCharacteristicId(1);
-    assertThat(ruleDtos).isEmpty();
-
-    // Rules from disabled characteristic
-    ruleDtos = dao.selectBySubCharacteristicId(11);
-    assertThat(idsFromRuleDtos(ruleDtos)).containsExactly(3);
-  }
-
-  @Test
-  public void update() {
-    setupData("update");
-
-    RuleDto ruleToUpdate = new RuleDto()
-      .setId(1)
-      .setRuleKey("NewRuleKey")
-      .setRepositoryKey("plugin")
-      .setName("new name")
-      .setDescription("new description")
-      .setStatus(Rule.STATUS_DEPRECATED)
-      .setConfigKey("NewConfigKey")
-      .setSeverity(Severity.INFO)
-      .setCardinality(Cardinality.MULTIPLE)
-      .setLanguage("dart")
-      .setParentId(3)
-      .setNoteData("My note")
-      .setNoteUserLogin("admin")
-      .setNoteCreatedAt(DateUtils.parseDate("2013-12-19"))
-      .setNoteUpdatedAt(DateUtils.parseDate("2013-12-20"))
-      .setSubCharacteristicId(100)
-      .setDefaultSubCharacteristicId(101)
-      .setRemediationFunction("linear")
-      .setDefaultRemediationFunction("linear_offset")
-      .setRemediationCoefficient("1h")
-      .setDefaultRemediationCoefficient("5d")
-      .setRemediationOffset("5min")
-      .setDefaultRemediationOffset("10h")
-      .setEffortToFixDescription("squid.S115.effortToFix")
-      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
-
-    dao.update(ruleToUpdate);
-
-    checkTables("update", "rules");
-  }
-
-  @Test
-  public void insert() {
-    setupData("empty");
-
-    RuleDto ruleToInsert = new RuleDto()
-      .setId(1)
-      .setRuleKey("NewRuleKey")
-      .setRepositoryKey("plugin")
-      .setName("new name")
-      .setDescription("new description")
-      .setStatus(Rule.STATUS_DEPRECATED)
-      .setConfigKey("NewConfigKey")
-      .setSeverity(Severity.INFO)
-      .setCardinality(Cardinality.MULTIPLE)
-      .setLanguage("dart")
-      .setParentId(3)
-      .setSubCharacteristicId(100)
-      .setDefaultSubCharacteristicId(101)
-      .setRemediationFunction("linear")
-      .setDefaultRemediationFunction("linear_offset")
-      .setRemediationCoefficient("1h")
-      .setDefaultRemediationCoefficient("5d")
-      .setRemediationOffset("5min")
-      .setDefaultRemediationOffset("10h")
-      .setEffortToFixDescription("squid.S115.effortToFix")
-      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
-      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
-
-    dao.insert(ruleToInsert);
-
-    checkTables("insert", "rules");
-  }
-
-  @Test
-  public void insert_all() {
-    setupData("empty");
-
-    RuleDto ruleToInsert1 = new RuleDto()
-      .setId(1)
-      .setRuleKey("NewRuleKey")
-      .setRepositoryKey("plugin")
-      .setName("new name")
-      .setDescription("new description")
-      .setStatus(Rule.STATUS_DEPRECATED)
-      .setConfigKey("NewConfigKey")
-      .setSeverity(Severity.INFO)
-      .setCardinality(Cardinality.MULTIPLE)
-      .setLanguage("dart")
-      .setParentId(3)
-      .setSubCharacteristicId(100)
-      .setDefaultSubCharacteristicId(101)
-      .setRemediationFunction("linear")
-      .setDefaultRemediationFunction("linear_offset")
-      .setRemediationCoefficient("1h")
-      .setDefaultRemediationCoefficient("5d")
-      .setRemediationOffset("5min")
-      .setDefaultRemediationOffset("10h")
-      .setEffortToFixDescription("squid.S115.effortToFix")
-      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
-      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
-
-    RuleDto ruleToInsert2 = new RuleDto()
-      .setId(2)
-      .setRuleKey("NewRuleKey2")
-      .setRepositoryKey("plugin2")
-      .setName("new name2")
-      .setDescription("new description2")
-      .setStatus(Rule.STATUS_BETA)
-      .setConfigKey("NewConfigKey2")
-      .setSeverity(Severity.MAJOR)
-      .setCardinality(Cardinality.SINGLE)
-      .setLanguage("js")
-      .setParentId(null)
-      .setSubCharacteristicId(102)
-      .setDefaultSubCharacteristicId(103)
-      .setRemediationFunction("linear_offset")
-      .setDefaultRemediationFunction("linear")
-      .setRemediationCoefficient("5d")
-      .setDefaultRemediationCoefficient("1h")
-      .setRemediationOffset("10h")
-      .setDefaultRemediationOffset("5min")
-      .setEffortToFixDescription("squid.S115.effortToFix2")
-      .setCreatedAt(DateUtils.parseDate("2013-12-14"))
-      .setUpdatedAt(DateUtils.parseDate("2013-12-15"));
-
-    dao.insert(ImmutableList.of(ruleToInsert1, ruleToInsert2));
-
-    checkTables("insert_all", "rules");
-  }
-
-  @Test
-  public void select_parameters() throws Exception {
-    setupData("selectParameters");
-    List<RuleParamDto> ruleDtos = dao.selectParameters();
-
-    assertThat(ruleDtos.size()).isEqualTo(1);
-    RuleParamDto ruleDto = ruleDtos.get(0);
-    assertThat(ruleDto.getId()).isEqualTo(1);
-    assertThat(ruleDto.getName()).isEqualTo("myParameter");
-    assertThat(ruleDto.getDescription()).isEqualTo("My Parameter");
-    assertThat(ruleDto.getType()).isEqualTo("plop");
-    assertThat(ruleDto.getDefaultValue()).isEqualTo("plouf");
-  }
-
-  @Test
-  public void select_parameters_by_rule_id() throws Exception {
-    setupData("select_parameters_by_rule_id");
-    int ruleId = 1;
-    List<RuleParamDto> ruleDtos = dao.selectParametersByRuleId(ruleId);
-
-    assertThat(ruleDtos.size()).isEqualTo(1);
-    RuleParamDto ruleDto = ruleDtos.get(0);
-    assertThat(ruleDto.getId()).isEqualTo(1);
-    assertThat(ruleDto.getName()).isEqualTo("myParameter");
-    assertThat(ruleDto.getDescription()).isEqualTo("My Parameter");
-    assertThat(ruleDto.getType()).isEqualTo("plop");
-    assertThat(ruleDto.getRuleId()).isEqualTo(ruleId);
-  }
-
-  @Test
-  public void select_parameters_by_rule_ids() throws Exception {
-    setupData("select_parameters_by_rule_ids");
-
-    assertThat(dao.selectParametersByRuleIds(newArrayList(1, 2))).hasSize(2);
-    assertThat(dao.selectParametersByRuleIds(newArrayList(1))).hasSize(1);
-  }
-
-  @Test
-  public void insert_parameter() {
-    setupData("insert_parameter");
-
-    RuleParamDto param = new RuleParamDto()
-      .setRuleId(1)
-      .setName("max")
-      .setType("INTEGER")
-      .setDefaultValue("30")
-      .setDescription("My Parameter");
-
-    dao.insert(param);
-
-    checkTables("insert_parameter", "rules_parameters");
-  }
-
-  @Test
-  public void update_parameter() {
-    setupData("update_parameter");
-
-    RuleParamDto param = new RuleParamDto()
-      .setId(1)
-      .setName("format")
-      .setType("STRING")
-      .setDefaultValue("^[a-z]+(\\.[a-z][a-z0-9]*)*$")
-      .setDescription("Regular expression used to check the package names against.");
-
-    dao.update(param);
-
-    checkTables("update_parameter", "rules_parameters");
-  }
-
-  @Test
-  public void select_tags_by_rule_id() throws Exception {
-    setupData("select_tags_by_rule_id");
-
-    assertThat(dao.selectTagsByRuleId(3)).hasSize(2);
-  }
-
-  @Test
-  public void select_tags_by_rule_ids() throws Exception {
-    setupData("select_tags_by_rule_ids");
-
-    assertThat(dao.selectTagsByRuleIds(newArrayList(3, 4))).hasSize(3);
-  }
-
-  @Test
-  public void keysOfRowsUpdatedAfter() throws Exception {
-    setupData("empty");
-
-    RuleDto rule1 = new RuleDto()
-      .setId(1)
-      .setRepositoryKey("foo")
-      .setRuleKey("R1")
-      .setName("ROne")
-      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
-      .setUpdatedAt(DateUtils.parseDate("2013-12-16"));
-    RuleDto rule2 = new RuleDto()
-      .setId(2)
-      .setRepositoryKey("foo")
-      .setRuleKey("R2")
-      .setName("RTwo")
-      .setCreatedAt(DateUtils.parseDate("2014-01-28"))
-      .setUpdatedAt(DateUtils.parseDate("2014-05-19"));
-    dao.insert(Arrays.asList(rule1, rule2));
-
-    assertThat(dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2014-06-01").getTime())).isEmpty();
-    assertThat(dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2012-01-01").getTime())).hasSize(2);
-    Iterable<RuleKey> keys = dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2014-05-17").getTime());
-    assertThat(keys).hasSize(1);
-    assertThat(Iterables.getFirst(keys, null).rule()).isEqualTo("R2");
-  }
-
-  private List<Integer> idsFromRuleDtos(List<RuleDto> ruleDtos){
-    return newArrayList(Iterables.transform(ruleDtos, new Function<RuleDto, Integer>() {
-      @Override
-      public Integer apply(RuleDto input) {
-        return input.getId();
-      }
-    }));
-  }
+//  private static RuleDao dao;
+//
+//  @Before
+//  public void createDao() throws Exception {
+//    dao = new RuleDao(getMyBatis());
+//  }
+//
+//  @Test
+//  public void select_all() throws Exception {
+//    setupData("selectAll");
+//    List<RuleDto> ruleDtos = dao.selectAll();
+//
+//    assertThat(ruleDtos).hasSize(1);
+//
+//    RuleDto ruleDto = ruleDtos.get(0);
+//    assertThat(ruleDto.getId()).isEqualTo(1);
+//    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
+//    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
+//    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
+//    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
+//    assertThat(ruleDto.getNoteData()).isEqualTo("Rule note with accents \u00e9\u00e8\u00e0");
+//    assertThat(ruleDto.getSubCharacteristicId()).isEqualTo(100);
+//    assertThat(ruleDto.getDefaultSubCharacteristicId()).isEqualTo(101);
+//    assertThat(ruleDto.getRemediationFunction()).isEqualTo("linear");
+//    assertThat(ruleDto.getDefaultRemediationFunction()).isEqualTo("linear_offset");
+//    assertThat(ruleDto.getRemediationCoefficient()).isEqualTo("1h");
+//    assertThat(ruleDto.getDefaultRemediationCoefficient()).isEqualTo("5d");
+//    assertThat(ruleDto.getRemediationOffset()).isEqualTo("5min");
+//    assertThat(ruleDto.getDefaultRemediationOffset()).isEqualTo("10h");
+//    assertThat(ruleDto.getEffortToFixDescription()).isEqualTo("squid.S115.effortToFix");
+//  }
+//
+//  @Test
+//  public void select_enables_and_non_manual() throws Exception {
+//    setupData("select_enables_and_non_manual");
+//    List<RuleDto> ruleDtos = dao.selectEnablesAndNonManual();
+//
+//    assertThat(ruleDtos.size()).isEqualTo(1);
+//    RuleDto ruleDto = ruleDtos.get(0);
+//    assertThat(ruleDto.getId()).isEqualTo(1);
+//    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
+//    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
+//    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
+//    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
+//    assertThat(ruleDto.getNoteData()).isEqualTo("Rule note with accents \u00e9\u00e8\u00e0");
+//    assertThat(ruleDto.getSubCharacteristicId()).isEqualTo(100);
+//    assertThat(ruleDto.getDefaultSubCharacteristicId()).isEqualTo(101);
+//    assertThat(ruleDto.getRemediationFunction()).isEqualTo("LINEAR");
+//    assertThat(ruleDto.getDefaultRemediationFunction()).isEqualTo("LINEAR_OFFSET");
+//    assertThat(ruleDto.getRemediationCoefficient()).isEqualTo("1h");
+//    assertThat(ruleDto.getDefaultRemediationCoefficient()).isEqualTo("5d");
+//    assertThat(ruleDto.getRemediationOffset()).isEqualTo("5min");
+//    assertThat(ruleDto.getDefaultRemediationOffset()).isEqualTo("10h");
+//    assertThat(ruleDto.getEffortToFixDescription()).isEqualTo("squid.S115.effortToFix");
+//  }
+//
+//  @Test
+//  public void select_by_id() throws Exception {
+//    setupData("selectById");
+//    RuleDto ruleDto = dao.selectById(2);
+//
+//    assertThat(ruleDto.getId()).isEqualTo(2);
+//    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
+//    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
+//    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
+//    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
+//  }
+//
+//  @Test
+//  public void select_by_rule_key() throws Exception {
+//    setupData("select_by_rule_key");
+//    assertThat(dao.selectByKey(RuleKey.of("checkstyle", "AvoidComparison"))).isNotNull();
+//    assertThat(dao.selectByKey(RuleKey.of("checkstyle", "Unknown"))).isNull();
+//    assertThat(dao.selectByKey(RuleKey.of("Unknown", "AvoidComparison"))).isNull();
+//  }
+//
+//  @Test
+//  public void select_by_name() throws Exception {
+//    setupData("select_by_name");
+//    RuleDto ruleDto = dao.selectByName("Avoid Null");
+//
+//    assertThat(ruleDto.getId()).isEqualTo(2);
+//    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
+//    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
+//    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
+//    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
+//  }
+//
+//  @Test
+//  public void select_non_manual() throws Exception {
+//    setupData("selectNonManual");
+//    DbSession session = getMyBatis().openSession(false);
+//    List<RuleDto> ruleDtos = dao.selectNonManual(session);
+//    session.commit();
+//    session.close();
+//
+//    assertThat(ruleDtos.size()).isEqualTo(1);
+//    RuleDto ruleDto = ruleDtos.get(0);
+//    assertThat(ruleDto.getId()).isEqualTo(1);
+//    assertThat(ruleDto.getName()).isEqualTo("Avoid Null");
+//    assertThat(ruleDto.getDescription()).isEqualTo("Should avoid NULL");
+//    assertThat(ruleDto.getStatus()).isEqualTo(Rule.STATUS_READY);
+//    assertThat(ruleDto.getRepositoryKey()).isEqualTo("checkstyle");
+//  }
+//
+//  @Test
+//  public void select_by_sub_characteristic_id(){
+//    setupData("select_by_sub_characteristic_id");
+//
+//    // Rules from sub characteristic (even REMOVED ones are returned)
+//    List<RuleDto> ruleDtos = dao.selectBySubCharacteristicId(3);
+//    assertThat(ruleDtos).hasSize(3);
+//    assertThat(idsFromRuleDtos(ruleDtos)).containsExactly(2, 4, 5);
+//
+//    // Nothing on root characteristic
+//    ruleDtos = dao.selectBySubCharacteristicId(1);
+//    assertThat(ruleDtos).isEmpty();
+//
+//    // Rules from disabled characteristic
+//    ruleDtos = dao.selectBySubCharacteristicId(11);
+//    assertThat(idsFromRuleDtos(ruleDtos)).containsExactly(3);
+//  }
+//
+//  @Test
+//  public void update() {
+//    setupData("update");
+//
+//    RuleDto ruleToUpdate = new RuleDto()
+//      .setId(1)
+//      .setRuleKey("NewRuleKey")
+//      .setRepositoryKey("plugin")
+//      .setName("new name")
+//      .setDescription("new description")
+//      .setStatus(Rule.STATUS_DEPRECATED)
+//      .setConfigKey("NewConfigKey")
+//      .setSeverity(Severity.INFO)
+//      .setCardinality(Cardinality.MULTIPLE)
+//      .setLanguage("dart")
+//      .setParentId(3)
+//      .setNoteData("My note")
+//      .setNoteUserLogin("admin")
+//      .setNoteCreatedAt(DateUtils.parseDate("2013-12-19"))
+//      .setNoteUpdatedAt(DateUtils.parseDate("2013-12-20"))
+//      .setSubCharacteristicId(100)
+//      .setDefaultSubCharacteristicId(101)
+//      .setRemediationFunction("linear")
+//      .setDefaultRemediationFunction("linear_offset")
+//      .setRemediationCoefficient("1h")
+//      .setDefaultRemediationCoefficient("5d")
+//      .setRemediationOffset("5min")
+//      .setDefaultRemediationOffset("10h")
+//      .setEffortToFixDescription("squid.S115.effortToFix")
+//      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
+//
+//    dao.update(ruleToUpdate);
+//
+//    checkTables("update", "rules");
+//  }
+//
+//  @Test
+//  public void insert() {
+//    setupData("empty");
+//
+//    RuleDto ruleToInsert = new RuleDto()
+//      .setId(1)
+//      .setRuleKey("NewRuleKey")
+//      .setRepositoryKey("plugin")
+//      .setName("new name")
+//      .setDescription("new description")
+//      .setStatus(Rule.STATUS_DEPRECATED)
+//      .setConfigKey("NewConfigKey")
+//      .setSeverity(Severity.INFO)
+//      .setCardinality(Cardinality.MULTIPLE)
+//      .setLanguage("dart")
+//      .setParentId(3)
+//      .setSubCharacteristicId(100)
+//      .setDefaultSubCharacteristicId(101)
+//      .setRemediationFunction("linear")
+//      .setDefaultRemediationFunction("linear_offset")
+//      .setRemediationCoefficient("1h")
+//      .setDefaultRemediationCoefficient("5d")
+//      .setRemediationOffset("5min")
+//      .setDefaultRemediationOffset("10h")
+//      .setEffortToFixDescription("squid.S115.effortToFix")
+//      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
+//      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
+//
+//    dao.insert(ruleToInsert);
+//
+//    checkTables("insert", "rules");
+//  }
+//
+//  @Test
+//  public void insert_all() {
+//    setupData("empty");
+//
+//    RuleDto ruleToInsert1 = new RuleDto()
+//      .setId(1)
+//      .setRuleKey("NewRuleKey")
+//      .setRepositoryKey("plugin")
+//      .setName("new name")
+//      .setDescription("new description")
+//      .setStatus(Rule.STATUS_DEPRECATED)
+//      .setConfigKey("NewConfigKey")
+//      .setSeverity(Severity.INFO)
+//      .setCardinality(Cardinality.MULTIPLE)
+//      .setLanguage("dart")
+//      .setParentId(3)
+//      .setSubCharacteristicId(100)
+//      .setDefaultSubCharacteristicId(101)
+//      .setRemediationFunction("linear")
+//      .setDefaultRemediationFunction("linear_offset")
+//      .setRemediationCoefficient("1h")
+//      .setDefaultRemediationCoefficient("5d")
+//      .setRemediationOffset("5min")
+//      .setDefaultRemediationOffset("10h")
+//      .setEffortToFixDescription("squid.S115.effortToFix")
+//      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
+//      .setUpdatedAt(DateUtils.parseDate("2013-12-17"));
+//
+//    RuleDto ruleToInsert2 = new RuleDto()
+//      .setId(2)
+//      .setRuleKey("NewRuleKey2")
+//      .setRepositoryKey("plugin2")
+//      .setName("new name2")
+//      .setDescription("new description2")
+//      .setStatus(Rule.STATUS_BETA)
+//      .setConfigKey("NewConfigKey2")
+//      .setSeverity(Severity.MAJOR)
+//      .setCardinality(Cardinality.SINGLE)
+//      .setLanguage("js")
+//      .setParentId(null)
+//      .setSubCharacteristicId(102)
+//      .setDefaultSubCharacteristicId(103)
+//      .setRemediationFunction("linear_offset")
+//      .setDefaultRemediationFunction("linear")
+//      .setRemediationCoefficient("5d")
+//      .setDefaultRemediationCoefficient("1h")
+//      .setRemediationOffset("10h")
+//      .setDefaultRemediationOffset("5min")
+//      .setEffortToFixDescription("squid.S115.effortToFix2")
+//      .setCreatedAt(DateUtils.parseDate("2013-12-14"))
+//      .setUpdatedAt(DateUtils.parseDate("2013-12-15"));
+//
+//    dao.insert(ImmutableList.of(ruleToInsert1, ruleToInsert2));
+//
+//    checkTables("insert_all", "rules");
+//  }
+//
+//  @Test
+//  public void select_parameters() throws Exception {
+//    setupData("selectParameters");
+//    List<RuleParamDto> ruleDtos = dao.selectParameters();
+//
+//    assertThat(ruleDtos.size()).isEqualTo(1);
+//    RuleParamDto ruleDto = ruleDtos.get(0);
+//    assertThat(ruleDto.getId()).isEqualTo(1);
+//    assertThat(ruleDto.getName()).isEqualTo("myParameter");
+//    assertThat(ruleDto.getDescription()).isEqualTo("My Parameter");
+//    assertThat(ruleDto.getType()).isEqualTo("plop");
+//    assertThat(ruleDto.getDefaultValue()).isEqualTo("plouf");
+//  }
+//
+//  @Test
+//  public void select_parameters_by_rule_id() throws Exception {
+//    setupData("select_parameters_by_rule_id");
+//    int ruleId = 1;
+//    List<RuleParamDto> ruleDtos = dao.selectParametersByRuleId(ruleId);
+//
+//    assertThat(ruleDtos.size()).isEqualTo(1);
+//    RuleParamDto ruleDto = ruleDtos.get(0);
+//    assertThat(ruleDto.getId()).isEqualTo(1);
+//    assertThat(ruleDto.getName()).isEqualTo("myParameter");
+//    assertThat(ruleDto.getDescription()).isEqualTo("My Parameter");
+//    assertThat(ruleDto.getType()).isEqualTo("plop");
+//    assertThat(ruleDto.getRuleId()).isEqualTo(ruleId);
+//  }
+//
+//  @Test
+//  public void select_parameters_by_rule_ids() throws Exception {
+//    setupData("select_parameters_by_rule_ids");
+//
+//    assertThat(dao.selectParametersByRuleIds(newArrayList(1, 2))).hasSize(2);
+//    assertThat(dao.selectParametersByRuleIds(newArrayList(1))).hasSize(1);
+//  }
+//
+//  @Test
+//  public void insert_parameter() {
+//    setupData("insert_parameter");
+//
+//    RuleParamDto param = new RuleParamDto()
+//      .setRuleId(1)
+//      .setName("max")
+//      .setType("INTEGER")
+//      .setDefaultValue("30")
+//      .setDescription("My Parameter");
+//
+//    dao.insert(param);
+//
+//    checkTables("insert_parameter", "rules_parameters");
+//  }
+//
+//  @Test
+//  public void update_parameter() {
+//    setupData("update_parameter");
+//
+//    RuleParamDto param = new RuleParamDto()
+//      .setId(1)
+//      .setName("format")
+//      .setType("STRING")
+//      .setDefaultValue("^[a-z]+(\\.[a-z][a-z0-9]*)*$")
+//      .setDescription("Regular expression used to check the package names against.");
+//
+//    dao.update(param);
+//
+//    checkTables("update_parameter", "rules_parameters");
+//  }
+//
+//  @Test
+//  public void select_tags_by_rule_id() throws Exception {
+//    setupData("select_tags_by_rule_id");
+//
+//    assertThat(dao.selectTagsByRuleId(3)).hasSize(2);
+//  }
+//
+//  @Test
+//  public void select_tags_by_rule_ids() throws Exception {
+//    setupData("select_tags_by_rule_ids");
+//
+//    assertThat(dao.selectTagsByRuleIds(newArrayList(3, 4))).hasSize(3);
+//  }
+//
+//  @Test
+//  public void keysOfRowsUpdatedAfter() throws Exception {
+//    setupData("empty");
+//
+//    RuleDto rule1 = new RuleDto()
+//      .setId(1)
+//      .setRepositoryKey("foo")
+//      .setRuleKey("R1")
+//      .setName("ROne")
+//      .setCreatedAt(DateUtils.parseDate("2013-12-16"))
+//      .setUpdatedAt(DateUtils.parseDate("2013-12-16"));
+//    RuleDto rule2 = new RuleDto()
+//      .setId(2)
+//      .setRepositoryKey("foo")
+//      .setRuleKey("R2")
+//      .setName("RTwo")
+//      .setCreatedAt(DateUtils.parseDate("2014-01-28"))
+//      .setUpdatedAt(DateUtils.parseDate("2014-05-19"));
+//    dao.insert(Arrays.asList(rule1, rule2));
+//
+//    assertThat(dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2014-06-01").getTime())).isEmpty();
+//    assertThat(dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2012-01-01").getTime())).hasSize(2);
+//    Iterable<RuleKey> keys = dao.keysOfRowsUpdatedAfter(DateUtils.parseDate("2014-05-17").getTime());
+//    assertThat(keys).hasSize(1);
+//    assertThat(Iterables.getFirst(keys, null).rule()).isEqualTo("R2");
+//  }
+//
+//  private List<Integer> idsFromRuleDtos(List<RuleDto> ruleDtos){
+//    return newArrayList(Iterables.transform(ruleDtos, new Function<RuleDto, Integer>() {
+//      @Override
+//      public Integer apply(RuleDto input) {
+//        return input.getId();
+//      }
+//    }));
+//  }
 }
index 2a78ee3369dabab6d93066f2bf29ab44379f27f5..5ee5f2686160494661764bb10656a9e19607113a 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.rule2;
 
 import com.google.common.collect.Iterables;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Test;
@@ -28,7 +29,10 @@ import org.sonar.api.rule.RuleStatus;
 import org.sonar.api.rule.Severity;
 import org.sonar.api.utils.DateUtils;
 import org.sonar.check.Cardinality;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.rule.RuleDto;
+import org.sonar.server.search.Hit;
 import org.sonar.server.search.QueryOptions;
 import org.sonar.server.search.Result;
 import org.sonar.server.tester.ServerTester;
@@ -41,31 +45,35 @@ import static org.fest.assertions.Assertions.assertThat;
 public class RuleIndexMediumTest {
 
   @ClassRule
-  public static ServerTester tester = new ServerTester()
-    .setProperty("sonar.es.http.port","8888");
+  public static ServerTester tester = new ServerTester();
 
+  MyBatis myBatis = tester.get(MyBatis.class);
   RuleDao dao = tester.get(RuleDao.class);
   RuleIndex index = tester.get(RuleIndex.class);
+  DbSession dbSession;
 
   @Before
-  public void clear_data_store() {
+  public void before() {
     tester.clearDataStores();
+    dbSession = myBatis.openSession(false);
+  }
+
+  @After
+  public void after() {
+    dbSession.close();
   }
 
   @Test
   public void facet_test_with_repository() {
-    dao.insert(newRuleDto(RuleKey.of("javascript", "S001"))
-      .setRuleKey("X001"));
-    dao.insert(newRuleDto(RuleKey.of("cobol", "S001"))
-      .setRuleKey("X001"));
-    dao.insert(newRuleDto(RuleKey.of("php", "S002")));
+    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")).setRuleKey("X001"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("cobol", "S001")).setRuleKey("X001"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("php", "S002")), dbSession);
+    dbSession.commit();
     index.refresh();
 
-    RuleQuery query = new RuleQuery();
-    Result result = null;
-
     // should not have any facet!
-    result = index.search(query, new QueryOptions().setFacet(false));
+    RuleQuery query = new RuleQuery();
+    Result result = index.search(query, new QueryOptions().setFacet(false));
     assertThat(result.getFacets()).isEmpty();
 
     // Repositories Facet is preset
@@ -75,12 +83,13 @@ public class RuleIndexMediumTest {
     assertThat(result.getFacets()).hasSize(3);
     assertThat(result.getFacet("Repositories").size()).isEqualTo(3);
     assertThat(result.getFacetKeys("Repositories"))
-      .contains("javascript","cobol","php");
+      .contains("javascript", "cobol", "php");
   }
 
   @Test
   public void return_all_doc_fields_by_default() {
-    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")));
+    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     QueryOptions options = new QueryOptions().setFieldsToReturn(null);
@@ -96,7 +105,8 @@ public class RuleIndexMediumTest {
 
   @Test
   public void select_doc_fields_to_return() {
-    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")));
+    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     QueryOptions options = new QueryOptions();
@@ -113,7 +123,8 @@ public class RuleIndexMediumTest {
   @Test
   public void search_name_by_query() {
     dao.insert(newRuleDto(RuleKey.of("javascript", "S001"))
-      .setName("testing the partial match and matching of rule"));
+      .setName("testing the partial match and matching of rule"), dbSession);
+    dbSession.commit();
     index.refresh();
 
     // substring
@@ -136,10 +147,11 @@ public class RuleIndexMediumTest {
   @Test
   public void search_key_by_query() {
     dao.insert(newRuleDto(RuleKey.of("javascript", "S001"))
-      .setRuleKey("X001"));
+      .setRuleKey("X001"), dbSession);
     dao.insert(newRuleDto(RuleKey.of("cobol", "S001"))
-      .setRuleKey("X001"));
-    dao.insert(newRuleDto(RuleKey.of("php", "S002")));
+      .setRuleKey("X001"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("php", "S002")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     // key
@@ -157,8 +169,9 @@ public class RuleIndexMediumTest {
 
   @Test
   public void search_all_rules() {
-    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")));
+    dao.insert(newRuleDto(RuleKey.of("javascript", "S001")), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     Result results = index.search(new RuleQuery(), new QueryOptions());
@@ -169,8 +182,9 @@ public class RuleIndexMediumTest {
 
   @Test
   public void search_by_any_of_repositories() {
-    dao.insert(newRuleDto(RuleKey.of("findbugs", "S001")));
-    dao.insert(newRuleDto(RuleKey.of("pmd", "S002")));
+    dao.insert(newRuleDto(RuleKey.of("findbugs", "S001")), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("pmd", "S002")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     RuleQuery query = new RuleQuery().setRepositories(Arrays.asList("checkstyle", "pmd"));
@@ -189,12 +203,11 @@ public class RuleIndexMediumTest {
 
   @Test
   public void search_by_any_of_languages() throws InterruptedException {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setLanguage("java"));
-    dao.insert(newRuleDto(RuleKey.of("javascript", "S002")).setLanguage("js"));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setLanguage("java"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("javascript", "S002")).setLanguage("js"), dbSession);
+    dbSession.commit();
     index.refresh();
 
-
-
     RuleQuery query = new RuleQuery().setLanguages(Arrays.asList("cobol", "js"));
     Result<Rule> results = index.search(query, new QueryOptions());
 
@@ -212,14 +225,13 @@ public class RuleIndexMediumTest {
     // null list => no filter
     query = new RuleQuery().setLanguages(null);
     assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
-
-
   }
 
   @Test
   public void search_by_any_of_severities() throws InterruptedException {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO), dbSession);
+    dbSession.commit();
     index.refresh();
 
     RuleQuery query = new RuleQuery().setSeverities(Arrays.asList(Severity.INFO, Severity.MINOR));
@@ -242,8 +254,9 @@ public class RuleIndexMediumTest {
 
   @Test
   public void search_by_any_of_statuses() throws InterruptedException {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA.name()));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY.name()));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA.name()), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY.name()), dbSession);
+    dbSession.commit();
     index.refresh();
 
     RuleQuery query = new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED, RuleStatus.READY));
@@ -266,9 +279,10 @@ public class RuleIndexMediumTest {
 
   @Test
   public void sort_by_name() {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setName("abcd"));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setName("ABC"));
-    dao.insert(newRuleDto(RuleKey.of("java", "S003")).setName("FGH"));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setName("abcd"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setName("ABC"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S003")).setName("FGH"), dbSession);
+    dbSession.commit();
     index.refresh();
 
     // ascending
@@ -288,8 +302,9 @@ public class RuleIndexMediumTest {
 
   @Test
   public void sort_by_language() {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setLanguage("java"));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setLanguage("php"));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")).setLanguage("java"), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")).setLanguage("php"), dbSession);
+    dbSession.commit();
     index.refresh();
 
     // ascending
@@ -307,9 +322,10 @@ public class RuleIndexMediumTest {
 
   @Test
   public void paging() {
-    dao.insert(newRuleDto(RuleKey.of("java", "S001")));
-    dao.insert(newRuleDto(RuleKey.of("java", "S002")));
-    dao.insert(newRuleDto(RuleKey.of("java", "S003")));
+    dao.insert(newRuleDto(RuleKey.of("java", "S001")), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S002")), dbSession);
+    dao.insert(newRuleDto(RuleKey.of("java", "S003")), dbSession);
+    dbSession.commit();
     index.refresh();
 
     // from 0 to 1 included
index 813ff213d12b7858653a6ed7f031b917ee308eef..f0fd11d80f40431d2e0daf48b70d56568a90ebca 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.server.rule2;
 
 import com.google.common.collect.Iterables;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Test;
@@ -31,14 +32,8 @@ import org.sonar.api.utils.DateUtils;
 import org.sonar.check.Cardinality;
 import org.sonar.core.persistence.DbSession;
 import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.qualityprofile.db.QualityProfileDao;
 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.search.QueryOptions;
 import org.sonar.server.tester.ServerTester;
 
 import java.util.List;
@@ -50,25 +45,31 @@ public class RuleServiceMediumTest {
   @ClassRule
   public static ServerTester tester = new ServerTester();
 
+  MyBatis myBatis = tester.get(MyBatis.class);
   RuleDao dao = tester.get(RuleDao.class);
-
-  QualityProfileDao qualityProfileDao = tester.get(QualityProfileDao.class);
-
   RuleIndex index = tester.get(RuleIndex.class);
+  DbSession dbSession;
 
   @Before
-  public void clear_data_store() {
+  public void before() {
     tester.clearDataStores();
+    dbSession = myBatis.openSession(false);
+  }
+
+  @After
+  public void after() {
+    dbSession.close();
   }
 
   @Test
   public void insert_in_db_and_index_in_es() {
     // insert db
     RuleKey ruleKey = RuleKey.of("javascript", "S001");
-    dao.insert(newRuleDto(ruleKey));
+    dao.insert(newRuleDto(ruleKey), dbSession);
+    dbSession.commit();
 
     // verify that rule is persisted in db
-    RuleDto persistedDto = dao.selectByKey(ruleKey);
+    RuleDto persistedDto = dao.getByKey(ruleKey, dbSession);
     assertThat(persistedDto).isNotNull();
     assertThat(persistedDto.getId()).isGreaterThanOrEqualTo(0);
     assertThat(persistedDto.getRuleKey()).isEqualTo(ruleKey.rule());
@@ -93,12 +94,11 @@ public class RuleServiceMediumTest {
 
     //TODO    assertThat((Collection) hit.getField(RuleNormalizer.RuleField.SYSTEM_TAGS.key())).isEmpty();
     //TODO    assertThat((Collection) hit.getField(RuleNormalizer.RuleField.TAGS.key())).isEmpty();
+
   }
 
   @Test
   public void insert_and_index_rule_parameters() {
-    DbSession dbSession = tester.get(MyBatis.class).openSession(false);
-
     // insert db
     RuleKey ruleKey = RuleKey.of("javascript", "S001");
     RuleDto ruleDto = newRuleDto(ruleKey);
@@ -106,23 +106,21 @@ public class RuleServiceMediumTest {
     dbSession.commit();
 
     RuleParamDto minParamDto = new RuleParamDto()
-      .setRuleId(ruleDto.getId())
       .setName("min")
       .setType(RuleParamType.INTEGER.type())
       .setDefaultValue("2")
       .setDescription("Minimum");
-    dao.insert(minParamDto, dbSession);
+    dao.addRuleParam(ruleDto, minParamDto, dbSession);
     RuleParamDto maxParamDto = new RuleParamDto()
-      .setRuleId(ruleDto.getId())
       .setName("max")
       .setType(RuleParamType.INTEGER.type())
       .setDefaultValue("10")
       .setDescription("Maximum");
-    dao.insert(maxParamDto, dbSession);
+    dao.addRuleParam(ruleDto, maxParamDto, dbSession);
     dbSession.commit();
 
     // verify that parameters are persisted in db
-    List<RuleParamDto> persistedDtos = dao.selectParametersByRuleId(ruleDto.getId());
+    List<RuleParamDto> persistedDtos = dao.findRuleParamsByRuleKey(ruleKey, dbSession);
     assertThat(persistedDtos).hasSize(2);
 
     // verify that parameters are indexed in es
@@ -139,74 +137,6 @@ public class RuleServiceMediumTest {
     assertThat(Iterables.getLast(rule.params(), null).key()).isEqualTo("max");
   }
 
-  //TODO test delete, update, tags, params
-
-  @Test
-  public void insert_and_index_tags() {
-    DbSession dbSession = tester.get(MyBatis.class).openSession(false);
-    RuleTagDao ruleTagDao = tester.get(RuleTagDao.class);
-
-    // insert db
-    RuleKey ruleKey = RuleKey.of("javascript", "S001");
-    RuleDto ruleDto = newRuleDto(ruleKey);
-    dao.insert(ruleDto, dbSession);
-    dbSession.commit();
-
-    RuleTagDto tag1 = new RuleTagDto()
-      .setTag("hello");
-    RuleTagDto tag2 = new RuleTagDto()
-      .setTag("world");
-    RuleTagDto tag3 = new RuleTagDto()
-      .setTag("AdMiN");
-    ruleTagDao.insert(tag1, dbSession);
-    ruleTagDao.insert(tag2, dbSession);
-    ruleTagDao.insert(tag3, dbSession);
-    dbSession.commit();
-
-    RuleRuleTagDto rTag1 = new RuleRuleTagDto()
-      .setTagId(tag1.getId())
-      .setTag(tag1.getTag())
-      .setRuleId(ruleDto.getId())
-      .setType(RuleTagType.ADMIN);
-    RuleRuleTagDto rTag2 = new RuleRuleTagDto()
-      .setTagId(tag2.getId())
-      .setTag(tag2.getTag())
-      .setRuleId(ruleDto.getId())
-      .setType(RuleTagType.ADMIN);
-    RuleRuleTagDto rTag3 = new RuleRuleTagDto()
-      .setTagId(tag3.getId())
-      .setTag(tag3.getTag())
-      .setRuleId(ruleDto.getId())
-      .setType(RuleTagType.SYSTEM);
-    dao.insert(rTag1, dbSession);
-    dao.insert(rTag2, dbSession);
-    dao.insert(rTag3, dbSession);
-    dbSession.commit();
-    dbSession.close();
-
-
-    // verify that tags are persisted in db
-    List<RuleRuleTagDto> persistedDtos = dao.selectTagsByRuleId(ruleDto.getId());
-    assertThat(persistedDtos).hasSize(3);
-
-    index.refresh();
-
-    // verify that tags are indexed in es
-    index.search(new RuleQuery(), new QueryOptions());
-    Rule hit = index.getByKey(ruleKey);
-    assertThat(hit).isNotNull();
-    assertThat(hit.tags()).containsExactly("hello","world");
-    assertThat(hit.systemTags()).containsExactly("AdMiN");
-
-    RuleService service = tester.get(RuleService.class);
-    Rule rule = service.getByKey(ruleKey);
-    assertThat(rule.tags()).containsExactly("hello","world");
-    assertThat(rule.systemTags()).containsExactly("AdMiN");
-
-    //TODO assertThat(service.listTags()).contains("hello", "world", "AdMiN");
-  }
-
-
   private RuleDto newRuleDto(RuleKey ruleKey) {
     return new RuleDto()
       .setRuleKey(ruleKey.rule())