]> source.dussan.org Git - sonarqube.git/commitdiff
Drop usages of MyBatis#openSession()
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Fri, 24 Feb 2017 15:46:37 +0000 (16:46 +0100)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Sun, 26 Feb 2017 06:38:05 +0000 (07:38 +0100)
in favor of DbClient#openSession()

58 files changed:
pom.xml
server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java
server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentKeyUpdaterDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueChangeDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/loadedtemplate/LoadedTemplateDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QualityProfileDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/source/FileSourceDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/user/UserDao.java
server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueChangeDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/loadedtemplate/LoadedTemplateDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateConditionDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDaoTest.java
server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDaoTest.java
server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/issue/NewEffortAggregator.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/qualitygate/QualityGateServiceImpl.java
server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java
server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/QualityGateConditionsUpdater.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/QualityGateUpdater.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/QualityGates.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/SelectAction.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java [deleted file]
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/SearchDataLoader.java
server/sonar-server/src/main/java/org/sonar/server/user/DefaultUserFinder.java
server/sonar-server/src/main/java/org/sonar/server/user/DeprecatedUserFinder.java
server/sonar-server/src/test/java/org/sonar/server/batch/ProjectDataLoaderMediumTest.java
server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/qualitygate/QualityGateServiceImplTest.java
server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/scm/ScmInfoRepositoryImplTest.java
server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/step/PersistTestsStepTest.java
server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java
server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/QualityGateUpdaterTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/QualityGatesTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/RegisterQualityGatesTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/ws/CreateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/ws/CreateConditionActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/ws/UpdateConditionActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilesTest.java [deleted file]
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesMediumTest.java
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/SetDefaultActionTest.java
server/sonar-server/src/test/java/org/sonar/server/source/SourceServiceTest.java
server/sonar-server/src/test/java/org/sonar/server/source/ws/LinesActionTest.java
server/sonar-server/src/test/java/org/sonar/server/source/ws/ScmActionTest.java
server/sonar-server/src/test/java/org/sonar/server/startup/ClearRulesOverloadedDebtTest.java
server/sonar-server/src/test/java/org/sonar/server/test/ws/ListActionTest.java
server/sonar-server/src/test/java/org/sonar/server/user/DefaultUserFinderTest.java [deleted file]
server/sonar-server/src/test/java/org/sonar/server/user/DeprecatedUserFinderTest.java
sonar-application/src/main/java/org/sonar/application/App.java
sonar-application/src/main/java/org/sonar/application/JavaCommandFactoryImpl.java

diff --git a/pom.xml b/pom.xml
index e28757b55ebc2057594b7ae7d57e27e5e9e36b3b..1efabbe2ac7df9b0c2a333c9fbd3816584579cae 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
     <groupId>org.sonarsource.parent</groupId>
                   <goal>compile</goal>
                 </goals>
                 <configuration>
-                  <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
+                  <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
+                  </protocArtifact>
                   <protoSourceRoot>${project.basedir}/src/main/protobuf</protoSourceRoot>
                   <outputDirectory>${project.build.directory}/generated-sources/protobuf</outputDirectory>
                 </configuration>
                   <goal>test-compile</goal>
                 </goals>
                 <configuration>
-                  <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
+                  <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
+                  </protocArtifact>
                   <protoTestSourceRoot>${project.basedir}/src/test/protobuf</protoTestSourceRoot>
                   <outputDirectory>${project.build.directory}/generated-test-sources/protobuf</outputDirectory>
                 </configuration>
index 96142a0ebb39eff8c4eb943351db80e55ad465a9..dd616f8c253203986570845ab09b66f724572094 100644 (file)
@@ -123,7 +123,6 @@ import org.sonar.server.plugins.ServerExtensionInstaller;
 import org.sonar.server.plugins.privileged.PrivilegedPluginsBootstraper;
 import org.sonar.server.plugins.privileged.PrivilegedPluginsStopper;
 import org.sonar.server.property.InternalPropertiesImpl;
-import org.sonar.server.qualityprofile.QProfileLookup;
 import org.sonar.server.qualityprofile.index.ActiveRuleIndex;
 import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
 import org.sonar.server.rule.CommonRuleDefinitionsImpl;
@@ -303,7 +302,6 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer {
       XMLProfileSerializer.class,
       AnnotationProfileParser.class,
       Rules.QProfiles.class,
-      QProfileLookup.class,
 
       // rule
       RuleIndexer.class,
index 39fef5d400f3aeecd20da50aa03258fc48bfb773..1d005bfc1a1b1045ec21c421c356242070d1dd67 100644 (file)
@@ -88,7 +88,7 @@ public class ComputeEngineContainerImplTest {
     assertThat(picoContainer.getComponentAdapters())
       .hasSize(
         CONTAINER_ITSELF
-          + 79 // level 4
+          + 78 // level 4
           + 4 // content of CeConfigurationModule
           + 3 // content of CeHttpModule
           + 5 // content of CeQueueModule
index 4f1606aa633a3d230ae3edf136be5ee80cf2d799..357732fa08cd71381805b13d758bc104a5622dcf 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.db.component;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -33,7 +34,6 @@ import org.apache.commons.lang.StringUtils;
 import org.sonar.api.resources.Qualifiers;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static org.sonar.core.component.ComponentKeys.checkModuleKey;
@@ -45,49 +45,25 @@ import static org.sonar.core.component.ComponentKeys.isValidModuleKey;
  * @since 3.2
  */
 public class ComponentKeyUpdaterDao implements Dao {
-  private static final Set<String> PROJECT_OR_MODULE_QUALIFIERS = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.MODULE);
-
-  private MyBatis mybatis;
-
-  public ComponentKeyUpdaterDao(MyBatis mybatis) {
-    this.mybatis = mybatis;
-  }
 
-  public void updateKey(String projectUuid, String newKey) {
-    try (DbSession session = mybatis.openSession(true)) {
-      ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class);
-      if (mapper.countResourceByKey(newKey) > 0) {
-        throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists.");
-      }
+  private static final Set<String> PROJECT_OR_MODULE_QUALIFIERS = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.MODULE);
 
-      // must SELECT first everything
-      ResourceDto project = mapper.selectProject(projectUuid);
-      String projectOldKey = project.getKey();
-      List<ResourceDto> resources = mapper.selectProjectResources(projectUuid);
-      resources.add(project);
+  public void updateKey(DbSession dbSession, String projectUuid, String newKey) {
+    ComponentKeyUpdaterMapper mapper = dbSession.getMapper(ComponentKeyUpdaterMapper.class);
+    if (mapper.countResourceByKey(newKey) > 0) {
+      throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists.");
+    }
 
-      // and then proceed with the batch UPDATE at once
-      runBatchUpdateForAllResources(resources, projectOldKey, newKey, mapper);
+    // must SELECT first everything
+    ResourceDto project = mapper.selectProject(projectUuid);
+    String projectOldKey = project.getKey();
+    List<ResourceDto> resources = mapper.selectProjectResources(projectUuid);
+    resources.add(project);
 
-      session.commit();
-    }
-  }
+    // and then proceed with the batch UPDATE at once
+    runBatchUpdateForAllResources(resources, projectOldKey, newKey, mapper);
 
-  public Map<String, String> checkModuleKeysBeforeRenaming(String projectUuid, String stringToReplace, String replacementString) {
-    try (DbSession session = mybatis.openSession(false)) {
-      ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class);
-      Map<String, String> result = Maps.newHashMap();
-      Set<ResourceDto> modules = collectAllModules(projectUuid, stringToReplace, mapper);
-      for (ResourceDto module : modules) {
-        String newKey = computeNewKey(module.getKey(), stringToReplace, replacementString);
-        if (mapper.countResourceByKey(newKey) > 0) {
-          result.put(module.getKey(), "#duplicate_key#");
-        } else {
-          result.put(module.getKey(), newKey);
-        }
-      }
-      return result;
-    }
+    dbSession.commit();
   }
 
   public static void checkIsProjectOrModule(ComponentDto component) {
@@ -117,7 +93,8 @@ public class ComponentKeyUpdaterDao implements Dao {
     return newComponentKeys.stream().collect(Collectors.toMap(Function.identity(), key -> mapper(dbSession).countResourceByKey(key) > 0));
   }
 
-  public static String computeNewKey(String key, String stringToReplace, String replacementString) {
+  @VisibleForTesting
+  static String computeNewKey(String key, String stringToReplace, String replacementString) {
     return key.replace(stringToReplace, replacementString);
   }
 
index e62dc9a014cadd347649fd176d6cd21b32243964..dc294c166eefd11768253a2cbd75a1284c234f55 100644 (file)
@@ -26,19 +26,12 @@ import org.sonar.core.issue.FieldDiffs;
 import org.sonar.core.util.stream.Collectors;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 
 import static java.util.Collections.singletonList;
 import static org.sonar.db.DatabaseUtils.executeLargeInputs;
 
 public class IssueChangeDao implements Dao {
 
-  private final MyBatis mybatis;
-
-  public IssueChangeDao(MyBatis mybatis) {
-    this.mybatis = mybatis;
-  }
-
   public List<FieldDiffs> selectChangelogByIssue(DbSession session, String issueKey) {
     return selectByTypeAndIssueKeys(session, singletonList(issueKey), IssueChangeDto.TYPE_FIELD_CHANGE)
       .stream()
@@ -46,11 +39,9 @@ public class IssueChangeDao implements Dao {
       .collect(Collectors.toList());
   }
 
-  public List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(String componentUuid) {
-    try (DbSession session = mybatis.openSession(false)) {
-      IssueChangeMapper mapper = mapper(session);
-      return mapper.selectChangelogOfNonClosedIssuesByComponent(componentUuid, IssueChangeDto.TYPE_FIELD_CHANGE);
-    }
+  public List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(DbSession session, String componentUuid) {
+    IssueChangeMapper mapper = mapper(session);
+    return mapper.selectChangelogOfNonClosedIssuesByComponent(componentUuid, IssueChangeDto.TYPE_FIELD_CHANGE);
   }
 
   public List<IssueChangeDto> selectByTypeAndIssueKeys(DbSession session, Collection<String> issueKeys, String changeType) {
index a69638b3a8e8edd00508042e6e859c87e8359930..8e6d8ff54d8a896d0691f09278ac913a0a1cd419 100644 (file)
@@ -21,33 +21,13 @@ package org.sonar.db.loadedtemplate;
 
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 
 public class LoadedTemplateDao implements Dao {
 
-  private MyBatis mybatis;
-
-  public LoadedTemplateDao(MyBatis mybatis) {
-    this.mybatis = mybatis;
-  }
-
-  public int countByTypeAndKey(String type, String key) {
-    try (DbSession session = mybatis.openSession(false)) {
-      return countByTypeAndKey(type, key, session);
-    }
-  }
-
   public int countByTypeAndKey(String type, String key, DbSession session) {
     return session.getMapper(LoadedTemplateMapper.class).countByTypeAndKey(type, key);
   }
 
-  public void insert(LoadedTemplateDto loadedTemplateDto) {
-    try (DbSession session = mybatis.openSession(false)) {
-      insert(loadedTemplateDto, session);
-      session.commit();
-    }
-  }
-
   public void insert(LoadedTemplateDto loadedTemplateDto, DbSession session) {
     session.getMapper(LoadedTemplateMapper.class).insert(loadedTemplateDto);
   }
index e8d9d1e38a556ecefa22e10f2ce6190be32467a6..f084f93a0f9068d31099e8dd82460eb0d0f67f93 100644 (file)
@@ -23,64 +23,25 @@ import java.util.Collection;
 import java.util.Date;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 
-/**
- * @since 4.3
- */
 public class QualityGateConditionDao implements Dao {
 
-  private final MyBatis myBatis;
-
-  public QualityGateConditionDao(MyBatis myBatis) {
-    this.myBatis = myBatis;
-  }
-
   public void insert(QualityGateConditionDto newQualityGate, DbSession session) {
     mapper(session).insert(newQualityGate.setCreatedAt(new Date()));
   }
 
-  public Collection<QualityGateConditionDto> selectForQualityGate(long qGateId) {
-    try (DbSession dbSession = myBatis.openSession(false)) {
-      return selectForQualityGate(qGateId, dbSession);
-    }
-  }
-
-  public Collection<QualityGateConditionDto> selectForQualityGate(long qGateId, DbSession session) {
+  public Collection<QualityGateConditionDto> selectForQualityGate(DbSession session, long qGateId) {
     return mapper(session).selectForQualityGate(qGateId);
   }
 
-  public QualityGateConditionDto selectById(long id) {
-    try (DbSession session = myBatis.openSession(false)) {
-      return selectById(id, session);
-    }
-  }
-
   public QualityGateConditionDto selectById(long id, DbSession session) {
     return mapper(session).selectById(id);
   }
 
-  public void delete(QualityGateConditionDto qGate) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      delete(qGate, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void delete(QualityGateConditionDto qGate, DbSession session) {
     mapper(session).delete(qGate.getId());
   }
 
-  public void update(QualityGateConditionDto qGate) {
-    try (DbSession dbSession = myBatis.openSession(false)) {
-      update(qGate, dbSession);
-      dbSession.commit();
-    }
-  }
-
   public void update(QualityGateConditionDto qGate, DbSession session) {
     mapper(session).update(qGate.setUpdatedAt(new Date()));
   }
index af43e971c99d836ce1533884347ba54f8c0d5dbf..519e0dcb7bc99ed5fc1362d4eea474dcad0904a3 100644 (file)
@@ -24,99 +24,33 @@ import java.util.Date;
 import javax.annotation.CheckForNull;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 
 public class QualityGateDao implements Dao {
 
-  private final MyBatis myBatis;
-
-  public QualityGateDao(MyBatis myBatis) {
-    this.myBatis = myBatis;
-  }
-
-  public void insert(QualityGateDto newQualityGate) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      insert(session, newQualityGate);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public QualityGateDto insert(DbSession session, QualityGateDto newQualityGate) {
     mapper(session).insert(newQualityGate.setCreatedAt(new Date()));
 
     return newQualityGate;
   }
 
-  public Collection<QualityGateDto> selectAll() {
-    DbSession session = myBatis.openSession(false);
-    try {
-      return selectAll(session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public Collection<QualityGateDto> selectAll(DbSession session) {
     return mapper(session).selectAll();
   }
 
-  @CheckForNull
-  public QualityGateDto selectByName(String name) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      return selectByName(session, name);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @CheckForNull
   public QualityGateDto selectByName(DbSession session, String name) {
     return mapper(session).selectByName(name);
   }
 
-  @CheckForNull
-  public QualityGateDto selectById(long id) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      return selectById(session, id);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @CheckForNull
   public QualityGateDto selectById(DbSession session, long id) {
     return mapper(session).selectById(id);
   }
 
-  public void delete(QualityGateDto qGate) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      delete(qGate, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void delete(QualityGateDto qGate, DbSession session) {
     mapper(session).delete(qGate.getId());
   }
 
-  public void update(QualityGateDto qGate) {
-    DbSession session = myBatis.openSession(false);
-    try {
-      update(qGate, session);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void update(QualityGateDto qGate, DbSession session) {
     mapper(session).update(qGate.setUpdatedAt(new Date()));
   }
index d7fa7d4755fdf76b605e28b71c289aac21b70043..055a84f83d5e091dc01fc746c1e28859d77417c7 100644 (file)
@@ -21,9 +21,9 @@ package org.sonar.db.qualityprofile;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import java.util.Collection;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -32,7 +32,6 @@ import javax.annotation.Nullable;
 import org.sonar.api.utils.System2;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 import org.sonar.db.RowNotFoundException;
 import org.sonar.db.component.ComponentDto;
 
@@ -40,11 +39,9 @@ import static org.sonar.db.DatabaseUtils.executeLargeInputs;
 
 public class QualityProfileDao implements Dao {
 
-  private final MyBatis mybatis;
   private final System2 system;
 
-  public QualityProfileDao(MyBatis mybatis, System2 system) {
-    this.mybatis = mybatis;
+  public QualityProfileDao(System2 system) {
     this.system = system;
   }
 
@@ -85,20 +82,6 @@ public class QualityProfileDao implements Dao {
     mapper.insert(profile);
   }
 
-  /**
-   * @deprecated use {@link #insert(DbSession, QualityProfileDto, QualityProfileDto...)}
-   */
-  @Deprecated
-  public void insert(QualityProfileDto dto) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      insert(session, dto);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void update(DbSession session, QualityProfileDto profile, QualityProfileDto... otherProfiles) {
     QualityProfileMapper mapper = mapper(session);
     doUpdate(mapper, profile);
@@ -118,19 +101,6 @@ public class QualityProfileDao implements Dao {
     mapper.delete(profileId);
   }
 
-  /**
-   * @deprecated Replaced by {@link #selectAll(DbSession)}
-   */
-  @Deprecated
-  public List<QualityProfileDto> selectAll() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return mapper(session).selectAll();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public List<QualityProfileDto> selectDefaultProfiles(DbSession session, Collection<String> languageKeys) {
     return executeLargeInputs(languageKeys, mapper(session)::selectDefaultProfiles);
   }
@@ -140,26 +110,6 @@ public class QualityProfileDao implements Dao {
     return mapper(session).selectDefaultProfile(language);
   }
 
-  @CheckForNull
-  public QualityProfileDto selectDefaultProfile(String language) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectDefaultProfile(session, language);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
-  @CheckForNull
-  public QualityProfileDto selectByProjectAndLanguage(long projectId, String language) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return mapper(session).selectByProjectIdAndLanguage(projectId, language);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @CheckForNull
   public QualityProfileDto selectByProjectAndLanguage(DbSession session, String projectKey, String language) {
     return mapper(session).selectByProjectAndLanguage(projectKey, language);
@@ -169,13 +119,8 @@ public class QualityProfileDao implements Dao {
     return executeLargeInputs(languageKeys, input -> mapper(session).selectByProjectAndLanguages(projectKey, input));
   }
 
-  public List<QualityProfileDto> selectByLanguage(String language) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return mapper(session).selectByLanguage(language);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public List<QualityProfileDto> selectByLanguage(DbSession dbSession, String language) {
+    return mapper(dbSession).selectByLanguage(language);
   }
 
   @CheckForNull
@@ -183,16 +128,6 @@ public class QualityProfileDao implements Dao {
     return mapper(session).selectById(id);
   }
 
-  @CheckForNull
-  public QualityProfileDto selectById(int id) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectById(session, id);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   @CheckForNull
   public QualityProfileDto selectParentById(DbSession session, int childId) {
     return mapper(session).selectParentById(childId);
@@ -223,30 +158,17 @@ public class QualityProfileDao implements Dao {
     return executeLargeInputs(languageKeys, input -> mapper(session).selectByNameAndLanguages(name, input));
   }
 
-  public List<ComponentDto> selectProjects(String profileName, String language) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return selectProjects(profileName, language, session);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public List<ComponentDto> selectProjects(String profileName, String language, DbSession session) {
     return mapper(session).selectProjects(profileName, language);
   }
 
-  public Map<String, Long> countProjectsByProfileKey() {
-    DbSession session = mybatis.openSession(false);
-    try {
-      Map<String, Long> countByKey = Maps.newHashMap();
-      for (QualityProfileProjectCount count : mapper(session).countProjectsByProfile()) {
-        countByKey.put(count.getProfileKey(), count.getProjectCount());
-      }
-      return countByKey;
-    } finally {
-      MyBatis.closeQuietly(session);
+  public Map<String, Long> countProjectsByProfileKey(DbSession dbSession) {
+    Map<String, Long> countByKey = new HashMap<>();
+    QualityProfileMapper mapper = mapper(dbSession);
+    for (QualityProfileProjectCount count : mapper.countProjectsByProfile()) {
+      countByKey.put(count.getProfileKey(), count.getProjectCount());
     }
+    return countByKey;
   }
 
   public void insertProjectProfileAssociation(String projectUuid, String profileKey, DbSession session) {
index 98754f4df262da83b11e5c6cd5c0b45549c81159..e179f4c69105b064ba7f1befc877f06821cd88f2 100644 (file)
@@ -33,17 +33,11 @@ import org.apache.commons.dbutils.DbUtils;
 import org.apache.commons.io.IOUtils;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 import org.sonar.db.source.FileSourceDto.Type;
 
 public class FileSourceDao implements Dao {
 
   private static final Splitter END_OF_LINE_SPLITTER = Splitter.on('\n');
-  private final MyBatis mybatis;
-
-  public FileSourceDao(MyBatis myBatis) {
-    this.mybatis = myBatis;
-  }
 
   @CheckForNull
   public FileSourceDto selectSourceByFileUuid(DbSession session, String fileUuid) {
@@ -51,13 +45,8 @@ public class FileSourceDao implements Dao {
   }
 
   @CheckForNull
-  public FileSourceDto selectTest(String fileUuid) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      return mapper(session).select(fileUuid, Type.TEST);
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
+  public FileSourceDto selectTest(DbSession dbSession, String fileUuid) {
+    return mapper(dbSession).select(fileUuid, Type.TEST);
   }
 
   @CheckForNull
@@ -109,30 +98,10 @@ public class FileSourceDao implements Dao {
     }
   }
 
-  public void insert(FileSourceDto dto) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      insert(session, dto);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void insert(DbSession session, FileSourceDto dto) {
     mapper(session).insert(dto);
   }
 
-  public void update(FileSourceDto dto) {
-    DbSession session = mybatis.openSession(false);
-    try {
-      update(session, dto);
-      session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
-    }
-  }
-
   public void update(DbSession session, FileSourceDto dto) {
     mapper(session).update(dto);
   }
index 754cb376ef56aeb1372659ceddc1a623fd7a30a8..7fd979f4f40c02a76eff5ca5ccf3e6f89be285f2 100644 (file)
@@ -32,7 +32,6 @@ import org.sonar.api.user.UserQuery;
 import org.sonar.api.utils.System2;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 import org.sonar.db.RowNotFoundException;
 
 import static com.google.common.collect.FluentIterable.from;
@@ -42,20 +41,12 @@ import static org.sonar.db.DatabaseUtils.executeLargeInputs;
 
 public class UserDao implements Dao {
 
-  private final MyBatis mybatis;
   private final System2 system2;
 
-  public UserDao(MyBatis mybatis, System2 system2) {
-    this.mybatis = mybatis;
+  public UserDao(System2 system2) {
     this.system2 = system2;
   }
 
-  public UserDto selectUserById(int userId) {
-    try (DbSession session = mybatis.openSession(false)) {
-      return selectUserById(session, userId);
-    }
-  }
-
   public UserDto selectUserById(DbSession session, int userId) {
     return mapper(session).selectUser(userId);
   }
@@ -70,18 +61,6 @@ public class UserDao implements Dao {
     return executeLargeInputs(ids, mapper(session)::selectByIds);
   }
 
-  /**
-   * Search for user by login. Disabled users are ignored.
-   *
-   * @return the user, null if user not found
-   */
-  @CheckForNull
-  public UserDto selectActiveUserByLogin(String login) {
-    try (DbSession session = mybatis.openSession(false)) {
-      return selectActiveUserByLogin(session, login);
-    }
-  }
-
   @CheckForNull
   public UserDto selectActiveUserByLogin(DbSession session, String login) {
     UserMapper mapper = mapper(session);
@@ -96,16 +75,6 @@ public class UserDao implements Dao {
     return executeLargeInputs(logins, mapper(session)::selectByLogins);
   }
 
-  /**
-   * @deprecated since 6.0 please use {@link #selectByLogins(DbSession, Collection)} instead
-   */
-  @Deprecated
-  public List<UserDto> selectByLogins(Collection<String> logins) {
-    try (DbSession session = mybatis.openSession(false)) {
-      return selectByLogins(session, logins);
-    }
-  }
-
   /**
    * Gets a list users by their logins. The result does NOT contain {@code null} values for users not found, so
    * the size of result may be less than the number of keys.
@@ -117,12 +86,6 @@ public class UserDao implements Dao {
     return from(logins).transform(new LoginToUser(unordered)).filter(Predicates.notNull()).toList();
   }
 
-  public List<UserDto> selectUsers(UserQuery query) {
-    try (DbSession session = mybatis.openSession(false)) {
-      return selectUsers(session, query);
-    }
-  }
-
   public List<UserDto> selectUsers(DbSession dbSession, UserQuery query) {
     return mapper(dbSession).selectUsers(query);
   }
@@ -194,7 +157,7 @@ public class UserDao implements Dao {
     return mapper(dbSession).countByEmail(email.toLowerCase(Locale.ENGLISH)) > 0;
   }
 
-  protected UserMapper mapper(DbSession session) {
+  private static UserMapper mapper(DbSession session) {
     return session.getMapper(UserMapper.class);
   }
 
index 9ff86e83aeffc719cf99680891005329c8902b3c..af97818229bfd3e948e49d0787b72c75307e4b44 100644 (file)
@@ -47,21 +47,21 @@ public class ComponentKeyUpdaterDaoTest {
 
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
-  DbClient dbClient = db.getDbClient();
-  DbSession dbSession = db.getSession();
-  ComponentKeyUpdaterDao underTest = db.getDbClient().componentKeyUpdaterDao();
+  private DbClient dbClient = db.getDbClient();
+  private DbSession dbSession = db.getSession();
+  private ComponentKeyUpdaterDao underTest = db.getDbClient().componentKeyUpdaterDao();
 
   @Test
-  public void shouldUpdateKey() {
+  public void updateKey_changes_the_key_of_tree_of_components() {
     db.prepareDbUnit(getClass(), "shared.xml");
 
-    underTest.updateKey("B", "struts:core");
+    underTest.updateKey(dbSession, "B", "struts:core");
 
     db.assertDbUnit(getClass(), "shouldUpdateKey-result.xml", "projects");
   }
 
   @Test
-  public void update_key_does_not_updated_inactive_components() {
+  public void updateKey_does_not_updated_inactive_components() {
     OrganizationDto organizationDto = db.organizations().insert();
     ComponentDto project = db.components().insertComponent(newProjectDto(organizationDto, "A").setKey("my_project"));
     ComponentDto directory = db.components().insertComponent(newDirectory(project, "/directory").setKey("my_project:directory"));
@@ -69,7 +69,7 @@ public class ComponentKeyUpdaterDaoTest {
     ComponentDto inactiveDirectory = db.components().insertComponent(newDirectory(project, "/inactive_directory").setKey("my_project:inactive_directory").setEnabled(false));
     db.components().insertComponent(newFileDto(project, inactiveDirectory).setKey("my_project:inactive_directory/file").setEnabled(false));
 
-    underTest.updateKey("A", "your_project");
+    underTest.updateKey(dbSession, "A", "your_project");
     db.commit();
 
     List<ComponentDto> result = dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, "your_project");
@@ -78,13 +78,13 @@ public class ComponentKeyUpdaterDaoTest {
   }
 
   @Test
-  public void shouldNotUpdateKey() {
+  public void updateKey_throws_IAE_if_component_with_specified_key_does_not_exist() {
     db.prepareDbUnit(getClass(), "shared.xml");
 
     thrown.expect(IllegalArgumentException.class);
     thrown.expectMessage("Impossible to update key: a component with key \"org.struts:struts-ui\" already exists.");
 
-    underTest.updateKey("B", "org.struts:struts-ui");
+    underTest.updateKey(dbSession, "B", "org.struts:struts-ui");
   }
 
   @Test
@@ -142,7 +142,7 @@ public class ComponentKeyUpdaterDaoTest {
   }
 
   @Test
-  public void fail_with_functional_exception_when_sub_component_key_is_longer_than_authorized() {
+  public void updateKey_throws_IAE_when_sub_component_key_is_too_long() {
     OrganizationDto organizationDto = db.organizations().insert();
     ComponentDto project = newProjectDto(organizationDto, "project-uuid").setKey("old-project-key");
     db.components().insertComponent(project);
@@ -151,7 +151,7 @@ public class ComponentKeyUpdaterDaoTest {
     thrown.expect(IllegalArgumentException.class);
     thrown.expectMessage("Component key length (405) is longer than the maximum authorized (400). '" + newLongProjectKey + ":file' was provided.");
 
-    underTest.updateKey(project.uuid(), newLongProjectKey);
+    underTest.updateKey(dbSession, project.uuid(), newLongProjectKey);
   }
 
   @Test
@@ -164,17 +164,6 @@ public class ComponentKeyUpdaterDaoTest {
     underTest.bulkUpdateKey(dbSession, project.uuid(), project.key(), "my?project?key");
   }
 
-  @Test
-  public void shouldCheckModuleKeysBeforeRenaming() {
-    db.prepareDbUnit(getClass(), "shared.xml");
-
-    Map<String, String> checkResults = underTest.checkModuleKeysBeforeRenaming("A", "org.struts", "foo");
-    assertThat(checkResults.size()).isEqualTo(3);
-    assertThat(checkResults.get("org.struts:struts")).isEqualTo("foo:struts");
-    assertThat(checkResults.get("org.struts:struts-core")).isEqualTo("#duplicate_key#");
-    assertThat(checkResults.get("org.struts:struts-ui")).isEqualTo("foo:struts-ui");
-  }
-
   @Test
   public void check_component_keys() {
     db.prepareDbUnit(getClass(), "shared.xml");
index c72675ed45f888356764657b3216bb579da1b2b9..a5b46eb3c15d959c5b9d8f14b9f7279964df9dae 100644 (file)
@@ -52,7 +52,7 @@ public class IssueChangeDaoTest {
   public void selectChangelogOfNonClosedIssuesByComponent() {
     db.prepareDbUnit(getClass(), "selectChangelogOfNonClosedIssuesByComponent.xml");
 
-    List<IssueChangeDto> dtos = underTest.selectChangelogOfNonClosedIssuesByComponent("FILE_1");
+    List<IssueChangeDto> dtos = underTest.selectChangelogOfNonClosedIssuesByComponent(db.getSession(), "FILE_1");
     // no need to have ordered results (see NewDebtCalculator)
     assertThat(dtos).extracting("id").containsOnly(100L, 103L);
   }
index 2a51769a217fec28b193e6edacacd9108876d682..1be4a70d918ed98cc5ce7ebe852d6ed2f9f1faeb 100644 (file)
@@ -22,25 +22,26 @@ package org.sonar.db.loadedtemplate;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.utils.System2;
+import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
 
 public class LoadedTemplateDaoTest {
 
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
 
-  LoadedTemplateDao dao = dbTester.getDbClient().loadedTemplateDao();
+  private LoadedTemplateDao underTest = dbTester.getDbClient().loadedTemplateDao();
+  private DbSession dbSession = dbTester.getSession();
 
   @Test
   public void shouldCountByTypeAndKey() {
     dbTester.prepareDbUnit(getClass(), "shouldCountByTypeAndKey.xml");
 
-    assertThat(dao.countByTypeAndKey("DASHBOARD", "HOTSPOTS"), is(1));
-    assertThat(dao.countByTypeAndKey("DASHBOARD", "UNKNOWN"), is(0));
-    assertThat(dao.countByTypeAndKey("PROFILE", "HOTSPOTS"), is(0));
+    assertThat(underTest.countByTypeAndKey("DASHBOARD", "HOTSPOTS", dbSession)).isEqualTo(1);
+    assertThat(underTest.countByTypeAndKey("DASHBOARD", "UNKNOWN", dbSession)).isEqualTo(0);
+    assertThat(underTest.countByTypeAndKey("PROFILE", "HOTSPOTS", dbSession)).isEqualTo(0);
   }
 
   @Test
@@ -48,7 +49,8 @@ public class LoadedTemplateDaoTest {
     dbTester.prepareDbUnit(getClass(), "shouldInsert.xml");
 
     LoadedTemplateDto template = new LoadedTemplateDto("SQALE", "DASHBOARD");
-    dao.insert(template);
+    underTest.insert(template, dbSession);
+    dbSession.commit();
 
     dbTester.assertDbUnit(getClass(), "shouldInsert-result.xml", "loaded_templates");
   }
index 3a5b925cd2bc99af09846e599ff55f1a88a7f1d9..d021f28b39c8ed44126fe241fcac6c1d2e77a617 100644 (file)
@@ -22,11 +22,11 @@ package org.sonar.db.qualitygate;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.utils.System2;
+import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
-
 public class QualityGateConditionDaoTest {
 
   private static final String[] COLUMNS_WITHOUT_TIMESTAMPS = {
@@ -36,6 +36,7 @@ public class QualityGateConditionDaoTest {
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
 
+  private DbSession dbSession = dbTester.getSession();
   private QualityGateConditionDao underTest = dbTester.getDbClient().gateConditionDao();
 
   @Test
@@ -54,14 +55,14 @@ public class QualityGateConditionDaoTest {
   @Test
   public void testSelectForQualityGate() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectForQualityGate.xml");
-    assertThat(underTest.selectForQualityGate(1L)).hasSize(3);
-    assertThat(underTest.selectForQualityGate(2L)).hasSize(2);
+    assertThat(underTest.selectForQualityGate(dbSession, 1L)).hasSize(3);
+    assertThat(underTest.selectForQualityGate(dbSession, 2L)).hasSize(2);
   }
 
   @Test
   public void testSelectById() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectForQualityGate.xml");
-    QualityGateConditionDto selectById = underTest.selectById(1L);
+    QualityGateConditionDto selectById = underTest.selectById(1L, dbSession);
     assertThat(selectById).isNotNull();
     assertThat(selectById.getId()).isNotNull().isNotEqualTo(0L);
     assertThat(selectById.getMetricId()).isEqualTo(2L);
@@ -70,20 +71,26 @@ public class QualityGateConditionDaoTest {
     assertThat(selectById.getQualityGateId()).isEqualTo(1L);
     assertThat(selectById.getWarningThreshold()).isEqualTo("10");
     assertThat(selectById.getErrorThreshold()).isEqualTo("20");
-    assertThat(underTest.selectById(42L)).isNull();
+    assertThat(underTest.selectById(42L, dbSession)).isNull();
   }
 
   @Test
   public void testDelete() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectForQualityGate.xml");
-    underTest.delete(new QualityGateConditionDto().setId(1L));
+
+    underTest.delete(new QualityGateConditionDto().setId(1L), dbSession);
+    dbSession.commit();
+
     dbTester.assertDbUnitTable(getClass(), "delete-result.xml", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS);
   }
 
   @Test
   public void testUpdate() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectForQualityGate.xml");
-    underTest.update(new QualityGateConditionDto().setId(1L).setMetricId(7L).setOperator(">").setPeriod(1).setWarningThreshold("50").setErrorThreshold("80"));
+
+    underTest.update(new QualityGateConditionDto().setId(1L).setMetricId(7L).setOperator(">").setPeriod(1).setWarningThreshold("50").setErrorThreshold("80"), dbSession);
+    dbSession.commit();
+
     dbTester.assertDbUnitTable(getClass(), "update-result.xml", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS);
   }
 
@@ -93,7 +100,7 @@ public class QualityGateConditionDaoTest {
 
     underTest.deleteConditionsWithInvalidMetrics(dbTester.getSession());
     dbTester.commit();
-    
-    dbTester.assertDbUnit(getClass(), "shouldCleanConditions-result.xml", new String[]{"created_at", "updated_at"}, "quality_gate_conditions");
+
+    dbTester.assertDbUnit(getClass(), "shouldCleanConditions-result.xml", new String[] {"created_at", "updated_at"}, "quality_gate_conditions");
   }
 }
index 919a34c70427dc2e648a3be6d8d04495bcf3b1cf..834cde95798e671f747356a360d7315775d32b67 100644 (file)
@@ -24,23 +24,27 @@ import java.util.Iterator;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.utils.System2;
+import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
-
 public class QualityGateDaoTest {
 
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
 
-  QualityGateDao dao = dbTester.getDbClient().qualityGateDao();
+  private DbSession dbSession = dbTester.getSession();
+  private QualityGateDao underTest = dbTester.getDbClient().qualityGateDao();
 
   @Test
   public void testInsert() throws Exception {
     dbTester.prepareDbUnit(getClass(), "insert.xml");
     QualityGateDto newQgate = new QualityGateDto().setName("My Quality Gate");
-    dao.insert(newQgate);
+
+    underTest.insert(dbSession, newQgate);
+    dbSession.commit();
+
     dbTester.assertDbUnitTable(getClass(), "insert-result.xml", "quality_gates", "name");
     assertThat(newQgate.getId()).isNotNull();
   }
@@ -48,7 +52,9 @@ public class QualityGateDaoTest {
   @Test
   public void testSelectAll() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectAll.xml");
-    Collection<QualityGateDto> allQualityGates = dao.selectAll();
+
+    Collection<QualityGateDto> allQualityGates = underTest.selectAll(dbSession);
+
     assertThat(allQualityGates).hasSize(3);
     Iterator<QualityGateDto> gatesIterator = allQualityGates.iterator();
     assertThat(gatesIterator.next().getName()).isEqualTo("Balanced");
@@ -59,28 +65,34 @@ public class QualityGateDaoTest {
   @Test
   public void testSelectByName() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectAll.xml");
-    assertThat(dao.selectByName("Balanced").getName()).isEqualTo("Balanced");
-    assertThat(dao.selectByName("Unknown")).isNull();
+    assertThat(underTest.selectByName(dbSession, "Balanced").getName()).isEqualTo("Balanced");
+    assertThat(underTest.selectByName(dbSession, "Unknown")).isNull();
   }
 
   @Test
   public void testSelectById() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectAll.xml");
-    assertThat(dao.selectById(1L).getName()).isEqualTo("Very strict");
-    assertThat(dao.selectById(42L)).isNull();
+    assertThat(underTest.selectById(dbSession, 1L).getName()).isEqualTo("Very strict");
+    assertThat(underTest.selectById(dbSession, 42L)).isNull();
   }
 
   @Test
   public void testDelete() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectAll.xml");
-    dao.delete(new QualityGateDto().setId(1L));
+
+    underTest.delete(new QualityGateDto().setId(1L), dbSession);
+    dbSession.commit();
+
     dbTester.assertDbUnitTable(getClass(), "delete-result.xml", "quality_gates", "id", "name");
   }
 
   @Test
   public void testUpdate() throws Exception {
     dbTester.prepareDbUnit(getClass(), "selectAll.xml");
-    dao.update(new QualityGateDto().setId(1L).setName("Not so strict"));
+
+    underTest.update(new QualityGateDto().setId(1L).setName("Not so strict"), dbSession);
+    dbSession.commit();
+
     dbTester.assertDbUnitTable(getClass(), "update-result.xml", "quality_gates", "id", "name");
   }
 }
index 32113be4dce9211cf0db70fcb4b808e6a20b6179..41a7950cf357308645934b43b04535d84b6871bf 100644 (file)
@@ -64,7 +64,8 @@ public class QualityProfileDaoTest {
       .setName("ABCDE")
       .setLanguage("xoo");
 
-    underTest.insert(dto);
+    underTest.insert(dbTester.getSession(), dto);
+    dbTester.commit();
 
     dbTester.assertDbUnit(getClass(), "insert-result.xml", new String[] {"created_at", "updated_at", "rules_updated_at"}, "rules_profiles");
   }
@@ -121,7 +122,7 @@ public class QualityProfileDaoTest {
   public void find_all_is_sorted_by_profile_name() {
     dbTester.prepareDbUnit(getClass(), "select_all_is_sorted_by_profile_name.xml");
 
-    List<QualityProfileDto> dtos = underTest.selectAll();
+    List<QualityProfileDto> dtos = underTest.selectAll(dbTester.getSession());
 
     assertThat(dtos).hasSize(3);
     assertThat(dtos.get(0).getName()).isEqualTo("First");
@@ -133,11 +134,11 @@ public class QualityProfileDaoTest {
   public void get_default_profile() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    QualityProfileDto java = underTest.selectDefaultProfile("java");
+    QualityProfileDto java = underTest.selectDefaultProfile(dbTester.getSession(), "java");
     assertThat(java).isNotNull();
     assertThat(java.getKey()).isEqualTo("java_sonar_way");
 
-    assertThat(underTest.selectDefaultProfile("js")).isNull();
+    assertThat(underTest.selectDefaultProfile(dbTester.getSession(), "js")).isNull();
   }
 
   @Test
@@ -186,7 +187,7 @@ public class QualityProfileDaoTest {
   public void find_by_language() {
     dbTester.prepareDbUnit(getClass(), "select_by_language.xml");
 
-    List<QualityProfileDto> result = underTest.selectByLanguage("java");
+    List<QualityProfileDto> result = underTest.selectByLanguage(dbTester.getSession(), "java");
     assertThat(result).hasSize(2);
     assertThat(result.get(0).getName()).isEqualTo("Sonar Way 1");
     assertThat(result.get(1).getName()).isEqualTo("Sonar Way 2");
@@ -196,13 +197,13 @@ public class QualityProfileDaoTest {
   public void get_by_id() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    QualityProfileDto dto = underTest.selectById(1);
+    QualityProfileDto dto = underTest.selectById(dbTester.getSession(), 1);
     assertThat(dto.getId()).isEqualTo(1);
     assertThat(dto.getName()).isEqualTo("Sonar Way");
     assertThat(dto.getLanguage()).isEqualTo("java");
     assertThat(dto.getParentKee()).isNull();
 
-    assertThat(underTest.selectById(555)).isNull();
+    assertThat(underTest.selectById(dbTester.getSession(),555)).isNull();
   }
 
   @Test
@@ -238,26 +239,18 @@ public class QualityProfileDaoTest {
   public void select_projects() {
     dbTester.prepareDbUnit(getClass(), "projects.xml");
 
-    assertThat(underTest.selectProjects("Sonar Way", "java")).hasSize(2);
+    assertThat(underTest.selectProjects("Sonar Way", "java", dbTester.getSession())).hasSize(2);
   }
 
   @Test
   public void count_projects_by_profile() {
     dbTester.prepareDbUnit(getClass(), "projects.xml");
 
-    assertThat(underTest.countProjectsByProfileKey()).containsOnly(
+    assertThat(underTest.countProjectsByProfileKey(dbTester.getSession())).containsOnly(
       MapEntry.entry("java_sonar_way", 2L),
       MapEntry.entry("js_sonar_way", 2L));
   }
 
-  @Test
-  public void select_by_project_id_and_language() {
-    dbTester.prepareDbUnit(getClass(), "projects.xml");
-
-    QualityProfileDto dto = underTest.selectByProjectAndLanguage(1L, "java");
-    assertThat(dto.getId()).isEqualTo(1);
-  }
-
   @Test
   public void select_by_project_key_and_language() {
     dbTester.prepareDbUnit(getClass(), "projects.xml");
index 62934d1f55b8773cbc2f347b89bedead053989fb..56b474aa17a70ed3bc374c567fa67f498284bdae 100644 (file)
@@ -93,7 +93,7 @@ public class FileSourceDaoTest {
   public void insert() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    underTest.insert(new FileSourceDto()
+    underTest.insert(session, new FileSourceDto()
       .setProjectUuid("PRJ_UUID")
       .setFileUuid("FILE2_UUID")
       .setBinaryData("FILE2_BINARY_DATA".getBytes())
@@ -104,6 +104,7 @@ public class FileSourceDaoTest {
       .setCreatedAt(1500000000000L)
       .setUpdatedAt(1500000000001L)
       .setRevision("123456789"));
+    session.commit();
 
     dbTester.assertDbUnitTable(getClass(), "insert-result.xml", "file_sources",
       "project_uuid", "file_uuid", "data_hash", "line_hashes", "src_hash", "created_at", "updated_at", "data_type", "revision");
@@ -113,7 +114,7 @@ public class FileSourceDaoTest {
   public void selectLineHashes_does_not_fail_when_lineshashes_is_null() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    underTest.insert(new FileSourceDto()
+    underTest.insert(session, new FileSourceDto()
         .setProjectUuid("PRJ_UUID")
         .setFileUuid("FILE2_UUID")
         .setBinaryData("FILE2_BINARY_DATA".getBytes())
@@ -123,6 +124,7 @@ public class FileSourceDaoTest {
         .setCreatedAt(1500000000000L)
         .setUpdatedAt(1500000000001L)
         .setRevision("123456789"));
+    session.commit();
 
     assertThat(underTest.selectLineHashes(dbTester.getSession(), "FILE2_UUID")).isEmpty();
   }
@@ -131,7 +133,7 @@ public class FileSourceDaoTest {
   public void readLineHashesStream_does_not_fail_when_lineshashes_is_null() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    underTest.insert(new FileSourceDto()
+    underTest.insert(session, new FileSourceDto()
         .setProjectUuid("PRJ_UUID")
         .setFileUuid("FILE2_UUID")
         .setBinaryData("FILE2_BINARY_DATA".getBytes())
@@ -141,6 +143,7 @@ public class FileSourceDaoTest {
         .setCreatedAt(1500000000000L)
         .setUpdatedAt(1500000000001L)
         .setRevision("123456789"));
+    session.commit();
 
     boolean[] flag = {false};
     underTest.readLineHashesStream(dbTester.getSession(), "FILE2_UUID", new Function<Reader, Void>() {
@@ -159,7 +162,7 @@ public class FileSourceDaoTest {
   public void update() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    underTest.update(new FileSourceDto()
+    underTest.update(session, new FileSourceDto()
       .setId(101L)
       .setProjectUuid("PRJ_UUID")
       .setFileUuid("FILE1_UUID")
@@ -170,6 +173,7 @@ public class FileSourceDaoTest {
       .setDataType(Type.SOURCE)
       .setUpdatedAt(1500000000002L)
       .setRevision("987654321"));
+    session.commit();
 
     dbTester.assertDbUnitTable(getClass(), "update-result.xml", "file_sources",
       "project_uuid", "file_uuid", "data_hash", "line_hashes", "src_hash", "created_at", "updated_at", "data_type", "revision");
index 54e49e3b0c75704e67f818403d03ff6b1185905c..8c90812f2df2e4297302733e92fd11560e8816e7 100644 (file)
@@ -82,10 +82,10 @@ public class UserDaoTest {
   public void selectUserByLogin_ignore_inactive() {
     db.prepareDbUnit(getClass(), "selectActiveUserByLogin.xml");
 
-    UserDto user = underTest.selectUserById(50);
+    UserDto user = underTest.selectUserById(session, 50);
     assertThat(user.getLogin()).isEqualTo("inactive_user");
 
-    user = underTest.selectActiveUserByLogin("inactive_user");
+    user = underTest.selectActiveUserByLogin(session, "inactive_user");
     assertThat(user).isNull();
   }
 
@@ -93,7 +93,7 @@ public class UserDaoTest {
   public void selectUserByLogin_not_found() {
     db.prepareDbUnit(getClass(), "selectActiveUserByLogin.xml");
 
-    UserDto user = underTest.selectActiveUserByLogin("not_found");
+    UserDto user = underTest.selectActiveUserByLogin(session, "not_found");
     assertThat(user).isNull();
   }
 
@@ -101,7 +101,7 @@ public class UserDaoTest {
   public void selectUsersByLogins() {
     db.prepareDbUnit(getClass(), "selectUsersByLogins.xml");
 
-    Collection<UserDto> users = underTest.selectByLogins(asList("marius", "inactive_user", "other"));
+    Collection<UserDto> users = underTest.selectByLogins(session, asList("marius", "inactive_user", "other"));
     assertThat(users).hasSize(2);
     assertThat(users).extracting("login").containsOnly("marius", "inactive_user");
   }
@@ -109,7 +109,7 @@ public class UserDaoTest {
   @Test
   public void selectUsersByLogins_empty_logins() {
     // no need to access db
-    Collection<UserDto> users = underTest.selectByLogins(Collections.<String>emptyList());
+    Collection<UserDto> users = underTest.selectByLogins(session, Collections.emptyList());
     assertThat(users).isEmpty();
   }
 
@@ -125,7 +125,7 @@ public class UserDaoTest {
     users = underTest.selectByOrderedLogins(session, asList("U2", "U3", "U1"));
     assertThat(users).extracting("login").containsExactly("U2", "U1");
 
-    assertThat(underTest.selectByOrderedLogins(session, Collections.<String>emptyList())).isEmpty();
+    assertThat(underTest.selectByOrderedLogins(session, Collections.emptyList())).isEmpty();
   }
 
   @Test
@@ -133,7 +133,7 @@ public class UserDaoTest {
     db.prepareDbUnit(getClass(), "selectUsersByQuery.xml");
 
     UserQuery query = UserQuery.builder().includeDeactivated().build();
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).hasSize(2);
   }
 
@@ -142,7 +142,7 @@ public class UserDaoTest {
     db.prepareDbUnit(getClass(), "selectUsersByQuery.xml");
 
     UserQuery query = UserQuery.ALL_ACTIVES;
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).hasSize(1);
     assertThat(users.get(0).getName()).isEqualTo("Marius");
   }
@@ -152,7 +152,7 @@ public class UserDaoTest {
     db.prepareDbUnit(getClass(), "selectUsersByQuery.xml");
 
     UserQuery query = UserQuery.builder().logins("marius", "john").build();
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).hasSize(1);
     assertThat(users.get(0).getName()).isEqualTo("Marius");
   }
@@ -162,7 +162,7 @@ public class UserDaoTest {
     db.prepareDbUnit(getClass(), "selectUsersByText.xml");
 
     UserQuery query = UserQuery.builder().searchText("sbr").build();
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).hasSize(1);
     assertThat(users.get(0).getLogin()).isEqualTo("sbrandhof");
   }
@@ -172,7 +172,7 @@ public class UserDaoTest {
     db.prepareDbUnit(getClass(), "selectUsersByText.xml");
 
     UserQuery query = UserQuery.builder().searchText("Simon").build();
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).hasSize(1);
     assertThat(users.get(0).getLogin()).isEqualTo("sbrandhof");
   }
@@ -184,7 +184,7 @@ public class UserDaoTest {
     UserQuery query = UserQuery.builder().searchText("%s%").build();
     // we expect really a login or name containing the 3 characters "%s%"
 
-    List<UserDto> users = underTest.selectUsers(query);
+    List<UserDto> users = underTest.selectUsers(session, query);
     assertThat(users).isEmpty();
   }
 
@@ -195,13 +195,13 @@ public class UserDaoTest {
     UserDto user2 = insertUser(true);
     UserDto root2 = insertRootUser(newUserDto());
 
-    assertThat(underTest.selectUsers(UserQuery.builder().build()))
+    assertThat(underTest.selectUsers(session, UserQuery.builder().build()))
       .extracting(UserDto::getLogin)
       .containsOnly(user1.getLogin(), user2.getLogin(), root1.getLogin(), root2.getLogin());
-    assertThat(underTest.selectUsers(UserQuery.builder().mustBeRoot().build()))
+    assertThat(underTest.selectUsers(session, UserQuery.builder().mustBeRoot().build()))
       .extracting(UserDto::getLogin)
       .containsOnly(root1.getLogin(), root2.getLogin());
-    assertThat(underTest.selectUsers(UserQuery.builder().mustNotBeRoot().build()))
+    assertThat(underTest.selectUsers(session, UserQuery.builder().mustNotBeRoot().build()))
       .extracting(UserDto::getLogin)
       .containsOnly(user1.getLogin(), user2.getLogin());
   }
@@ -322,7 +322,7 @@ public class UserDaoTest {
     underTest.insert(db.getSession(), userDto);
     db.getSession().commit();
 
-    UserDto user = underTest.selectActiveUserByLogin("john");
+    UserDto user = underTest.selectActiveUserByLogin(session, "john");
     assertThat(user).isNotNull();
     assertThat(user.getId()).isNotNull();
     assertThat(user.getLogin()).isEqualTo("john");
@@ -442,7 +442,7 @@ public class UserDaoTest {
     String login = "does_not_exist";
     boolean deactivated = underTest.deactivateUserByLogin(session, login);
     assertThat(deactivated).isFalse();
-    assertThat(underTest.selectActiveUserByLogin(login)).isNull();
+    assertThat(underTest.selectActiveUserByLogin(session, login)).isNull();
   }
 
   @Test
index 735a5ba891c0030faac6e0abdba31da7d492cd1c..02642279a5c7ed69cba08afd9bb17a928a724fd6 100644 (file)
@@ -59,7 +59,7 @@ public class ComponentService {
     userSession.checkComponentPermission(UserRole.ADMIN, component);
     checkIsProjectOrModule(component);
     checkProjectOrModuleKeyFormat(newKey);
-    dbClient.componentKeyUpdaterDao().updateKey(component.uuid(), newKey);
+    dbClient.componentKeyUpdaterDao().updateKey(dbSession, component.uuid(), newKey);
     dbSession.commit();
     index(component.uuid());
   }
index 8dbb3c8cf85919ef6430ac5aafbadfde1f424879..d0ede5918186cd52c5c730126a013e5924c9f539 100644 (file)
@@ -28,6 +28,7 @@ import java.util.Map;
 import org.sonar.api.measures.CoreMetrics;
 import org.sonar.core.issue.DefaultIssue;
 import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.issue.IssueChangeDto;
 import org.sonar.server.computation.task.projectanalysis.component.Component;
 import org.sonar.server.computation.task.projectanalysis.measure.Measure;
@@ -63,7 +64,7 @@ public class NewEffortAggregator extends IssueVisitor {
   private NewEffortCounter counter = null;
 
   public NewEffortAggregator(NewEffortCalculator calculator, PeriodHolder periodHolder, DbClient dbClient,
-                             MetricRepository metricRepository, MeasureRepository measureRepository) {
+    MetricRepository metricRepository, MeasureRepository measureRepository) {
     this.calculator = calculator;
     this.periodHolder = periodHolder;
     this.dbClient = dbClient;
@@ -76,9 +77,11 @@ public class NewEffortAggregator extends IssueVisitor {
 
   @Override
   public void beforeComponent(Component component) {
-    List<IssueChangeDto> changes = dbClient.issueChangeDao().selectChangelogOfNonClosedIssuesByComponent(component.getUuid());
-    for (IssueChangeDto change : changes) {
-      changesByIssueUuid.put(change.getIssueKey(), change);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      List<IssueChangeDto> changes = dbClient.issueChangeDao().selectChangelogOfNonClosedIssuesByComponent(dbSession, component.getUuid());
+      for (IssueChangeDto change : changes) {
+        changesByIssueUuid.put(change.getIssueKey(), change);
+      }
     }
 
     counter = new NewEffortCounter(calculator);
index d8154f73c5b9a9cc4a4303124a423792dc5c4266..a9b4ee85bc4feafbca5251ceac5234121f8b78e6 100644 (file)
  */
 package org.sonar.server.computation.task.projectanalysis.qualitygate;
 
-import com.google.common.base.Function;
 import com.google.common.base.Optional;
-import org.sonar.db.qualitygate.QualityGateConditionDao;
+import java.util.Collection;
+import org.sonar.core.util.stream.Collectors;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.qualitygate.QualityGateConditionDto;
-import org.sonar.db.qualitygate.QualityGateDao;
 import org.sonar.db.qualitygate.QualityGateDto;
 import org.sonar.server.computation.task.projectanalysis.metric.Metric;
 import org.sonar.server.computation.task.projectanalysis.metric.MetricRepository;
 
-import static com.google.common.collect.FluentIterable.from;
-
 public class QualityGateServiceImpl implements QualityGateService {
-  private final QualityGateDao qualityGateDao;
-  private final QualityGateConditionDao conditionDao;
-  private final Function<QualityGateConditionDto, Condition> conditionDtoToBean;
-
-  public QualityGateServiceImpl(QualityGateDao qualityGateDao, QualityGateConditionDao conditionDao, final MetricRepository metricRepository) {
-    this.qualityGateDao = qualityGateDao;
-    this.conditionDao = conditionDao;
-    this.conditionDtoToBean = (QualityGateConditionDto input) -> {
-      Metric metric = metricRepository.getById(input.getMetricId());
-      return new Condition(metric, input.getOperator(), input.getErrorThreshold(), input.getWarningThreshold(), input.getPeriod() != null);
-    };
+
+  private final DbClient dbClient;
+  private final MetricRepository metricRepository;
+
+  public QualityGateServiceImpl(DbClient dbClient, final MetricRepository metricRepository) {
+    this.dbClient = dbClient;
+    this.metricRepository = metricRepository;
   }
 
   @Override
   public Optional<QualityGate> findById(long id) {
-    QualityGateDto qualityGateDto = qualityGateDao.selectById(id);
-    if (qualityGateDto == null) {
-      return Optional.absent();
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectById(dbSession, id);
+      if (qualityGateDto == null) {
+        return Optional.absent();
+      }
+      return Optional.of(toQualityGate(dbSession, qualityGateDto));
     }
-    return Optional.of(toQualityGate(qualityGateDto));
   }
 
-  private QualityGate toQualityGate(QualityGateDto qualityGateDto) {
-    Iterable<Condition> conditions = from(conditionDao.selectForQualityGate(qualityGateDto.getId())).transform(conditionDtoToBean);
+  private QualityGate toQualityGate(DbSession dbSession, QualityGateDto qualityGateDto) {
+    Collection<QualityGateConditionDto> dtos = dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getId());
+
+    Iterable<Condition> conditions = dtos.stream()
+      .map(input -> {
+        Metric metric = metricRepository.getById(input.getMetricId());
+        return new Condition(metric, input.getOperator(), input.getErrorThreshold(), input.getWarningThreshold(), input.getPeriod() != null);
+      })
+      .collect(Collectors.toList(dtos.size()));
 
     return new QualityGate(qualityGateDto.getId(), qualityGateDto.getName(), conditions);
   }
index 98090196ea8c70bcb262b58304c38a91844c9ce1..3f043c34ce4de4c7991e4ce302a584e1045c9d9a 100644 (file)
@@ -29,8 +29,8 @@ import java.util.Map;
 import java.util.Optional;
 import org.sonar.api.server.ServerSide;
 import org.sonar.api.utils.log.Loggers;
+import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 import org.sonar.db.version.SqTables;
 import org.sonar.server.component.index.ComponentIndexDefinition;
 import org.sonar.server.es.BulkIndexer;
@@ -60,11 +60,11 @@ public class BackendCleanup {
     "schema_migrations", BackendCleanup::truncateSchemaMigrations);
 
   private final EsClient esClient;
-  private final MyBatis myBatis;
+  private final DbClient dbClient;
 
-  public BackendCleanup(EsClient esClient, MyBatis myBatis) {
+  public BackendCleanup(EsClient esClient, DbClient dbClient) {
     this.esClient = esClient;
-    this.myBatis = myBatis;
+    this.dbClient = dbClient;
   }
 
   public void clearAll() {
@@ -73,7 +73,7 @@ public class BackendCleanup {
   }
 
   public void clearDb() {
-    try (DbSession dbSession = myBatis.openSession(false);
+    try (DbSession dbSession = dbClient.openSession(false);
       Connection connection = dbSession.getConnection();
       Statement ddlStatement = connection.createStatement()) {
       for (String tableName : SqTables.TABLES) {
@@ -105,7 +105,7 @@ public class BackendCleanup {
    * Please be careful when updating this method as it's called by Orchestrator.
    */
   public void resetData() {
-    try (DbSession dbSession = myBatis.openSession(false);
+    try (DbSession dbSession = dbClient.openSession(false);
       Connection connection = dbSession.getConnection()) {
 
       truncateAnalysisTables(connection);
index bd92fdce7896c5ebb0fe6f13686b8f7996254d1f..b80458ed32eb1b8f0903c4b0891eeeea693eb4f3 100644 (file)
@@ -148,7 +148,6 @@ import org.sonar.server.qualityprofile.QProfileLookup;
 import org.sonar.server.qualityprofile.QProfileProjectOperations;
 import org.sonar.server.qualityprofile.QProfileReset;
 import org.sonar.server.qualityprofile.QProfileService;
-import org.sonar.server.qualityprofile.QProfiles;
 import org.sonar.server.qualityprofile.RuleActivator;
 import org.sonar.server.qualityprofile.RuleActivatorContextFactory;
 import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
@@ -261,7 +260,6 @@ public class PlatformLevel4 extends PlatformLevel {
       XMLProfileParser.class,
       XMLProfileSerializer.class,
       AnnotationProfileParser.class,
-      QProfiles.class,
       QProfileLookup.class,
       QProfileProjectOperations.class,
       QProfileComparison.class,
index f2e08156c0b7cff2776498abb1699f01c629ddb8..e4fbf4373042362f08741de234e905bcc3dea380 100644 (file)
@@ -119,11 +119,11 @@ public class QualityGateConditionsUpdater {
   }
 
   private Collection<QualityGateConditionDto> getConditions(DbSession dbSession, long qGateId, @Nullable Long conditionId) {
-    Collection<QualityGateConditionDto> conditions = dbClient.gateConditionDao().selectForQualityGate(qGateId, dbSession);
+    Collection<QualityGateConditionDto> conditions = dbClient.gateConditionDao().selectForQualityGate(dbSession, qGateId);
     if (conditionId == null) {
       return conditions;
     }
-    return dbClient.gateConditionDao().selectForQualityGate(qGateId, dbSession).stream()
+    return dbClient.gateConditionDao().selectForQualityGate(dbSession, qGateId).stream()
       .filter(condition -> condition.getId() != conditionId)
       .collect(Collectors.toList());
   }
index 6726ff563ca5c2052eff7458f6a18ec199944710..6d7657d1988cb7b574a6ba4507f761141de3de79 100644 (file)
@@ -39,26 +39,26 @@ public class QualityGateUpdater {
   }
 
   public QualityGateDto create(DbSession dbSession, String name) {
-    validateQualityGate(null, name);
+    validateQualityGate(dbSession, null, name);
     QualityGateDto newQualityGate = new QualityGateDto().setName(name);
     dbClient.qualityGateDao().insert(dbSession, newQualityGate);
     return newQualityGate;
   }
 
-  private void validateQualityGate(@Nullable Long qGateId, @Nullable String name) {
+  private void validateQualityGate(DbSession dbSession, @Nullable Long qGateId, @Nullable String name) {
     Errors errors = new Errors();
     if (isNullOrEmpty(name)) {
       errors.add(Message.of(Validation.CANT_BE_EMPTY_MESSAGE, "Name"));
     } else {
-      checkQualityGateDoesNotAlreadyExist(qGateId, name, errors);
+      checkQualityGateDoesNotAlreadyExist(dbSession, qGateId, name, errors);
     }
     if (!errors.isEmpty()) {
       throw BadRequestException.create(errors);
     }
   }
 
-  private void checkQualityGateDoesNotAlreadyExist(@Nullable Long qGateId, String name, Errors errors) {
-    QualityGateDto existingQgate = dbClient.qualityGateDao().selectByName(name);
+  private void checkQualityGateDoesNotAlreadyExist(DbSession dbSession, @Nullable Long qGateId, String name, Errors errors) {
+    QualityGateDto existingQgate = dbClient.qualityGateDao().selectByName(dbSession, name);
     boolean isModifyingCurrentQgate = qGateId != null && existingQgate != null && existingQgate.getId().equals(qGateId);
     errors.check(isModifyingCurrentQgate || existingQgate == null, Validation.IS_ALREADY_USED_MESSAGE, "Name");
   }
index 359c8cfa462e2f74be63a38af3122ba1d54e4afa..4aaad198de878e7fc9e10742d7502661c6d0eb24 100644 (file)
@@ -29,7 +29,6 @@ import org.sonar.api.measures.MetricFinder;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.permission.OrganizationPermission;
 import org.sonar.db.property.PropertiesDao;
@@ -81,51 +80,50 @@ public class QualityGates {
 
   public QualityGateDto rename(long idToRename, String name) {
     checkIsSystemAdministrator();
-    QualityGateDto toRename = getNonNullQgate(idToRename);
-    validateQualityGate(idToRename, name);
-    toRename.setName(name);
-    dao.update(toRename);
-    return toRename;
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      QualityGateDto toRename = getNonNullQgate(idToRename);
+      validateQualityGate(dbSession, idToRename, name);
+      toRename.setName(name);
+      dao.update(toRename, dbSession);
+      dbSession.commit();
+      return toRename;
+    }
   }
 
   public QualityGateDto copy(long sourceId, String destinationName) {
     checkIsSystemAdministrator();
     getNonNullQgate(sourceId);
-    validateQualityGate(null, destinationName);
-    QualityGateDto destinationGate = new QualityGateDto().setName(destinationName);
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      validateQualityGate(dbSession, null, destinationName);
+      QualityGateDto destinationGate = new QualityGateDto().setName(destinationName);
       dao.insert(dbSession, destinationGate);
-      for (QualityGateConditionDto sourceCondition : conditionDao.selectForQualityGate(sourceId, dbSession)) {
+      for (QualityGateConditionDto sourceCondition : conditionDao.selectForQualityGate(dbSession, sourceId)) {
         conditionDao.insert(new QualityGateConditionDto().setQualityGateId(destinationGate.getId())
           .setMetricId(sourceCondition.getMetricId()).setOperator(sourceCondition.getOperator())
           .setWarningThreshold(sourceCondition.getWarningThreshold()).setErrorThreshold(sourceCondition.getErrorThreshold()).setPeriod(sourceCondition.getPeriod()),
           dbSession);
       }
       dbSession.commit();
-    } finally {
-      MyBatis.closeQuietly(dbSession);
+      return destinationGate;
     }
-    return destinationGate;
   }
 
   public Collection<QualityGateDto> list() {
-    return dao.selectAll();
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      return dao.selectAll(dbSession);
+    }
   }
 
   public void delete(long idToDelete) {
     checkIsSystemAdministrator();
     QualityGateDto qGate = getNonNullQgate(idToDelete);
-    DbSession session = dbClient.openSession(false);
-    try {
+    try (DbSession session = dbClient.openSession(false)) {
       if (isDefault(qGate)) {
         propertiesDao.deleteGlobalProperty(SONAR_QUALITYGATE_PROPERTY, session);
       }
       propertiesDao.deleteProjectProperties(SONAR_QUALITYGATE_PROPERTY, Long.toString(idToDelete), session);
       dao.delete(qGate, session);
       session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
@@ -151,26 +149,32 @@ public class QualityGates {
     Long defaultId = getDefaultId();
     if (defaultId == null) {
       return null;
-    } else {
-      return dao.selectById(defaultId);
+    }
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      return dao.selectById(dbSession, defaultId);
     }
   }
 
   public Collection<QualityGateConditionDto> listConditions(long qGateId) {
-    Collection<QualityGateConditionDto> conditionsForGate = conditionDao.selectForQualityGate(qGateId);
-    for (QualityGateConditionDto condition : conditionsForGate) {
-      Metric metric = metricFinder.findById((int) condition.getMetricId());
-      if (metric == null) {
-        throw new IllegalStateException("Could not find metric with id " + condition.getMetricId());
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      Collection<QualityGateConditionDto> conditionsForGate = conditionDao.selectForQualityGate(dbSession, qGateId);
+      for (QualityGateConditionDto condition : conditionsForGate) {
+        Metric metric = metricFinder.findById((int) condition.getMetricId());
+        if (metric == null) {
+          throw new IllegalStateException("Could not find metric with id " + condition.getMetricId());
+        }
+        condition.setMetricKey(metric.getKey());
       }
-      condition.setMetricKey(metric.getKey());
+      return conditionsForGate;
     }
-    return conditionsForGate;
   }
 
   public void deleteCondition(Long condId) {
     checkIsSystemAdministrator();
-    conditionDao.delete(getNonNullCondition(condId));
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      conditionDao.delete(getNonNullCondition(dbSession, condId), dbSession);
+      dbSession.commit();
+    }
   }
 
   public void dissociateProject(DbSession dbSession, Long qGateId, ComponentDto project) {
@@ -207,35 +211,37 @@ public class QualityGates {
   }
 
   private QualityGateDto getNonNullQgate(String name) {
-    QualityGateDto qGate = dao.selectByName(name);
-    if (qGate == null) {
-      throw new NotFoundException("There is no quality gate with name=" + name);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      QualityGateDto qGate = dao.selectByName(dbSession, name);
+      if (qGate == null) {
+        throw new NotFoundException("There is no quality gate with name=" + name);
+      }
+      return qGate;
     }
-    return qGate;
   }
 
-  private QualityGateConditionDto getNonNullCondition(long id) {
-    QualityGateConditionDto condition = conditionDao.selectById(id);
+  private QualityGateConditionDto getNonNullCondition(DbSession dbSession, long id) {
+    QualityGateConditionDto condition = conditionDao.selectById(id, dbSession);
     if (condition == null) {
       throw new NotFoundException("There is no condition with id=" + id);
     }
     return condition;
   }
 
-  private void validateQualityGate(@Nullable Long updatingQgateId, @Nullable String name) {
+  private void validateQualityGate(DbSession dbSession, @Nullable Long updatingQgateId, @Nullable String name) {
     Errors errors = new Errors();
     if (Strings.isNullOrEmpty(name)) {
       errors.add(Message.of(Validation.CANT_BE_EMPTY_MESSAGE, "Name"));
     } else {
-      checkQgateNotAlreadyExists(updatingQgateId, name, errors);
+      checkQgateNotAlreadyExists(dbSession, updatingQgateId, name, errors);
     }
     if (!errors.isEmpty()) {
       throw BadRequestException.create(errors);
     }
   }
 
-  private void checkQgateNotAlreadyExists(@Nullable Long updatingQgateId, String name, Errors errors) {
-    QualityGateDto existingQgate = dao.selectByName(name);
+  private void checkQgateNotAlreadyExists(DbSession dbSession, @Nullable Long updatingQgateId, String name, Errors errors) {
+    QualityGateDto existingQgate = dao.selectByName(dbSession, name);
     boolean isModifyingCurrentQgate = updatingQgateId != null && existingQgate != null && existingQgate.getId().equals(updatingQgateId);
     errors.check(isModifyingCurrentQgate || existingQgate == null, Validation.IS_ALREADY_USED_MESSAGE, "Name");
   }
index 3d09b014fadf7da2bc5cf8ba60353b0a1908cf88..a1d0db5ba7819cbab63a8075d898c7becf88514d 100644 (file)
@@ -92,7 +92,7 @@ public class SelectAction implements QualityGatesWsAction {
 
   private void doHandle(SelectWsRequest request) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      checkQualityGate(dbClient, request.getGateId());
+      checkQualityGate(dbSession, request.getGateId());
       ComponentDto project = getProject(dbSession, request.getProjectId(), request.getProjectKey());
 
       dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto()
@@ -136,7 +136,7 @@ public class SelectAction implements QualityGatesWsAction {
     }
   }
 
-  private static void checkQualityGate(DbClient dbClient, long id) {
-    checkFound(dbClient.qualityGateDao().selectById(id), "There is no quality gate with id=" + id);
+  private void checkQualityGate(DbSession dbSession, long id) {
+    checkFound(dbClient.qualityGateDao().selectById(dbSession, id), "There is no quality gate with id=" + id);
   }
 }
index 1a550124f4f9b5b6edbfd641661735d34afc7a23..c947646237ef6cde5ce98ce9ca371d85aded6f09 100644 (file)
@@ -24,7 +24,6 @@ import com.google.common.collect.Iterables;
 import java.util.List;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nonnull;
-import org.sonar.api.ce.ComputeEngineSide;
 import org.sonar.api.server.ServerSide;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
@@ -33,7 +32,6 @@ import org.sonar.db.qualityprofile.QualityProfileDto;
 import static com.google.common.collect.Lists.newArrayList;
 
 @ServerSide
-@ComputeEngineSide
 public class QProfileLookup {
 
   private final DbClient db;
@@ -42,98 +40,31 @@ public class QProfileLookup {
     this.db = db;
   }
 
-  public List<QProfile> allProfiles() {
-    return toQProfiles(db.qualityProfileDao().selectAll());
+  public List<QProfile> allProfiles(DbSession dbSession) {
+    return toQProfiles(db.qualityProfileDao().selectAll(dbSession));
   }
 
-  public List<QProfile> profiles(String language) {
-    return toQProfiles(db.qualityProfileDao().selectByLanguage(language));
-  }
-
-  @CheckForNull
-  public QProfile profile(int id) {
-    DbSession session = db.openSession(false);
-    try {
-      return profile(id, session);
-    } finally {
-      session.close();
-    }
-  }
-
-  @CheckForNull
-  public QProfile profile(int id, DbSession session) {
-    QualityProfileDto dto = findQualityProfile(id, session);
-    if (dto != null) {
-      return QProfile.from(dto);
-    }
-    return null;
-  }
-
-  public QProfile profile(String name, String language, DbSession session) {
-    QualityProfileDto dto = findQualityProfile(name, language, session);
-    if (dto != null) {
-      return QProfile.from(dto);
-    }
-    return null;
+  public List<QProfile> profiles(DbSession dbSession, String language) {
+    return toQProfiles(db.qualityProfileDao().selectByLanguage(dbSession, language));
   }
 
   @CheckForNull
   public QProfile profile(String name, String language) {
-    DbSession session = db.openSession(false);
-    try {
-      return profile(name, language, session);
-    } finally {
-      session.close();
-    }
-  }
-
-  @CheckForNull
-  public QProfile parent(QProfile profile) {
-    DbSession session = db.openSession(false);
-    try {
-      String parent = profile.parent();
-      if (parent != null) {
-        QualityProfileDto parentDto = findQualityProfile(parent, profile.language(), session);
-        if (parentDto != null) {
-          return QProfile.from(parentDto);
-        }
+    try (DbSession dbSession = db.openSession(false)) {
+      QualityProfileDto dto = findQualityProfile(name, language, dbSession);
+      if (dto != null) {
+        return QProfile.from(dto);
       }
       return null;
-    } finally {
-      session.close();
-    }
-  }
-
-  public List<QProfile> children(QProfile profile) {
-    DbSession session = db.openSession(false);
-    try {
-      return children(profile, session);
-    } finally {
-      session.close();
     }
   }
 
-  public List<QProfile> children(QProfile profile, DbSession session) {
-    return toQProfiles(db.qualityProfileDao().selectChildren(session, profile.key()));
-  }
-
   public List<QProfile> ancestors(QualityProfileDto profile, DbSession session) {
     List<QProfile> ancestors = newArrayList();
     incrementAncestors(QProfile.from(profile), ancestors, session);
     return ancestors;
   }
 
-  public List<QProfile> ancestors(QProfile profile) {
-    List<QProfile> ancestors = newArrayList();
-    DbSession session = db.openSession(false);
-    try {
-      incrementAncestors(profile, ancestors, session);
-    } finally {
-      session.close();
-    }
-    return ancestors;
-  }
-
   private void incrementAncestors(QProfile profile, List<QProfile> ancestors, DbSession session) {
     if (profile.parent() != null) {
       QualityProfileDto parentDto = db.qualityProfileDao().selectParentById(session, profile.id());
@@ -150,11 +81,6 @@ public class QProfileLookup {
     return newArrayList(Iterables.transform(dtos, ToQProfile.INSTANCE));
   }
 
-  @CheckForNull
-  private QualityProfileDto findQualityProfile(int id, DbSession session) {
-    return db.qualityProfileDao().selectById(session, id);
-  }
-
   @CheckForNull
   private QualityProfileDto findQualityProfile(String name, String language, DbSession session) {
     return db.qualityProfileDao().selectByNameAndLanguage(name, language, session);
diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java
deleted file mode 100644 (file)
index aded21d..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.server.qualityprofile;
-
-import java.util.List;
-import javax.annotation.CheckForNull;
-import org.sonar.api.server.ServerSide;
-import org.sonar.db.DbClient;
-import org.sonar.db.qualityprofile.QualityProfileDto;
-
-/**
- * Use {@link org.sonar.server.qualityprofile.QProfileService} instead
- */
-@Deprecated
-@ServerSide
-public class QProfiles {
-
-  private final QProfileLookup profileLookup;
-  private final DbClient dbClient;
-
-  public QProfiles(QProfileLookup profileLookup, DbClient dbClient) {
-    this.profileLookup = profileLookup;
-    this.dbClient = dbClient;
-  }
-
-  public List<QProfile> allProfiles() {
-    return profileLookup.allProfiles();
-  }
-
-  public List<QProfile> profilesByLanguage(String language) {
-    return profileLookup.profiles(language);
-  }
-
-  /**
-   * Used in /project/profile and in /api/profiles
-   */
-  @CheckForNull
-  public QProfile findProfileByProjectAndLanguage(long projectId, String language) {
-    QualityProfileDto dto = dbClient.qualityProfileDao().selectByProjectAndLanguage(projectId, language);
-    if (dto != null) {
-      return QProfile.from(dto);
-    }
-    return null;
-  }
-
-}
index b81fa6684c7c03addc85ec9b222ea8241bc8edf3..11eb3cf05ac041169a9511daed02e92f328e4f06 100644 (file)
@@ -68,74 +68,72 @@ public class SearchDataLoader {
   SearchData load(SearchWsRequest request) {
     validateRequest(request);
 
-    return new SearchData()
-      .setProfiles(findProfiles(request))
-      .setActiveRuleCountByProfileKey(activeRuleIndex.countAllByQualityProfileKey())
-      .setActiveDeprecatedRuleCountByProfileKey(activeRuleIndex.countAllDeprecatedByQualityProfileKey())
-      .setProjectCountByProfileKey(dbClient.qualityProfileDao().countProjectsByProfileKey());
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      return new SearchData()
+        .setProfiles(findProfiles(dbSession, request))
+        .setActiveRuleCountByProfileKey(activeRuleIndex.countAllByQualityProfileKey())
+        .setActiveDeprecatedRuleCountByProfileKey(activeRuleIndex.countAllDeprecatedByQualityProfileKey())
+        .setProjectCountByProfileKey(dbClient.qualityProfileDao().countProjectsByProfileKey(dbSession));
+    }
   }
 
-  private List<QProfile> findProfiles(SearchWsRequest request) {
+  private List<QProfile> findProfiles(DbSession dbSession, SearchWsRequest request) {
     Collection<QProfile> profiles;
     if (askDefaultProfiles(request)) {
-      profiles = findDefaultProfiles(request);
+      profiles = findDefaultProfiles(dbSession, request);
     } else if (hasComponentKey(request)) {
-      profiles = findProjectProfiles(request);
+      profiles = findProjectProfiles(dbSession, request);
     } else {
-      profiles = findAllProfiles(request);
+      profiles = findAllProfiles(dbSession, request);
     }
 
     return profiles.stream().sorted(QProfileComparator.INSTANCE).collect(Collectors.toList());
   }
 
-  private Collection<QProfile> findDefaultProfiles(SearchWsRequest request) {
+  private Collection<QProfile> findDefaultProfiles(DbSession dbSession, SearchWsRequest request) {
     String profileName = request.getProfileName();
 
     Set<String> languageKeys = getLanguageKeys();
-    try (DbSession dbSession = dbClient.openSession(false)) {
-      Map<String, QProfile> qualityProfiles = new HashMap<>(languageKeys.size());
-
-      Set<String> missingLanguageKeys = lookupByProfileName(dbSession, qualityProfiles, languageKeys, profileName);
-      Set<String> noDefaultProfileLanguageKeys = lookupDefaults(dbSession, qualityProfiles, missingLanguageKeys);
+    Map<String, QProfile> qualityProfiles = new HashMap<>(languageKeys.size());
 
-      if (!noDefaultProfileLanguageKeys.isEmpty()) {
-        throw new IllegalStateException(format("No quality profile can been found on language(s) '%s'", noDefaultProfileLanguageKeys));
-      }
+    Set<String> missingLanguageKeys = lookupByProfileName(dbSession, qualityProfiles, languageKeys, profileName);
+    Set<String> noDefaultProfileLanguageKeys = lookupDefaults(dbSession, qualityProfiles, missingLanguageKeys);
 
-      return qualityProfiles.values();
+    if (!noDefaultProfileLanguageKeys.isEmpty()) {
+      throw new IllegalStateException(format("No quality profile can been found on language(s) '%s'", noDefaultProfileLanguageKeys));
     }
+
+    return qualityProfiles.values();
   }
 
-  private Collection<QProfile> findProjectProfiles(SearchWsRequest request) {
+  private Collection<QProfile> findProjectProfiles(DbSession dbSession, SearchWsRequest request) {
     String componentKey = request.getProjectKey();
     String profileName = request.getProfileName();
 
     Set<String> languageKeys = getLanguageKeys();
-    try (DbSession dbSession = dbClient.openSession(false)) {
-      Map<String, QProfile> qualityProfiles = new HashMap<>(languageKeys.size());
+    Map<String, QProfile> qualityProfiles = new HashMap<>(languageKeys.size());
 
-      // look up profiles by profileName (if any) for each language
-      Set<String> unresolvedLanguages = lookupByProfileName(dbSession, qualityProfiles, languageKeys, profileName);
-      // look up profile by componentKey for each language for which we don't have one yet
-      Set<String> stillUnresolvedLanguages = lookupByModuleKey(dbSession, qualityProfiles, unresolvedLanguages, componentKey);
-      // look up profile by default for each language for which we don't have one yet
-      Set<String> noDefaultProfileLanguages = lookupDefaults(dbSession, qualityProfiles, stillUnresolvedLanguages);
+    // look up profiles by profileName (if any) for each language
+    Set<String> unresolvedLanguages = lookupByProfileName(dbSession, qualityProfiles, languageKeys, profileName);
+    // look up profile by componentKey for each language for which we don't have one yet
+    Set<String> stillUnresolvedLanguages = lookupByModuleKey(dbSession, qualityProfiles, unresolvedLanguages, componentKey);
+    // look up profile by default for each language for which we don't have one yet
+    Set<String> noDefaultProfileLanguages = lookupDefaults(dbSession, qualityProfiles, stillUnresolvedLanguages);
 
-      if (!noDefaultProfileLanguages.isEmpty()) {
-        throw new IllegalStateException(format("No quality profile can been found on language(s) '%s' for project '%s'", noDefaultProfileLanguages, componentKey));
-      }
-
-      return qualityProfiles.values();
+    if (!noDefaultProfileLanguages.isEmpty()) {
+      throw new IllegalStateException(format("No quality profile can been found on language(s) '%s' for project '%s'", noDefaultProfileLanguages, componentKey));
     }
+
+    return qualityProfiles.values();
   }
 
-  private List<QProfile> findAllProfiles(SearchWsRequest request) {
+  private List<QProfile> findAllProfiles(DbSession dbSession, SearchWsRequest request) {
     String language = request.getLanguage();
 
     if (language == null) {
-      return profileLookup.allProfiles().stream().filter(qProfile -> languages.get(qProfile.language()) != null).collect(Collectors.toList());
+      return profileLookup.allProfiles(dbSession).stream().filter(qProfile -> languages.get(qProfile.language()) != null).collect(Collectors.toList());
     }
-    return profileLookup.profiles(language);
+    return profileLookup.profiles(dbSession, language);
   }
 
   private Set<String> lookupByProfileName(DbSession dbSession, Map<String, QProfile> qualityProfiles, Set<String> languageKeys, @Nullable String profileName) {
index c799329ff6e485c97198e5d607c1d748cf6472a6..08a111881176127e5cfe8ef825b13706b5b453e6 100644 (file)
@@ -26,7 +26,8 @@ import javax.annotation.CheckForNull;
 import org.sonar.api.user.User;
 import org.sonar.api.user.UserFinder;
 import org.sonar.api.user.UserQuery;
-import org.sonar.db.user.UserDao;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.user.UserDto;
 
 /**
@@ -34,29 +35,35 @@ import org.sonar.db.user.UserDto;
  */
 public class DefaultUserFinder implements UserFinder {
 
-  private final UserDao userDao;
+  private final DbClient dbClient;
 
-  public DefaultUserFinder(UserDao userDao) {
-    this.userDao = userDao;
+  public DefaultUserFinder(DbClient dbClient) {
+    this.dbClient = dbClient;
   }
 
   @Override
   @CheckForNull
   public User findByLogin(String login) {
-    UserDto dto = userDao.selectActiveUserByLogin(login);
-    return dto != null ? dto.toUser() : null;
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login);
+      return dto != null ? dto.toUser() : null;
+    }
   }
 
   @Override
   public List<User> findByLogins(List<String> logins) {
-    List<UserDto> dtos = userDao.selectByLogins(logins);
-    return toUsers(dtos);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      List<UserDto> dtos = dbClient.userDao().selectByLogins(dbSession, logins);
+      return toUsers(dtos);
+    }
   }
 
   @Override
   public List<User> find(UserQuery query) {
-    List<UserDto> dtos = userDao.selectUsers(query);
-    return toUsers(dtos);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      List<UserDto> dtos = dbClient.userDao().selectUsers(dbSession, query);
+      return toUsers(dtos);
+    }
   }
 
   private static List<User> toUsers(Collection<UserDto> dtos) {
index 7a191e7d3d89bf37e90ca32c71ca12a7f99483e3..8d08587f2a482506f87339dfa823e55fade03a56 100644 (file)
@@ -22,7 +22,8 @@ package org.sonar.server.user;
 import javax.annotation.Nullable;
 import org.sonar.api.database.model.User;
 import org.sonar.api.security.UserFinder;
-import org.sonar.db.user.UserDao;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.user.UserDto;
 
 /**
@@ -30,20 +31,24 @@ import org.sonar.db.user.UserDto;
  */
 public class DeprecatedUserFinder implements UserFinder {
 
-  private final UserDao userDao;
+  private final DbClient dbClient;
 
-  public DeprecatedUserFinder(UserDao userDao) {
-    this.userDao = userDao;
+  public DeprecatedUserFinder(DbClient dbClient) {
+    this.dbClient = dbClient;
   }
 
   @Override
   public User findById(int id) {
-    return copy(userDao.selectUserById(id));
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      return copy(dbClient.userDao().selectUserById(dbSession, id));
+    }
   }
 
   @Override
   public User findByLogin(String login) {
-    return copy(userDao.selectActiveUserByLogin(login));
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      return copy(dbClient.userDao().selectActiveUserByLogin(dbSession, login));
+    }
   }
 
   private static User copy(@Nullable UserDto dto) {
index 786c7e4cb8b7598efa0802de478b3ab2f5102583..0b2b434d7fa788ea3d0317d9ad1bf8d241e6e423 100644 (file)
@@ -533,8 +533,7 @@ public class ProjectDataLoaderMediumTest {
 
     ComponentDto file = ComponentTesting.newFileDto(project, null, "file");
     dbClient.componentDao().insert(dbSession, file);
-    tester.get(FileSourceDao.class).insert(newFileSourceDto(file).setSrcHash("123456"));
-
+    tester.get(FileSourceDao.class).insert(dbSession, newFileSourceDto(file).setSrcHash("123456"));
     dbSession.commit();
 
     ProjectRepositories ref = underTest.load(ProjectDataQuery.create().setModuleKey(project.key()));
@@ -555,7 +554,7 @@ public class ProjectDataLoaderMediumTest {
     // File on project
     ComponentDto projectFile = ComponentTesting.newFileDto(project, null, "projectFile");
     dbClient.componentDao().insert(dbSession, projectFile);
-    tester.get(FileSourceDao.class).insert(newFileSourceDto(projectFile).setSrcHash("123456"));
+    tester.get(FileSourceDao.class).insert(dbSession, newFileSourceDto(projectFile).setSrcHash("123456"));
 
     ComponentDto module = ComponentTesting.newModuleDto(project);
     dbClient.componentDao().insert(dbSession, module);
@@ -563,7 +562,7 @@ public class ProjectDataLoaderMediumTest {
     // File on module
     ComponentDto moduleFile = ComponentTesting.newFileDto(module, null, "moduleFile");
     dbClient.componentDao().insert(dbSession, moduleFile);
-    tester.get(FileSourceDao.class).insert(newFileSourceDto(moduleFile).setSrcHash("789456"));
+    tester.get(FileSourceDao.class).insert(dbSession, newFileSourceDto(moduleFile).setSrcHash("789456"));
 
     dbSession.commit();
 
@@ -583,7 +582,7 @@ public class ProjectDataLoaderMediumTest {
     // File on project
     ComponentDto projectFile = ComponentTesting.newFileDto(project, null, "projectFile");
     dbClient.componentDao().insert(dbSession, projectFile);
-    tester.get(FileSourceDao.class).insert(newFileSourceDto(projectFile).setSrcHash("123456").setRevision("987654321"));
+    tester.get(FileSourceDao.class).insert(dbSession, newFileSourceDto(projectFile).setSrcHash("123456").setRevision("987654321"));
 
     ComponentDto module = ComponentTesting.newModuleDto(project);
     userSessionRule.logIn().addProjectUuidPermissions(SCAN_EXECUTION, project.uuid());
@@ -592,7 +591,7 @@ public class ProjectDataLoaderMediumTest {
     // File on module
     ComponentDto moduleFile = ComponentTesting.newFileDto(module, null, "moduleFile");
     dbClient.componentDao().insert(dbSession, moduleFile);
-    tester.get(FileSourceDao.class).insert(newFileSourceDto(moduleFile).setSrcHash("789456").setRevision("123456789"));
+    tester.get(FileSourceDao.class).insert(dbSession, newFileSourceDto(moduleFile).setSrcHash("789456").setRevision("123456789"));
 
     dbSession.commit();
 
index 486ea624301db2310dd004e6b84fe59a27010503..60cd97e5646f1ae467d1c91cf6c40cbc9ffb64d6 100644 (file)
@@ -22,7 +22,10 @@ package org.sonar.server.computation.task.projectanalysis.qualitygate;
 import com.google.common.base.Optional;
 import com.google.common.collect.ImmutableList;
 import java.util.Collections;
+import org.junit.Before;
 import org.junit.Test;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.qualitygate.QualityGateConditionDao;
 import org.sonar.db.qualitygate.QualityGateConditionDto;
 import org.sonar.db.qualitygate.QualityGateDao;
@@ -32,6 +35,8 @@ import org.sonar.server.computation.task.projectanalysis.metric.MetricRepository
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.guava.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -50,7 +55,14 @@ public class QualityGateServiceImplTest {
   private QualityGateDao qualityGateDao = mock(QualityGateDao.class);
   private QualityGateConditionDao qualityGateConditionDao = mock(QualityGateConditionDao.class);
   private MetricRepository metricRepository = mock(MetricRepository.class);
-  private QualityGateServiceImpl underTest = new QualityGateServiceImpl(qualityGateDao, qualityGateConditionDao, metricRepository);
+  private DbClient dbClient = mock(DbClient.class);
+  private QualityGateServiceImpl underTest = new QualityGateServiceImpl(dbClient, metricRepository);
+
+  @Before
+  public void setUp() throws Exception {
+    when(dbClient.qualityGateDao()).thenReturn(qualityGateDao);
+    when(dbClient.gateConditionDao()).thenReturn(qualityGateConditionDao);
+  }
 
   @Test
   public void findById_returns_absent_when_QualityGateDto_does_not_exist() {
@@ -59,8 +71,8 @@ public class QualityGateServiceImplTest {
 
   @Test
   public void findById_returns_QualityGate_with_empty_set_of_conditions_when_there_is_none_in_DB() {
-    when(qualityGateDao.selectById(SOME_ID)).thenReturn(QUALITY_GATE_DTO);
-    when(qualityGateConditionDao.selectForQualityGate(SOME_ID)).thenReturn(Collections.<QualityGateConditionDto>emptyList());
+    when(qualityGateDao.selectById(any(DbSession.class), eq(SOME_ID))).thenReturn(QUALITY_GATE_DTO);
+    when(qualityGateConditionDao.selectForQualityGate(any(DbSession.class), eq(SOME_ID))).thenReturn(Collections.emptyList());
 
     Optional<QualityGate> res = underTest.findById(SOME_ID);
 
@@ -72,8 +84,8 @@ public class QualityGateServiceImplTest {
 
   @Test
   public void findById_returns_conditions_when_there_is_some_in_DB() {
-    when(qualityGateDao.selectById(SOME_ID)).thenReturn(QUALITY_GATE_DTO);
-    when(qualityGateConditionDao.selectForQualityGate(SOME_ID)).thenReturn(ImmutableList.of(CONDITION_1, CONDITION_2));
+    when(qualityGateDao.selectById(any(DbSession.class), eq(SOME_ID))).thenReturn(QUALITY_GATE_DTO);
+    when(qualityGateConditionDao.selectForQualityGate(any(DbSession.class), eq(SOME_ID))).thenReturn(ImmutableList.of(CONDITION_1, CONDITION_2));
     // metrics are always supposed to be there
     when(metricRepository.getById(METRIC_ID_1)).thenReturn(METRIC_1);
     when(metricRepository.getById(METRIC_ID_2)).thenReturn(METRIC_2);
index 0a1e619b733451268658204cfe96619810b51719..2b5da1dab3468bceacd6a77fb762c284d10fba68 100644 (file)
@@ -255,11 +255,12 @@ public class ScmInfoRepositoryImplTest {
     if (revision != null) {
       builder.setScmRevision(revision);
     }
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), new FileSourceDto()
       .setFileUuid(FILE.getUuid())
       .setProjectUuid("PROJECT_UUID")
       .setSourceData(fileDataBuilder.build())
       .setSrcHash(srcHash));
+    dbTester.commit();
   }
 
   private void addCopyFromPreviousChangesetInReport() {
index 51589995b6fda2e3f27f03e6b5bb7c490b76a1b4..18e6b72709ad55d28f87812c88f1a58f0c7b6dc4 100644 (file)
@@ -104,7 +104,7 @@ public class PersistTestsStepTest extends BaseStepTest {
   public void no_test_in_database_and_batch_report() {
     underTest.execute();
 
-    assertThat(dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1)).isNull();
+    assertThat(dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1)).isNull();
     assertThat(log.logs()).isEmpty();
   }
 
@@ -121,7 +121,7 @@ public class PersistTestsStepTest extends BaseStepTest {
 
     assertThat(db.countRowsOfTable("file_sources")).isEqualTo(1);
 
-    FileSourceDto dto = dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1);
+    FileSourceDto dto = dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1);
     assertThat(dto.getCreatedAt()).isEqualTo(now);
     assertThat(dto.getUpdatedAt()).isEqualTo(now);
     assertThat(dto.getProjectUuid()).isEqualTo(PROJECT_UUID);
@@ -142,7 +142,7 @@ public class PersistTestsStepTest extends BaseStepTest {
 
     underTest.execute();
 
-    FileSourceDto dto = dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1);
+    FileSourceDto dto = dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1);
     assertThat(dto.getCreatedAt()).isEqualTo(now);
     assertThat(dto.getUpdatedAt()).isEqualTo(now);
     assertThat(dto.getProjectUuid()).isEqualTo(PROJECT_UUID);
@@ -168,7 +168,7 @@ public class PersistTestsStepTest extends BaseStepTest {
 
     underTest.execute();
 
-    FileSourceDto dto = dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1);
+    FileSourceDto dto = dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1);
     assertThat(dto.getFileUuid()).isEqualTo(TEST_FILE_UUID_1);
     List<DbFileSources.Test> tests = dto.getTestData();
     assertThat(tests).hasSize(1);
@@ -203,7 +203,7 @@ public class PersistTestsStepTest extends BaseStepTest {
 
     underTest.execute();
 
-    FileSourceDto dto = dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1);
+    FileSourceDto dto = dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1);
     List<Integer> coveredLines = dto.getTestData().get(0).getCoveredFile(0).getCoveredLineList();
     assertThat(coveredLines).containsOnly(1, 2, 3, 4);
   }
@@ -225,7 +225,7 @@ public class PersistTestsStepTest extends BaseStepTest {
       .setCreatedAt(100_000)
       .setUpdatedAt(100_000));
     db.getSession().commit();
-    assertThat(dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1)).isNotNull();
+    assertThat(dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1)).isNotNull();
 
     ScannerReport.Test newBatchTest = newTest(1);
     reportReader.putTests(TEST_FILE_REF_1, Arrays.asList(newBatchTest));
@@ -237,7 +237,7 @@ public class PersistTestsStepTest extends BaseStepTest {
     underTest.execute();
 
     // ASSERT
-    FileSourceDto dto = dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1);
+    FileSourceDto dto = dbClient.fileSourceDao().selectTest(db.getSession(), TEST_FILE_UUID_1);
     assertThat(dto.getCreatedAt()).isEqualTo(100_000);
     assertThat(dto.getUpdatedAt()).isEqualTo(now);
     assertThat(dto.getTestData()).hasSize(1);
index c4dff3ab2400e510c1c71e5e8ef9398d95310281..c287b05d303ddf4b0df96fc51dab8df5960dbfa2 100644 (file)
@@ -517,7 +517,7 @@ public class BulkChangeActionTest {
   }
 
   private void addActions() {
-    actions.add(new org.sonar.server.issue.AssignAction(new DefaultUserFinder(db.getDbClient().userDao()), issueFieldsSetter));
+    actions.add(new org.sonar.server.issue.AssignAction(new DefaultUserFinder(db.getDbClient()), issueFieldsSetter));
     actions.add(new org.sonar.server.issue.SetSeverityAction(issueFieldsSetter, userSession));
     actions.add(new org.sonar.server.issue.SetTypeAction(issueFieldsSetter, userSession));
     actions.add(new org.sonar.server.issue.TransitionAction(new TransitionService(userSession, issueWorkflow)));
index 1aad19a90810a08723aa8432be0e6b62a4821221..3a4336b6938490530d2ab326161a1d452d0e4277 100644 (file)
@@ -58,7 +58,7 @@ public class BackendCleanupTest {
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
 
-  BackendCleanup backendCleanup = new BackendCleanup(esTester.client(), dbTester.myBatis());
+  private BackendCleanup underTest = new BackendCleanup(esTester.client(), dbTester.getDbClient());
   private OrganizationDto organization;
 
   @Before
@@ -70,7 +70,7 @@ public class BackendCleanupTest {
   public void clear_db() {
     dbTester.prepareDbUnit(getClass(), "shared.xml");
 
-    backendCleanup.clearDb();
+    underTest.clearDb();
 
     assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(0);
     assertThat(dbTester.countRowsOfTable("snapshots")).isEqualTo(0);
@@ -84,7 +84,7 @@ public class BackendCleanupTest {
     esTester.putDocuments(RuleIndexDefinition.INDEX_TYPE_RULE, newRuleDoc());
     esTester.putDocuments(ComponentIndexDefinition.INDEX_TYPE_COMPONENT, newComponentDoc());
 
-    backendCleanup.clearIndexes();
+    underTest.clearIndexes();
 
     assertThat(esTester.countDocuments(IssueIndexDefinition.INDEX_TYPE_ISSUE)).isEqualTo(0);
     assertThat(esTester.countDocuments(ComponentIndexDefinition.INDEX_TYPE_COMPONENT)).isEqualTo(0);
@@ -97,7 +97,7 @@ public class BackendCleanupTest {
     esTester.putDocuments(RuleIndexDefinition.INDEX_TYPE_RULE, newRuleDoc());
     esTester.putDocuments(ComponentIndexDefinition.INDEX_TYPE_COMPONENT, newComponentDoc());
 
-    backendCleanup.clearAll();
+    underTest.clearAll();
 
     assertThat(esTester.countDocuments(IssueIndexDefinition.INDEX_TYPE_ISSUE)).isEqualTo(0);
     assertThat(esTester.countDocuments(RuleIndexDefinition.INDEX_TYPE_RULE)).isEqualTo(0);
@@ -121,7 +121,7 @@ public class BackendCleanupTest {
       .setName("Name"));
     esTester.putDocuments(ComponentIndexDefinition.INDEX_TYPE_COMPONENT, newComponentDoc());
 
-    backendCleanup.resetData();
+    underTest.resetData();
 
     assertThat(dbTester.countRowsOfTable("projects")).isZero();
     assertThat(dbTester.countRowsOfTable("snapshots")).isZero();
index c32af6ce67c5b580a44576ed72c7fd20361409f6..98ec82066151272d7e432a0fc9d318543fe56869 100644 (file)
@@ -41,10 +41,9 @@ public class QualityGateUpdaterTest {
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
 
-  DbClient dbClient = db.getDbClient();
-  DbSession dbSession = db.getSession();
-
-  QualityGateUpdater underTest = new QualityGateUpdater(dbClient);
+  private DbClient dbClient = db.getDbClient();
+  private DbSession dbSession = db.getSession();
+  private QualityGateUpdater underTest = new QualityGateUpdater(dbClient);
 
   @Test
   public void create_quality_gate() throws Exception {
@@ -61,15 +60,18 @@ public class QualityGateUpdaterTest {
   public void fail_to_create_when_name_is_empty() throws Exception {
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Name can't be empty");
+
     underTest.create(dbSession, "");
   }
 
   @Test
   public void fail_to_create_when_name_already_exists() throws Exception {
-    dbClient.qualityGateDao().insert(new QualityGateDto().setName(QGATE_NAME));
+    dbClient.qualityGateDao().insert(dbSession, new QualityGateDto().setName(QGATE_NAME));
+    dbSession.commit();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Name has already been taken");
+
     underTest.create(dbSession, QGATE_NAME);
   }
 }
index f5868bb7d566f5718ce070af0095169c7eaffb24..0f9492e650bebb9c29ee2b9d8ca8a382209cf2c8 100644 (file)
@@ -101,7 +101,7 @@ public class QualityGatesTest {
   @Test
   public void should_list_qgates() {
     List<QualityGateDto> allQgates = Lists.newArrayList(new QualityGateDto().setName("Gate One"), new QualityGateDto().setName("Gate Two"));
-    when(dao.selectAll()).thenReturn(allQgates);
+    when(dao.selectAll(dbSession)).thenReturn(allQgates);
     assertThat(underTest.list()).isEqualTo(allQgates);
   }
 
@@ -120,9 +120,9 @@ public class QualityGatesTest {
     long id = QUALITY_GATE_ID;
     final String name = "Golden";
     QualityGateDto existing = new QualityGateDto().setId(id).setName(name);
-    when(dao.selectByName(name)).thenReturn(existing);
+    when(dao.selectByName(dbSession, name)).thenReturn(existing);
     assertThat(underTest.get(name)).isEqualTo(existing);
-    verify(dao).selectByName(name);
+    verify(dao).selectByName(dbSession, name);
   }
 
   @Test(expected = NotFoundException.class)
@@ -139,8 +139,8 @@ public class QualityGatesTest {
     QualityGateDto sg1 = underTest.rename(id, name);
     assertThat(sg1.getName()).isEqualTo(name);
     verify(dao).selectById(dbSession, id);
-    verify(dao).selectByName(name);
-    verify(dao).update(sg1);
+    verify(dao).selectByName(dbSession, name);
+    verify(dao).update(sg1, dbSession);
   }
 
   @Test
@@ -152,8 +152,8 @@ public class QualityGatesTest {
     QualityGateDto sg1 = underTest.rename(id, name);
     assertThat(sg1.getName()).isEqualTo(name);
     verify(dao).selectById(dbSession, id);
-    verify(dao).selectByName(name);
-    verify(dao).update(sg1);
+    verify(dao).selectByName(dbSession, name);
+    verify(dao).update(sg1, dbSession);
   }
 
   @Test(expected = NotFoundException.class)
@@ -167,7 +167,7 @@ public class QualityGatesTest {
     String name = "SG-1";
     QualityGateDto existing = new QualityGateDto().setId(id).setName("Golden");
     when(dao.selectById(dbSession, id)).thenReturn(existing);
-    when(dao.selectByName(name)).thenReturn(new QualityGateDto().setId(666L).setName(name));
+    when(dao.selectByName(dbSession, name)).thenReturn(new QualityGateDto().setId(666L).setName(name));
     underTest.rename(id, name);
   }
 
@@ -235,7 +235,7 @@ public class QualityGatesTest {
     long defaultId = QUALITY_GATE_ID;
     when(propertiesDao.selectGlobalProperty("sonar.qualitygate")).thenReturn(new PropertyDto().setValue(Long.toString(defaultId)));
     QualityGateDto defaultQgate = new QualityGateDto().setId(defaultId).setName(defaultName);
-    when(dao.selectById(defaultId)).thenReturn(defaultQgate);
+    when(dao.selectById(dbSession, defaultId)).thenReturn(defaultQgate);
     assertThat(underTest.getDefault()).isEqualTo(defaultQgate);
   }
 
@@ -255,7 +255,7 @@ public class QualityGatesTest {
     QualityGateConditionDto cond1 = new QualityGateConditionDto().setMetricId(metric1Id);
     QualityGateConditionDto cond2 = new QualityGateConditionDto().setMetricId(metric2Id);
     Collection<QualityGateConditionDto> conditions = ImmutableList.of(cond1, cond2);
-    when(conditionDao.selectForQualityGate(qGateId)).thenReturn(conditions);
+    when(conditionDao.selectForQualityGate(dbSession, qGateId)).thenReturn(conditions);
     Metric metric1 = mock(Metric.class);
     when(metric1.getKey()).thenReturn(metric1Key);
     when(metricFinder.findById((int) metric1Id)).thenReturn(metric1);
@@ -277,7 +277,7 @@ public class QualityGatesTest {
     QualityGateConditionDto cond1 = new QualityGateConditionDto().setMetricId(metric1Id);
     QualityGateConditionDto cond2 = new QualityGateConditionDto().setMetricId(metric2Id);
     Collection<QualityGateConditionDto> conditions = ImmutableList.of(cond1, cond2);
-    when(conditionDao.selectForQualityGate(qGateId)).thenReturn(conditions);
+    when(conditionDao.selectForQualityGate(dbSession, qGateId)).thenReturn(conditions);
     Metric metric1 = mock(Metric.class);
     when(metric1.getKey()).thenReturn(metric1Key);
     when(metricFinder.findById((int) metric1Id)).thenReturn(metric1);
@@ -288,10 +288,10 @@ public class QualityGatesTest {
   public void should_delete_condition() {
     long idToDelete = QUALITY_GATE_ID;
     QualityGateConditionDto toDelete = new QualityGateConditionDto().setId(idToDelete);
-    when(conditionDao.selectById(idToDelete)).thenReturn(toDelete);
+    when(conditionDao.selectById(idToDelete, dbSession)).thenReturn(toDelete);
     underTest.deleteCondition(idToDelete);
-    verify(conditionDao).selectById(idToDelete);
-    verify(conditionDao).delete(toDelete);
+    verify(conditionDao).selectById(idToDelete, dbSession);
+    verify(conditionDao).delete(toDelete, dbSession);
   }
 
   @Test(expected = NotFoundException.class)
@@ -315,12 +315,12 @@ public class QualityGatesTest {
       ((QualityGateDto) invocation.getArguments()[1]).setId(destId);
       return null;
     }).when(dao).insert(eq(dbSession), any(QualityGateDto.class));
-    when(conditionDao.selectForQualityGate(anyLong(), eq(dbSession))).thenReturn(conditions);
+    when(conditionDao.selectForQualityGate(eq(dbSession), anyLong())).thenReturn(conditions);
     QualityGateDto atlantis = underTest.copy(sourceId, name);
     assertThat(atlantis.getName()).isEqualTo(name);
-    verify(dao).selectByName(name);
+    verify(dao).selectByName(dbSession, name);
     verify(dao).insert(dbSession, atlantis);
-    verify(conditionDao).selectForQualityGate(anyLong(), eq(dbSession));
+    verify(conditionDao).selectForQualityGate(eq(dbSession), anyLong());
     verify(conditionDao, times(conditions.size())).insert(any(QualityGateConditionDto.class), eq(dbSession));
   }
 
index 04a40cd49df95ece49ba13942d7e14cc034f62ad..b7562a234296cab6cf56f87726f3430ee49e4a4a 100644 (file)
@@ -75,7 +75,7 @@ public class RegisterQualityGatesTest {
     assertThat(dbClient.loadedTemplateDao().countByTypeAndKey("QUALITY_GATE", "SonarQube way", dbSession)).isEqualTo(1);
     QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByName(dbSession, "SonarQube way");
     assertThat(qualityGateDto).isNotNull();
-    assertThat(dbClient.gateConditionDao().selectForQualityGate(qualityGateDto.getId()))
+    assertThat(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getId()))
       .extracting(QualityGateConditionDto::getMetricId, QualityGateConditionDto::getOperator, QualityGateConditionDto::getWarningThreshold,
         QualityGateConditionDto::getErrorThreshold, QualityGateConditionDto::getPeriod)
       .containsOnly(
index 94bfc0a36156aa5d3fa6b620462c0d2d2b7966e0..62761bc0049aa0f17b3abdfe98a23eec5e86a79c 100644 (file)
@@ -68,7 +68,7 @@ public class CreateActionTest {
     assertThat(response.getName()).isEqualTo("Default");
     assertThat(response.getId()).isNotNull();
     dbSession.commit();
-    QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByName("Default");
+    QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByName(dbSession, "Default");
     assertThat(qualityGateDto).isNotNull();
   }
 
index 119c637c7fa9e0cf98c58dc6e6b3bdfc1d40acd0..aa596032a92ca0453696308f0960818355b31609 100644 (file)
@@ -150,7 +150,7 @@ public class CreateConditionActionTest {
   }
 
   private void assertCondition(CreateConditionWsResponse response, String operator, @Nullable String warning, @Nullable String error, @Nullable Integer period) {
-    List<QualityGateConditionDto> conditionDtoList = new ArrayList<>(dbClient.gateConditionDao().selectForQualityGate(qualityGateDto.getId(), dbSession));
+    List<QualityGateConditionDto> conditionDtoList = new ArrayList<>(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getId()));
     assertThat(conditionDtoList).hasSize(1);
     QualityGateConditionDto qualityGateConditionDto = conditionDtoList.get(0);
     assertThat(qualityGateConditionDto.getQualityGateId()).isEqualTo(qualityGateDto.getId());
index e2903f34150bf5430035486ab26936633f41c002..4cb0638170cb47af37e95bfcfac74fde5c3e696d 100644 (file)
@@ -158,7 +158,7 @@ public class UpdateConditionActionTest {
   }
 
   private void assertCondition(CreateConditionWsResponse response, String operator, @Nullable String warning, @Nullable String error, @Nullable Integer period) {
-    List<QualityGateConditionDto> conditionDtoList = new ArrayList<>(dbClient.gateConditionDao().selectForQualityGate(qualityGateDto.getId(), dbSession));
+    List<QualityGateConditionDto> conditionDtoList = new ArrayList<>(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getId()));
     assertThat(conditionDtoList).hasSize(1);
     QualityGateConditionDto qualityGateConditionDto = conditionDtoList.get(0);
     assertThat(qualityGateConditionDto.getQualityGateId()).isEqualTo(qualityGateDto.getId());
diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilesTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilesTest.java
deleted file mode 100644 (file)
index 11f2c81..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.server.qualityprofile;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbTester;
-import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.qualityprofile.QualityProfileDao;
-import org.sonar.db.qualityprofile.QualityProfileDto;
-import org.sonar.db.qualityprofile.QualityProfileTesting;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-public class QProfilesTest {
-
-  private static final String PROJECT_UUID = "P1";
-
-  @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
-
-  private QProfileLookup profileLookup = mock(QProfileLookup.class);
-  private QProfiles underTest = new QProfiles(profileLookup, dbTester.getDbClient());
-
-  @Test
-  public void search_profiles() {
-    underTest.allProfiles();
-    verify(profileLookup).allProfiles();
-  }
-
-  @Test
-  public void search_profiles_by_language() {
-    underTest.profilesByLanguage("java");
-    verify(profileLookup).profiles("java");
-  }
-
-  @Test
-  public void findProfileByProjectAndLanguage() {
-    ComponentDto project = ComponentTesting.newProjectDto(dbTester.organizations().insert(), PROJECT_UUID);
-    dbTester.getDbClient().componentDao().insert(dbTester.getSession(), project);
-    QualityProfileDao qProfileDao = dbTester.getDbClient().qualityProfileDao();
-    QualityProfileDto profile = QualityProfileTesting.newQualityProfileDto().setLanguage("js");
-    qProfileDao.insert(dbTester.getSession(), profile);
-    qProfileDao.insertProjectProfileAssociation(PROJECT_UUID, profile.getKey(), dbTester.getSession());
-    dbTester.commit();
-
-    assertThat(underTest.findProfileByProjectAndLanguage(1, "java")).isNull();
-    assertThat(underTest.findProfileByProjectAndLanguage(project.getId(), "java")).isNull();
-    assertThat(underTest.findProfileByProjectAndLanguage(project.getId(), "js").key()).isEqualTo(profile.getKey());
-  }
-}
index 8f9c77e40fec8c3786efdf514af1317e53110c94..d5ca10ec180972920f1d335d38378a1277c8ef1f 100644 (file)
@@ -54,8 +54,8 @@ import static org.assertj.guava.api.Assertions.assertThat;
 // TODO replace this MediumTest by DbTester and EsTester
 public class RegisterQualityProfilesMediumTest {
 
-  ServerTester tester;
-  DbSession dbSession;
+  private ServerTester tester;
+  private DbSession dbSession;
 
   @After
   public void tearDown() {
@@ -193,10 +193,10 @@ public class RegisterQualityProfilesMediumTest {
     tester.start();
 
     QualityProfileDao profileDao = dbClient().qualityProfileDao();
-    DbSession session = dbClient().openSession(false);
-    QualityProfileDto profileTwo = profileDao.selectByNameAndLanguage("two", "xoo", session);
-    tester.get(QProfileFactory.class).setDefault(session, profileTwo.getKee());
-    session.commit();
+    dbSession = dbClient().openSession(false);
+    QualityProfileDto profileTwo = profileDao.selectByNameAndLanguage("two", "xoo", dbSession);
+    tester.get(QProfileFactory.class).setDefault(dbSession, profileTwo.getKee());
+    dbSession.commit();
 
     verifyDefaultProfile("xoo", "two");
 
@@ -226,7 +226,8 @@ public class RegisterQualityProfilesMediumTest {
   }
 
   private void verifyDefaultProfile(String language, String name) {
-    QualityProfileDto defaultProfile = dbClient().qualityProfileDao().selectDefaultProfile(language);
+    dbSession = dbClient().openSession(false);
+    QualityProfileDto defaultProfile = dbClient().qualityProfileDao().selectDefaultProfile(dbSession, language);
     assertThat(defaultProfile).isNotNull();
     assertThat(defaultProfile.getName()).isEqualTo(name);
   }
index 7ad8e9d1735959b37cb40102b8fb75c6d07e7899..8797ddea2ff022eb86c0f5579e77bc20dcc69b24 100644 (file)
@@ -100,7 +100,7 @@ public class DeleteActionTest {
     tester.newPostRequest("api/qualityprofiles", "delete").setParam("profileKey", "sonar-way-xoo1-12345").execute().assertNoContent();
 
     assertThat(qualityProfileDao.selectByKey(session, "sonar-way-xoo1-12345")).isNull();
-    assertThat(qualityProfileDao.selectProjects("Sonar way", xoo1.getName())).isEmpty();
+    assertThat(qualityProfileDao.selectProjects("Sonar way", xoo1.getName(), session)).isEmpty();
   }
 
   @Test
@@ -118,7 +118,7 @@ public class DeleteActionTest {
     tester.newPostRequest("api/qualityprofiles", "delete").setParam("profileName", "Sonar way").setParam("language", xoo1.getKey()).execute().assertNoContent();
 
     assertThat(qualityProfileDao.selectByKey(session, "sonar-way-xoo1-12345")).isNull();
-    assertThat(qualityProfileDao.selectProjects("Sonar way", xoo1.getName())).isEmpty();
+    assertThat(qualityProfileDao.selectProjects("Sonar way", xoo1.getName(), session)).isEmpty();
   }
 
   @Test
index 106e9c6754bd9feaea109cd005b07aa6ab495850..407181880ac5ff937fcce901c98d8d2f224e220a 100644 (file)
@@ -159,6 +159,6 @@ public class SetDefaultActionTest {
   }
 
   private void checkDefaultProfile(String language, String key) {
-    assertThat(dbClient.qualityProfileDao().selectDefaultProfile(language).getKey()).isEqualTo(key);
+    assertThat(dbClient.qualityProfileDao().selectDefaultProfile(db.getSession(), language).getKey()).isEqualTo(key);
   }
 }
index 843ef7795caa29b98247cd5834720b65ec6e5323..9b6aff06521ef0688aa7d893ea5dabee66bfddcc 100644 (file)
@@ -56,7 +56,8 @@ public class SourceServiceTest {
     FileSourceDto dto = new FileSourceDto();
     dto.setFileUuid(FILE_UUID).setProjectUuid("PROJECT_UUID");
     dto.setSourceData(FileSourceTesting.newFakeData(10).build());
-    dbTester.getDbClient().fileSourceDao().insert(dto);
+    dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), dto);
+    dbTester.commit();
   }
 
   @Test
index a2918564bd6c29726aed10fa0fae86bf25787606..d7a8d1fcc9b512a907f227f912eaece44aea300b 100644 (file)
@@ -225,10 +225,11 @@ public class LinesActionTest {
 
   private void insertFileWithData(DbFileSources.Data fileData) throws IOException {
     insertFile();
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(fileData));
+    dbTester.commit();
   }
 
   private void setUserWithValidPermission() {
index 1df0b13878d523d1f40f6fa1bb7b16c47d202bf5..998bbc1a21a43282f2d12145f901acffcfeec1f6 100644 (file)
@@ -27,6 +27,7 @@ import org.sonar.api.utils.DateUtils;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTesting;
@@ -51,9 +52,9 @@ public class ScmActionTest {
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
-  WsTester tester;
-
-  DbClient dbClient = dbTester.getDbClient();
+  private WsTester tester;
+  private DbClient dbClient = dbTester.getDbClient();
+  private DbSession dbSession = dbTester.getSession();
 
   @Before
   public void setUp() {
@@ -66,11 +67,12 @@ public class ScmActionTest {
     initFile();
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder().addLines(
         newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1)).build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY);
     request.execute().assertJson(getClass(), "show_scm.json");
@@ -81,7 +83,7 @@ public class ScmActionTest {
     initFile();
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder()
@@ -90,6 +92,7 @@ public class ScmActionTest {
         .addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
         .addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
         .build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("from", "2").setParam("to", "3");
     request.execute().assertJson(getClass(), "show_scm_from_given_range_lines.json");
@@ -101,7 +104,7 @@ public class ScmActionTest {
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
     // lines 1 and 2 are the same commit, but not 3 (different date)
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder()
@@ -110,6 +113,7 @@ public class ScmActionTest {
         .addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
         .addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
         .build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("commits_by_line",
       "true");
@@ -122,7 +126,7 @@ public class ScmActionTest {
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
     // lines 1 and 2 are the same commit, but not 3 (different date)
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder()
@@ -131,6 +135,7 @@ public class ScmActionTest {
         .addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
         .addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
         .build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("commits_by_line",
       "false");
@@ -142,7 +147,7 @@ public class ScmActionTest {
     initFile();
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder()
@@ -151,6 +156,7 @@ public class ScmActionTest {
         .addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
         .addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
         .build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY).setParam("from",
       "-2").setParam("to", "3");
@@ -162,10 +168,11 @@ public class ScmActionTest {
     initFile();
     userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
 
-    dbTester.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
       .setProjectUuid(PROJECT_UUID)
       .setFileUuid(FILE_UUID)
       .setSourceData(DbFileSources.Data.newBuilder().build()));
+    dbSession.commit();
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "scm").setParam("key", FILE_KEY);
     request.execute().assertJson(getClass(), "return_empty_value_when_no_scm.json");
index ca7854d6c6841adfb70980599e43760cb555857e..0b24025575b867890205068555e483a11929780b 100644 (file)
@@ -153,7 +153,7 @@ public class ClearRulesOverloadedDebtTest {
   }
 
   private void verifyTaskRegistered() {
-    assertThat(dbClient.loadedTemplateDao().countByTypeAndKey(ONE_SHOT_TASK_TYPE, "ClearRulesOverloadedDebt")).isEqualTo(1);
+    assertThat(dbClient.loadedTemplateDao().countByTypeAndKey(ONE_SHOT_TASK_TYPE, "ClearRulesOverloadedDebt", dbSession)).isEqualTo(1);
   }
 
   private void verifyLog() {
index 4d2b0cdfa351fb7d93db4f2f97844def3c2fa895..db854029e64f4402dd7eec186a504fa9506f2e83 100644 (file)
@@ -280,7 +280,7 @@ public class ListActionTest {
   }
 
   private void insertTests(ComponentDto testFile, DbFileSources.Test... tests) {
-    db.getDbClient().fileSourceDao().insert(new FileSourceDto()
+    db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
       .setProjectUuid(project.uuid())
       .setFileUuid(testFile.uuid())
       .setTestData(asList(tests)));
diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/DefaultUserFinderTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/DefaultUserFinderTest.java
deleted file mode 100644 (file)
index 385de3d..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-package org.sonar.server.user;
-
-import java.util.Arrays;
-import java.util.Collection;
-import org.junit.Test;
-import org.sonar.api.user.User;
-import org.sonar.api.user.UserQuery;
-import org.sonar.db.user.UserDao;
-import org.sonar.db.user.UserDto;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class DefaultUserFinderTest {
-  UserDao dao = mock(UserDao.class);
-  DefaultUserFinder finder = new DefaultUserFinder(dao);
-
-  @Test
-  public void findByLogin() {
-    UserDto dto = new UserDto().setLogin("david").setName("David").setEmail("dav@id.com");
-    when(dao.selectActiveUserByLogin("david")).thenReturn(dto);
-
-    assertThat(finder.findByLogin("david").name()).isEqualTo("David");
-  }
-
-  @Test
-  public void findByLogins() {
-    UserDto david = new UserDto().setLogin("david").setName("David").setEmail("dav@id.com");
-    UserDto john = new UserDto().setLogin("john").setName("John").setEmail("jo@hn.com");
-    when(dao.selectByLogins(Arrays.asList("david", "john"))).thenReturn(Arrays.asList(david, john));
-
-    Collection<User> users = finder.findByLogins(Arrays.asList("david", "john"));
-    assertThat(users).hasSize(2);
-    for (User user : users) {
-      assertThat(user.login()).isIn("david", "john");
-    }
-  }
-
-  @Test
-  public void findByQuery() {
-    UserQuery query = UserQuery.builder().logins("simon").build();
-    finder.find(query);
-    verify(dao).selectUsers(query);
-  }
-}
index d99a0e4d8b5c95e594a68b4c0e8a260bb83c686a..32414882dc16b37ff8a0808d3835cb128f658e49 100644 (file)
@@ -25,19 +25,18 @@ import org.junit.Test;
 import org.sonar.api.database.model.User;
 import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
-import org.sonar.db.user.UserDao;
 
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.nullValue;
 import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
 
 
 public class DeprecatedUserFinderTest {
 
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
-
+  private DeprecatedUserFinder underTest = new DeprecatedUserFinder(dbTester.getDbClient());
+  
   @Before
   public void init() {
     dbTester.prepareDbUnit(DeprecatedUserFinderTest.class, "fixture.xml");
@@ -45,39 +44,38 @@ public class DeprecatedUserFinderTest {
 
   @Test
   public void shouldFindUserByLogin() {
-    DeprecatedUserFinder finder = new DeprecatedUserFinder(new UserDao(dbTester.myBatis(), mock(System2.class)));
-    User user = finder.findByLogin("simon");
+    
+    User user = underTest.findByLogin("simon");
     assertThat(user.getId(), is(1));
     assertThat(user.getLogin(), is("simon"));
     assertThat(user.getName(), is("Simon Brandhof"));
     assertThat(user.getEmail(), is("simon.brandhof@sonarsource.com"));
 
-    user = finder.findByLogin("godin");
+    user = underTest.findByLogin("godin");
     assertThat(user.getId(), is(2));
     assertThat(user.getLogin(), is("godin"));
     assertThat(user.getName(), is("Evgeny Mandrikov"));
     assertThat(user.getEmail(), is("evgeny.mandrikov@sonarsource.com"));
 
-    user = finder.findByLogin("user");
+    user = underTest.findByLogin("user");
     assertThat(user, nullValue());
   }
 
   @Test
   public void shouldFindUserById() {
-    DeprecatedUserFinder finder = new DeprecatedUserFinder(new UserDao(dbTester.myBatis(), mock(System2.class)));
-    User user = finder.findById(1);
+    User user = underTest.findById(1);
     assertThat(user.getId(), is(1));
     assertThat(user.getLogin(), is("simon"));
     assertThat(user.getName(), is("Simon Brandhof"));
     assertThat(user.getEmail(), is("simon.brandhof@sonarsource.com"));
 
-    user = finder.findById(2);
+    user = underTest.findById(2);
     assertThat(user.getId(), is(2));
     assertThat(user.getLogin(), is("godin"));
     assertThat(user.getName(), is("Evgeny Mandrikov"));
     assertThat(user.getEmail(), is("evgeny.mandrikov@sonarsource.com"));
 
-    user = finder.findById(3);
+    user = underTest.findById(3);
     assertThat(user, nullValue());
   }
 
index 8fc3ba6f5b34525aee6229235f0bb0ce1740e787..01c965f822c0fbcde046cad6558d56ca29569f13 100644 (file)
@@ -75,7 +75,8 @@ public class App implements Stoppable {
   }
 
   @VisibleForTesting
-  App(Properties commandLineArguments, Function<Properties, Props> propsSupplier, Monitor monitor, CheckFSConfigOnReload checkFsConfigOnReload, JavaCommandFactory javaCommandFactory) {
+  App(Properties commandLineArguments, Function<Properties, Props> propsSupplier, Monitor monitor, CheckFSConfigOnReload checkFsConfigOnReload,
+    JavaCommandFactory javaCommandFactory) {
     this.commandLineArguments = commandLineArguments;
     this.propsSupplier = propsSupplier;
     this.javaCommandFactory = javaCommandFactory;
@@ -88,24 +89,6 @@ public class App implements Stoppable {
     monitor.awaitTermination();
   }
 
-  private List<JavaCommand> createCommands(Props props) {
-    File homeDir = props.nonNullValueAsFile(ProcessProperties.PATH_HOME);
-    List<JavaCommand> commands = new ArrayList<>(3);
-    if (isProcessEnabled(props, ProcessProperties.CLUSTER_SEARCH_DISABLED)) {
-      commands.add(javaCommandFactory.createESCommand(props, homeDir));
-    }
-
-    if (isProcessEnabled(props, ProcessProperties.CLUSTER_WEB_DISABLED)) {
-      commands.add(javaCommandFactory.createWebCommand(props, homeDir));
-    }
-
-    if (isProcessEnabled(props, ProcessProperties.CLUSTER_CE_DISABLED)) {
-      commands.add(javaCommandFactory.createCeCommand(props, homeDir));
-    }
-
-    return commands;
-  }
-
   private static boolean isProcessEnabled(Props props, String disabledPropertyKey) {
     return !props.valueAsBoolean(ProcessProperties.CLUSTER_ENABLED) ||
       !props.valueAsBoolean(disabledPropertyKey);
@@ -176,5 +159,23 @@ public class App implements Stoppable {
 
       return createCommands(reloadedProps);
     }
+
+    private List<JavaCommand> createCommands(Props props) {
+      File homeDir = props.nonNullValueAsFile(ProcessProperties.PATH_HOME);
+      List<JavaCommand> commands = new ArrayList<>(3);
+      if (isProcessEnabled(props, ProcessProperties.CLUSTER_SEARCH_DISABLED)) {
+        commands.add(javaCommandFactory.createESCommand(props, homeDir));
+      }
+
+      if (isProcessEnabled(props, ProcessProperties.CLUSTER_WEB_DISABLED)) {
+        commands.add(javaCommandFactory.createWebCommand(props, homeDir));
+      }
+
+      if (isProcessEnabled(props, ProcessProperties.CLUSTER_CE_DISABLED)) {
+        commands.add(javaCommandFactory.createCeCommand(props, homeDir));
+      }
+
+      return commands;
+    }
   }
 }
index 4f9ebd80ed89436f01244169bb6a8dae90333560..8058beb10181958d787c274ceceefa15514f688c 100644 (file)
@@ -46,49 +46,49 @@ public class JavaCommandFactoryImpl implements JavaCommandFactory {
 
   @Override
   public JavaCommand createESCommand(Props props, File workDir) {
-      return newJavaCommand(ProcessId.ELASTICSEARCH, props, workDir)
-        .addJavaOptions("-Djava.awt.headless=true")
-        .addJavaOptions(props.nonNullValue(ProcessProperties.SEARCH_JAVA_OPTS))
-        .addJavaOptions(props.nonNullValue(ProcessProperties.SEARCH_JAVA_ADDITIONAL_OPTS))
-        .setClassName("org.sonar.search.SearchServer")
-        .addClasspath("./lib/common/*")
-        .addClasspath("./lib/search/*");
-    }
+    return newJavaCommand(ProcessId.ELASTICSEARCH, props, workDir)
+      .addJavaOptions("-Djava.awt.headless=true")
+      .addJavaOptions(props.nonNullValue(ProcessProperties.SEARCH_JAVA_OPTS))
+      .addJavaOptions(props.nonNullValue(ProcessProperties.SEARCH_JAVA_ADDITIONAL_OPTS))
+      .setClassName("org.sonar.search.SearchServer")
+      .addClasspath("./lib/common/*")
+      .addClasspath("./lib/search/*");
+  }
 
   @Override
   public JavaCommand createWebCommand(Props props, File workDir) {
-      JavaCommand command = newJavaCommand(ProcessId.WEB_SERVER, props, workDir)
-        .addJavaOptions(ProcessProperties.WEB_ENFORCED_JVM_ARGS)
-        .addJavaOptions(props.nonNullValue(ProcessProperties.WEB_JAVA_OPTS))
-        .addJavaOptions(props.nonNullValue(ProcessProperties.WEB_JAVA_ADDITIONAL_OPTS))
-        // required for logback tomcat valve
-        .setEnvVariable(ProcessProperties.PATH_LOGS, props.nonNullValue(ProcessProperties.PATH_LOGS))
-        .setClassName("org.sonar.server.app.WebServer")
-        .addClasspath("./lib/common/*")
-        .addClasspath("./lib/server/*");
-      String driverPath = props.value(ProcessProperties.JDBC_DRIVER_PATH);
-      if (driverPath != null) {
-        command.addClasspath(driverPath);
-      }
-      return command;
+    JavaCommand command = newJavaCommand(ProcessId.WEB_SERVER, props, workDir)
+      .addJavaOptions(ProcessProperties.WEB_ENFORCED_JVM_ARGS)
+      .addJavaOptions(props.nonNullValue(ProcessProperties.WEB_JAVA_OPTS))
+      .addJavaOptions(props.nonNullValue(ProcessProperties.WEB_JAVA_ADDITIONAL_OPTS))
+      // required for logback tomcat valve
+      .setEnvVariable(ProcessProperties.PATH_LOGS, props.nonNullValue(ProcessProperties.PATH_LOGS))
+      .setClassName("org.sonar.server.app.WebServer")
+      .addClasspath("./lib/common/*")
+      .addClasspath("./lib/server/*");
+    String driverPath = props.value(ProcessProperties.JDBC_DRIVER_PATH);
+    if (driverPath != null) {
+      command.addClasspath(driverPath);
     }
+    return command;
+  }
 
   @Override
   public JavaCommand createCeCommand(Props props, File workDir) {
-      JavaCommand command = newJavaCommand(ProcessId.COMPUTE_ENGINE, props, workDir)
-        .addJavaOptions(ProcessProperties.CE_ENFORCED_JVM_ARGS)
-        .addJavaOptions(props.nonNullValue(ProcessProperties.CE_JAVA_OPTS))
-        .addJavaOptions(props.nonNullValue(ProcessProperties.CE_JAVA_ADDITIONAL_OPTS))
-        .setClassName("org.sonar.ce.app.CeServer")
-        .addClasspath("./lib/common/*")
-        .addClasspath("./lib/server/*")
-        .addClasspath("./lib/ce/*");
-      String driverPath = props.value(ProcessProperties.JDBC_DRIVER_PATH);
-      if (driverPath != null) {
-        command.addClasspath(driverPath);
-      }
-      return command;
+    JavaCommand command = newJavaCommand(ProcessId.COMPUTE_ENGINE, props, workDir)
+      .addJavaOptions(ProcessProperties.CE_ENFORCED_JVM_ARGS)
+      .addJavaOptions(props.nonNullValue(ProcessProperties.CE_JAVA_OPTS))
+      .addJavaOptions(props.nonNullValue(ProcessProperties.CE_JAVA_ADDITIONAL_OPTS))
+      .setClassName("org.sonar.ce.app.CeServer")
+      .addClasspath("./lib/common/*")
+      .addClasspath("./lib/server/*")
+      .addClasspath("./lib/ce/*");
+    String driverPath = props.value(ProcessProperties.JDBC_DRIVER_PATH);
+    if (driverPath != null) {
+      command.addClasspath(driverPath);
     }
+    return command;
+  }
 
   private static JavaCommand newJavaCommand(ProcessId id, Props props, File workDir) {
     JavaCommand command = new JavaCommand(id)