]> source.dussan.org Git - sonarqube.git/commitdiff
Replace DbClient#closeSession(DbSession) by try-with-resources
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Thu, 23 Feb 2017 21:49:29 +0000 (22:49 +0100)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Sat, 25 Feb 2017 17:38:06 +0000 (18:38 +0100)
57 files changed:
server/sonar-db-dao/src/main/java/org/sonar/db/DbClient.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/notification/NotificationQueueDao.java
server/sonar-server/src/main/java/org/sonar/ce/queue/CeQueueImpl.java
server/sonar-server/src/main/java/org/sonar/server/authentication/CredentialsAuthenticator.java
server/sonar-server/src/main/java/org/sonar/server/authentication/JwtHttpHandler.java
server/sonar-server/src/main/java/org/sonar/server/ce/ws/IsQueueEmptyWs.java
server/sonar-server/src/main/java/org/sonar/server/component/ws/ShowAction.java
server/sonar-server/src/main/java/org/sonar/server/computation/queue/CeQueueInitializer.java
server/sonar-server/src/main/java/org/sonar/server/computation/queue/InternalCeQueueImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/component/UuidFactory.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/issue/RuleRepositoryImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/scm/ScmInfoRepositoryImpl.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ComputeMeasureVariationsStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/LoadPeriodsStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistAnalysisStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistComponentsStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PersistCrossProjectDuplicationIndexStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/PurgeDatastoresStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStep.java
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/step/ValidateProjectStep.java
server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java
server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CreateAction.java
server/sonar-server/src/main/java/org/sonar/server/measure/ws/ComponentAction.java
server/sonar-server/src/main/java/org/sonar/server/measure/ws/ComponentTreeDataLoader.java
server/sonar-server/src/main/java/org/sonar/server/project/ws/BulkUpdateKeyAction.java
server/sonar-server/src/main/java/org/sonar/server/project/ws/UpdateKeyAction.java
server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java
server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/DeleteAction.java
server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/SearchAction.java
server/sonar-server/src/main/java/org/sonar/server/property/ws/IndexAction.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/QgateProjectFinder.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/QualityGates.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/RegisterQualityGates.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/AppAction.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/GetByProjectAction.java
server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/ProjectStatusAction.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporters.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/CompareAction.java
server/sonar-server/src/main/java/org/sonar/server/rule/DefaultRuleFinder.java
server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexer.java
server/sonar-server/src/main/java/org/sonar/server/rule/ws/CreateAction.java
server/sonar-server/src/main/java/org/sonar/server/rule/ws/ListAction.java
server/sonar-server/src/main/java/org/sonar/server/rule/ws/SearchAction.java
server/sonar-server/src/main/java/org/sonar/server/rule/ws/ShowAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java
server/sonar-server/src/main/java/org/sonar/server/startup/ClearRulesOverloadedDebt.java
server/sonar-server/src/main/java/org/sonar/server/startup/DisplayLogOnDeprecatedProjects.java
server/sonar-server/src/main/java/org/sonar/server/test/ws/CoveredFilesAction.java
server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java
server/sonar-server/src/main/java/org/sonar/server/user/ws/CurrentAction.java
server/sonar-server/src/main/java/org/sonar/server/user/ws/SearchAction.java
server/sonar-server/src/main/java/org/sonar/server/usertoken/UserTokenAuthenticator.java

index 24dc5dfea8b3cc7e7b5c41ab011851c6ed1b7011..0102d58ac2ffd31ec9a1ff65a2392a4f5f463b07 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.db;
 
 import java.util.IdentityHashMap;
 import java.util.Map;
-import javax.annotation.Nullable;
 import org.sonar.db.ce.CeActivityDao;
 import org.sonar.db.ce.CeQueueDao;
 import org.sonar.db.ce.CeScannerContextDao;
@@ -177,10 +176,6 @@ public class DbClient {
     return myBatis.openSession(batch);
   }
 
-  public void closeSession(@Nullable DbSession session) {
-    MyBatis.closeQuietly(session);
-  }
-
   public Database getDatabase() {
     return database;
   }
index 5ca05d074cde910f7398c932479de68bbaa24b1a..4f1606aa633a3d230ae3edf136be5ee80cf2d799 100644 (file)
@@ -30,7 +30,6 @@ import java.util.Set;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 import org.apache.commons.lang.StringUtils;
-import org.apache.ibatis.session.SqlSession;
 import org.sonar.api.resources.Qualifiers;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
@@ -55,9 +54,8 @@ public class ComponentKeyUpdaterDao implements Dao {
   }
 
   public void updateKey(String projectUuid, String newKey) {
-    DbSession session = mybatis.openSession(true);
-    ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class);
-    try {
+    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.");
       }
@@ -72,16 +70,13 @@ public class ComponentKeyUpdaterDao implements Dao {
       runBatchUpdateForAllResources(resources, projectOldKey, newKey, mapper);
 
       session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
   public Map<String, String> checkModuleKeysBeforeRenaming(String projectUuid, String stringToReplace, String replacementString) {
-    SqlSession session = mybatis.openSession(false);
-    ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class);
-    Map<String, String> result = Maps.newHashMap();
-    try {
+    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);
@@ -91,10 +86,8 @@ public class ComponentKeyUpdaterDao implements Dao {
           result.put(module.getKey(), newKey);
         }
       }
-    } finally {
-      MyBatis.closeQuietly(session);
+      return result;
     }
-    return result;
   }
 
   public static void checkIsProjectOrModule(ComponentDto component) {
index 79423e9f79d923f637581cc2ce62960b2be02911..e62dc9a014cadd347649fd176d6cd21b32243964 100644 (file)
@@ -47,13 +47,9 @@ public class IssueChangeDao implements Dao {
   }
 
   public List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(String componentUuid) {
-    DbSession session = mybatis.openSession(false);
-    try {
+    try (DbSession session = mybatis.openSession(false)) {
       IssueChangeMapper mapper = mapper(session);
       return mapper.selectChangelogOfNonClosedIssuesByComponent(componentUuid, IssueChangeDto.TYPE_FIELD_CHANGE);
-
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
index d72b550791878ffdd4488f15659f12d73a32470a..90c70291d7da8c238977b1efe8d1c225a9b0a5f6 100644 (file)
@@ -33,11 +33,8 @@ public class LoadedTemplateDao implements Dao {
   }
 
   public int countByTypeAndKey(String type, String key) {
-    SqlSession session = mybatis.openSession(false);
-    try {
+    try (DbSession session = mybatis.openSession(false)) {
       return countByTypeAndKey(type, key, session);
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
@@ -46,12 +43,9 @@ public class LoadedTemplateDao implements Dao {
   }
 
   public void insert(LoadedTemplateDto loadedTemplateDto) {
-    SqlSession session = mybatis.openSession(false);
-    try {
+    try (DbSession session = mybatis.openSession(false)) {
       insert(loadedTemplateDto, session);
       session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
index be3902914449a4c21ac6a06ade9ba5f99e79983b..ab56cd0c7040c4982ffb84060f57622ca9aecde6 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.db.notification;
 
 import java.util.Collections;
 import java.util.List;
-import org.apache.ibatis.session.SqlSession;
 import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
 import org.sonar.db.MyBatis;
@@ -35,28 +34,22 @@ public class NotificationQueueDao implements Dao {
   }
 
   public void insert(List<NotificationQueueDto> dtos) {
-    DbSession session = mybatis.openSession(true);
-    NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class);
-    try {
+    try (DbSession session = mybatis.openSession(true)) {
+      NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class);
       for (NotificationQueueDto dto : dtos) {
         mapper.insert(dto);
       }
       session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
   public void delete(List<NotificationQueueDto> dtos) {
-    DbSession session = mybatis.openSession(true);
-    NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class);
-    try {
+    try (DbSession session = mybatis.openSession(true)) {
+      NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class);
       for (NotificationQueueDto dto : dtos) {
         mapper.delete(dto.getId());
       }
       session.commit();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
@@ -64,20 +57,14 @@ public class NotificationQueueDao implements Dao {
     if (count < 1) {
       return Collections.emptyList();
     }
-    SqlSession session = mybatis.openSession(false);
-    try {
+    try (DbSession session = mybatis.openSession(false)) {
       return session.getMapper(NotificationQueueMapper.class).findOldest(count);
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 
   public long count() {
-    SqlSession session = mybatis.openSession(false);
-    try {
+    try (DbSession session = mybatis.openSession(false)) {
       return session.getMapper(NotificationQueueMapper.class).count();
-    } finally {
-      MyBatis.closeQuietly(session);
     }
   }
 }
index 6cdfe37bfc4bdb39abf91ebee6ed5ec9190af5df..a78c09090badeb4b6b54153f187836ff38c201c3 100644 (file)
@@ -70,15 +70,11 @@ public class CeQueueImpl implements CeQueue {
   public CeTask submit(CeTaskSubmit submission) {
     checkState(!submitPaused.get(), "Compute Engine does not currently accept new tasks");
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       CeQueueDto dto = new CeTaskSubmitToInsertedCeQueueDto(dbSession, dbClient).apply(submission);
       CeTask task = loadTask(dbSession, dto);
       dbSession.commit();
       return task;
-
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -89,17 +85,13 @@ public class CeQueueImpl implements CeQueue {
       return Collections.emptyList();
     }
 
-    DbSession dbSession = dbClient.openSession(true);
-    try {
+    try (DbSession dbSession = dbClient.openSession(true)) {
       List<CeQueueDto> ceQueueDtos = from(submissions)
         .transform(new CeTaskSubmitToInsertedCeQueueDto(dbSession, dbClient))
         .toList();
       List<CeTask> tasks = loadTasks(dbSession, ceQueueDtos);
       dbSession.commit();
       return tasks;
-
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -130,8 +122,7 @@ public class CeQueueImpl implements CeQueue {
 
   @Override
   public boolean cancel(String taskUuid) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskUuid);
       if (queueDto.isPresent()) {
         checkState(CeQueueDto.Status.PENDING.equals(queueDto.get().getStatus()), "Task is in progress and can't be canceled [uuid=%s]", taskUuid);
@@ -139,8 +130,6 @@ public class CeQueueImpl implements CeQueue {
         return true;
       }
       return false;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -157,8 +146,7 @@ public class CeQueueImpl implements CeQueue {
 
   protected int cancelAll(boolean includeInProgress) {
     int count = 0;
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       for (CeQueueDto queueDto : dbClient.ceQueueDao().selectAllInAscOrder(dbSession)) {
         if (includeInProgress || !queueDto.getStatus().equals(CeQueueDto.Status.IN_PROGRESS)) {
           cancelImpl(dbSession, queueDto);
@@ -166,8 +154,6 @@ public class CeQueueImpl implements CeQueue {
         }
       }
       return count;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 387385034ef6b374ae830a85e3f0a12a271d8957..c0d87f2b34557949ab501d195bbb5ec6b0166fe9 100644 (file)
@@ -46,11 +46,8 @@ public class CredentialsAuthenticator {
   }
 
   public UserDto authenticate(String userLogin, String userPassword, HttpServletRequest request, Method method) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       return authenticate(dbSession, userLogin, userPassword, request, method);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index d5da7740e0a83eccada2882b644f493475dd18b1..b2c0f837fbdd8816db43dea768c2e2614dd060f2 100644 (file)
@@ -171,11 +171,8 @@ public class JwtHttpHandler {
   }
 
   private Optional<UserDto> selectUserFromDb(String userLogin) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       return Optional.ofNullable(dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin));
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 0b433f008874ad3ad43293cfa2fce55f6f8993ef..75b40d780b61e39a7145e649960ad81e7c0434f4 100644 (file)
@@ -67,12 +67,9 @@ public class IsQueueEmptyWs implements WebService {
 
     @Override
     public void handle(Request request, Response response) throws Exception {
-      DbSession dbSession = dbClient.openSession(false);
-      try {
+      try (DbSession dbSession = dbClient.openSession(false)) {
         boolean isQueueEmpty = dbClient.ceQueueDao().selectAllInAscOrder(dbSession).isEmpty();
         IOUtils.write(String.valueOf(isQueueEmpty), response.stream().output());
-      } finally {
-        dbClient.closeSession(dbSession);
       }
     }
   }
index c60d687b1d105104d909d260f2f6fe9ee1031a3f..1ef14f0ee269dae9a4aecb4b3c090326a74c107d 100644 (file)
@@ -93,15 +93,12 @@ public class ShowAction implements ComponentsWsAction {
   }
 
   private ShowWsResponse doHandle(ShowWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = getComponentByUuidOrKey(dbSession, request);
       Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.projectUuid());
       List<ComponentDto> ancestors = dbClient.componentDao().selectAncestors(dbSession, component);
       OrganizationDto organizationDto = componentFinder.getOrganization(dbSession, component);
       return buildResponse(component, organizationDto, ancestors, lastAnalysis);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 7a0f627c8da0d79712f5e7969b56762407d47190..93a260ced5a28d1b79345d3823be0b1d7ba378b4 100644 (file)
@@ -54,13 +54,9 @@ public class CeQueueInitializer implements ServerStartHandler {
   }
 
   private void initCe() {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       cleaner.clean(dbSession);
       scheduler.startScheduling();
-
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 }
index 33a542747b7c5bdf1d3aa5269f42f745b51e2ee9..072e55bc174e8cbd83532b33ac09e814ae15f336 100644 (file)
@@ -67,8 +67,7 @@ public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue
     if (peekPaused.get()) {
       return Optional.absent();
     }
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<CeQueueDto> dto = dbClient.ceQueueDao().peek(dbSession);
       CeTask task = null;
       if (dto.isPresent()) {
@@ -77,8 +76,6 @@ public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue
       }
       return Optional.fromNullable(task);
 
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -90,8 +87,7 @@ public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue
   @Override
   public void remove(CeTask task, CeActivityDto.Status status, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
     checkArgument(error == null || status == CeActivityDto.Status.FAILED, "Error can be provided only when status is FAILED");
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, task.getUuid());
       checkState(queueDto.isPresent(), "Task does not exist anymore: %s", task);
       CeActivityDto activityDto = new CeActivityDto(queueDto.get());
@@ -100,8 +96,6 @@ public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue
       updateTaskResult(activityDto, taskResult);
       updateError(activityDto, error);
       remove(dbSession, queueDto.get(), activityDto);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 0a0e7eac9093254729df0dc92e9f7a60cfb74d95..f050e817ad8b3f0142fffb5dbcda089f9726d083 100644 (file)
@@ -31,14 +31,11 @@ public class UuidFactory {
   private final Map<String, String> uuidsByKey = new HashMap<>();
 
   public UuidFactory(DbClient dbClient, String rootKey) {
-    DbSession session = dbClient.openSession(false);
-    try {
-      List<ComponentDto> components = dbClient.componentDao().selectAllComponentsFromProjectKey(session, rootKey);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      List<ComponentDto> components = dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, rootKey);
       for (ComponentDto componentDto : components) {
         uuidsByKey.put(componentDto.getKey(), componentDto.uuid());
       }
-    } finally {
-      dbClient.closeSession(session);
     }
   }
 
index 0052299deab7aa7699edf192d9befefec2659a9b..7e0dd8c21f9d477e08bff8fb087ac18b03052a0e 100644 (file)
@@ -86,11 +86,8 @@ public class RuleRepositoryImpl implements RuleRepository {
 
   private void ensureInitialized() {
     if (rulesByKey == null) {
-      DbSession dbSession = dbClient.openSession(false);
-      try {
+      try (DbSession dbSession = dbClient.openSession(false)) {
         loadRulesFromDb(dbSession);
-      } finally {
-        dbClient.closeSession(dbSession);
       }
     }
   }
index 919392eb1d4dd2faddee981641094f5015da08ca..4d50f32733b1ed3ba543f628f7cafaa1a17b9b4f 100644 (file)
@@ -98,15 +98,12 @@ public class ScmInfoRepositoryImpl implements ScmInfoRepository {
     }
 
     LOGGER.trace("Reading SCM info from db for file '{}'", file.getKey());
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       FileSourceDto dto = dbClient.fileSourceDao().selectSourceByFileUuid(dbSession, file.getUuid());
       if (dto == null || !sourceHashRepository.getRawSourceHash(file).equals(dto.getSrcHash())) {
         return NoScmInfo.INSTANCE;
       }
       return DbScmInfo.create(file, dto.getSourceData().getLinesList()).or(NoScmInfo.INSTANCE);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 822b61ee23fcb7ea6167c77d0236209a53f6f05b..074fc983bf4cbb59d51d45ab7f45aa6e03d10841 100644 (file)
@@ -80,13 +80,10 @@ public class ComputeMeasureVariationsStep implements ComputationStep {
 
   @Override
   public void execute() {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<Metric> metrics = StreamSupport.stream(metricRepository.getAll().spliterator(), false).filter(isNumeric()).collect(Collectors.toList());
       new DepthTraversalTypeAwareCrawler(new VariationMeasuresVisitor(dbSession, metrics))
         .visit(treeRootHolder.getRoot());
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index b47c7c687e8b32545361422b9db3cb3104e18f3c..e34bdc8b387bd2a406aa9ae24691ecbffca0339c 100644 (file)
@@ -116,13 +116,10 @@ public class LoadCrossProjectDuplicationsRepositoryStep implements ComputationSt
     }
 
     private List<DuplicationUnitDto> selectDuplicates(Component file, Collection<String> hashes) {
-      DbSession dbSession = dbClient.openSession(false);
-      try {
+      try (DbSession dbSession = dbClient.openSession(false)) {
         Analysis projectAnalysis = analysisMetadataHolder.getBaseAnalysis();
         String analysisUuid = projectAnalysis == null ? null : projectAnalysis.getUuid();
         return dbClient.duplicationDao().selectCandidates(dbSession, analysisUuid, file.getFileAttributes().getLanguageKey(), hashes);
-      } finally {
-        dbClient.closeSession(dbSession);
       }
     }
   }
index aa9558d68f25fee2edb80821c3d43e3acc0ea172..75e40591c3c3f54975738121ee39263f51f996a8 100644 (file)
@@ -83,11 +83,8 @@ public class LoadPeriodsStep implements ComputationStep {
   }
 
   public void execute(Component projectOrView) {
-    DbSession session = dbClient.openSession(false);
-    try {
-      periodsHolder.setPeriod(buildPeriod(projectOrView, session));
-    } finally {
-      dbClient.closeSession(session);
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      periodsHolder.setPeriod(buildPeriod(projectOrView, dbSession));
     }
   }
 
index a7cbf7cef2c74edb405e8418ae1e0db5de018bb3..ef8e57dc3a20625fc5f2346619fa43c786f0b188 100644 (file)
@@ -55,14 +55,11 @@ public class PersistAnalysisStep implements ComputationStep {
 
   @Override
   public void execute() {
-    DbSession session = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       new DepthTraversalTypeAwareCrawler(
-        new PersistSnapshotsPathAwareVisitor(session, analysisMetadataHolder.getAnalysisDate()))
+        new PersistSnapshotsPathAwareVisitor(dbSession, analysisMetadataHolder.getAnalysisDate()))
           .visit(treeRootHolder.getRoot());
-      session.commit();
-    } finally {
-      dbClient.closeSession(session);
+      dbSession.commit();
     }
   }
 
index 97345d99b2e2a94339518df47837ae06f65d49b9..f20245b652fc54f05cf18425dc3d2237a82ac48c 100644 (file)
@@ -85,8 +85,7 @@ public class PersistComponentsStep implements ComputationStep {
 
   @Override
   public void execute() {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       String projectUuid = treeRootHolder.getRoot().getUuid();
 
       // safeguard, reset all rows to b-changed=false
@@ -101,8 +100,6 @@ public class PersistComponentsStep implements ComputationStep {
       disableRemainingComponents(dbSession, existingDtosByKeys.values());
 
       dbSession.commit();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index f7145f0be8ff66332223b8214d156d0adf0b3e25..7dc928e7c1f8d8d29bfe81ab7bfde6cfa401dbe8 100644 (file)
@@ -63,13 +63,10 @@ public class PersistCrossProjectDuplicationIndexStep implements ComputationStep
       return;
     }
 
-    DbSession session = dbClient.openSession(true);
-    try {
+    try (DbSession dbSession = dbClient.openSession(true)) {
       Component project = treeRootHolder.getRoot();
-      new DepthTraversalTypeAwareCrawler(new DuplicationVisitor(session, analysisMetadataHolder.getUuid())).visit(project);
-      session.commit();
-    } finally {
-      dbClient.closeSession(session);
+      new DepthTraversalTypeAwareCrawler(new DuplicationVisitor(dbSession, analysisMetadataHolder.getUuid())).visit(project);
+      dbSession.commit();
     }
   }
 
index 6e3172241b4c87ddebc50576e0f75c2083095d32..f260563094c713941cd286199526d2bbd3cae6ae 100644 (file)
@@ -73,13 +73,10 @@ public class PurgeDatastoresStep implements ComputationStep {
   }
 
   private void execute(Component root) {
-    DbSession session = dbClient.openSession(true);
-    try {
+    try (DbSession dbSession = dbClient.openSession(true)) {
       IdUuidPair idUuidPair = new IdUuidPair(dbIdsRepository.getComponentId(root), root.getUuid());
-      projectCleaner.purge(session, idUuidPair, settingsRepository.getSettings(root), disabledComponentsHolder.getUuids());
-      session.commit();
-    } finally {
-      dbClient.closeSession(session);
+      projectCleaner.purge(dbSession, idUuidPair, settingsRepository.getSettings(root), disabledComponentsHolder.getUuids());
+      dbSession.commit();
     }
   }
 
index e6f3ed493d9e5295105dfb60771cdc244b979ef1..cc93017ec04f2185f6c89b4ec99ee0e3e797a511 100644 (file)
@@ -60,8 +60,7 @@ public class UpdateQualityProfilesLastUsedDateStep implements ComputationStep {
 
   @Override
   public void execute() {
-    DbSession dbSession = dbClient.openSession(true);
-    try {
+    try (DbSession dbSession = dbClient.openSession(true)) {
       Component root = treeRootHolder.getRoot();
       Metric metric = metricRepository.getByKey(QUALITY_PROFILES_KEY);
       Set<QualityProfile> qualityProfiles = parseQualityProfiles(measureRepository.getRawMeasure(root, metric));
@@ -78,8 +77,6 @@ public class UpdateQualityProfilesLastUsedDateStep implements ComputationStep {
       });
 
       dbSession.commit();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 6d67330e7d03f84a852922a8ac30e36b8730dcdc..aff50f630b36abb9b73c2f0d6aa02cf415dbb414 100644 (file)
@@ -76,19 +76,16 @@ public class ValidateProjectStep implements ComputationStep {
 
   @Override
   public void execute() {
-    DbSession session = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Component root = treeRootHolder.getRoot();
-      List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(session, root.getKey());
+      List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getKey());
       Map<String, ComponentDto> baseModulesByKey = from(baseModules).uniqueIndex(ComponentDto::key);
-      ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(session, dbClient.componentDao(), baseModulesByKey);
+      ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
       new DepthTraversalTypeAwareCrawler(visitor).visit(root);
 
       if (!visitor.validationMessages.isEmpty()) {
         throw MessageException.of("Validation of project failed:\n  o " + MESSAGES_JOINER.join(visitor.validationMessages));
       }
-    } finally {
-      dbClient.closeSession(session);
     }
   }
 
index fc154a3758b25599910744f1033618e1843b1a35..f44e0a3d00207c5b30af6699259c0fef501c6fc7 100644 (file)
@@ -71,8 +71,7 @@ public class SearchResponseLoader {
    * The issue keys are given by the multi-criteria search in Elasticsearch index.
    */
   public SearchResponseData load(Collector collector, @Nullable Facets facets) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       SearchResponseData result = new SearchResponseData(dbClient.issueDao().selectByOrderedKeys(dbSession, collector.getIssueKeys()));
       collector.collect(result.getIssues());
 
@@ -86,8 +85,6 @@ public class SearchResponseLoader {
       loadActionsAndTransitions(collector, result);
       completeTotalEffortFromFacet(facets, result);
       return result;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index bf630ef1b75cb17cce0621f08b770bc5b5c5011f..b0489c52edff2fecf1ab0447f5c678154bd1c34c 100644 (file)
@@ -105,12 +105,11 @@ public class CreateAction implements CustomMeasuresWsAction {
 
   @Override
   public void handle(Request request, Response response) throws Exception {
-    DbSession dbSession = dbClient.openSession(false);
     String valueAsString = request.mandatoryParam(PARAM_VALUE);
     String description = request.param(PARAM_DESCRIPTION);
     long now = system.now();
 
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = componentFinder.getByUuidOrKey(dbSession, request.param(PARAM_PROJECT_ID), request.param(PARAM_PROJECT_KEY), PROJECT_ID_AND_KEY);
       MetricDto metric = searchMetric(dbSession, request);
       checkPermissions(userSession, component);
@@ -131,8 +130,6 @@ public class CreateAction implements CustomMeasuresWsAction {
       JsonWriter json = response.newJsonWriter();
       customMeasureJsonWriter.write(json, measure, metric, component, user, true, CustomMeasureJsonWriter.OPTIONAL_FIELDS);
       json.close();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 65716911364a2addbb0002c920657772def9d0c7..ad0c597df08d6ec899e6d967bea33fa70577aa87 100644 (file)
@@ -123,8 +123,7 @@ public class ComponentAction implements MeasuresWsAction {
   }
 
   private ComponentWsResponse doHandle(ComponentWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = componentFinder.getByUuidOrKey(dbSession, request.getComponentId(), request.getComponentKey(), COMPONENT_ID_AND_KEY);
       Long developerId = searchDeveloperId(dbSession, request);
       Optional<ComponentDto> refComponent = getReferenceComponent(dbSession, component);
@@ -135,8 +134,6 @@ public class ComponentAction implements MeasuresWsAction {
       List<MeasureDto> measures = searchMeasures(dbSession, component, analysis, metrics, developerId);
 
       return buildResponse(request, component, refComponent, measures, metrics, periods);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 34364cba92619caf7a65b35686807e079e37a0ce..47bc1cc7657f5bc0067f8f83217bbc0e2d584fea 100644 (file)
@@ -89,8 +89,7 @@ public class ComponentTreeDataLoader {
   }
 
   ComponentTreeData load(ComponentTreeWsRequest wsRequest) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto baseComponent = componentFinder.getByUuidOrKey(dbSession, wsRequest.getBaseComponentId(), wsRequest.getBaseComponentKey(), BASE_COMPONENT_ID_AND_KEY);
       checkPermissions(baseComponent);
       Optional<SnapshotDto> baseSnapshot = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, baseComponent.projectUuid());
@@ -122,8 +121,6 @@ public class ComponentTreeDataLoader {
         .setPeriods(snapshotToWsPeriods(baseSnapshot.get()))
         .setReferenceComponentsByUuid(searchReferenceComponentsById(dbSession, components))
         .build();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 7c048152d8c9cef4c48c661be47464fd6da349e4..890571e70ba5471edbb8d40e97863d06b6d14328 100644 (file)
@@ -132,8 +132,7 @@ public class BulkUpdateKeyAction implements ProjectsWsAction {
   }
 
   private BulkUpdateKeyWsResponse doHandle(BulkUpdateKeyWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto projectOrModule = componentFinder.getByUuidOrKey(dbSession, request.getId(), request.getKey(), ParamNames.ID_AND_KEY);
       checkIsProjectOrModule(projectOrModule);
       userSession.checkComponentPermission(UserRole.ADMIN, projectOrModule);
@@ -147,8 +146,6 @@ public class BulkUpdateKeyAction implements ProjectsWsAction {
       }
 
       return buildResponse(newKeysByOldKeys, newKeysWithDuplicateMap);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index f9d9d408e840a437f10141e0f795e31b489d4faa..d845d695d89e9e4331c9c8f34edd627035207900 100644 (file)
@@ -98,13 +98,10 @@ public class UpdateKeyAction implements ProjectsWsAction {
   }
 
   private void doHandle(UpdateKeyWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto projectOrModule = componentFinder.getByUuidOrKey(dbSession, request.getId(), request.getKey(), ParamNames.PROJECT_ID_AND_FROM);
       componentService.updateKey(dbSession, projectOrModule, request.getNewKey());
       dbSession.commit();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 623c7d7a5fb840dfc171ad9bfd86e68db575604b..7d51c91d044c9e591a578893b360a8c2efc38daf 100644 (file)
@@ -102,8 +102,7 @@ public class CreateAction implements ProjectLinksWsAction {
     String name = createWsRequest.getName();
     String url = createWsRequest.getUrl();
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = getComponentByUuidOrKey(dbSession, createWsRequest);
 
       userSession.checkComponentPermission(UserRole.ADMIN, component);
@@ -117,8 +116,6 @@ public class CreateAction implements ProjectLinksWsAction {
 
       dbSession.commit();
       return buildResponse(link);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 2c1258f949683b8900cc7f27ce5b88b8f5c7f2d1..8fac8ecdb67d91b72ef901cd3c196caec9626549 100644 (file)
@@ -72,8 +72,7 @@ public class DeleteAction implements ProjectLinksWsAction {
   }
 
   private void doHandle(DeleteWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       long id = request.getId();
       ComponentLinkDto link = dbClient.componentLinkDao().selectById(dbSession, id);
 
@@ -83,8 +82,6 @@ public class DeleteAction implements ProjectLinksWsAction {
 
       dbClient.componentLinkDao().delete(dbSession, link.getId());
       dbSession.commit();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index b11e6f909db5585aaccadcf437db0ecf0011719f..8717182d46551e5dbf7420611a6e6ea8b3460059 100644 (file)
@@ -89,14 +89,11 @@ public class SearchAction implements ProjectLinksWsAction {
   }
 
   private SearchWsResponse doHandle(SearchWsRequest searchWsRequest) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto component = getComponentByUuidOrKey(dbSession, searchWsRequest);
       List<ComponentLinkDto> links = dbClient.componentLinkDao()
         .selectByComponentUuid(dbSession, component.uuid());
       return buildResponse(links);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 7154d689f7e91a368fda9493b11aa03d2f99e5ff..c261aed0f7ac69bcbef87f56bde470de63597f1d 100644 (file)
@@ -102,14 +102,11 @@ public class IndexAction implements WsAction {
   }
 
   private void doHandle(JsonWriter json, Request request) {
-    DbSession dbSession = dbClient.openSession(true);
-    try {
+    try (DbSession dbSession = dbClient.openSession(true)) {
       Optional<ComponentDto> component = loadComponent(dbSession, request);
       String key = request.param(PARAM_ID);
       List<PropertyDto> propertyDtos = loadProperties(dbSession, component, Optional.ofNullable(key));
       new ResponseBuilder(propertyDtos).build(json);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 646c989053467aaa634f6502dd598970b18234e5..fa5decc0225c26185fbcf5f978740c12d5ca699e 100644 (file)
@@ -53,8 +53,7 @@ public class QgateProjectFinder {
   }
 
   public Association find(ProjectQgateAssociationQuery query) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       getQualityGateId(dbSession, query.gateId());
       List<ProjectQgateAssociationDto> projects = associationDao.selectProjects(dbSession, query);
       List<ProjectQgateAssociationDto> authorizedProjects = keepAuthorizedProjects(dbSession, projects);
@@ -63,8 +62,6 @@ public class QgateProjectFinder {
         .withPageSize(query.pageSize())
         .andTotal(authorizedProjects.size());
       return new Association(toProjectAssociations(getPaginatedProjects(authorizedProjects, paging)), paging.hasNextPage());
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 0e9aac9fbb12d4c66b4b16e28089ca4ed4ef617b..359c8cfa462e2f74be63a38af3122ba1d54e4afa 100644 (file)
@@ -31,6 +31,7 @@ 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;
 import org.sonar.db.property.PropertyDto;
 import org.sonar.db.qualitygate.QualityGateConditionDao;
@@ -41,7 +42,6 @@ import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.Errors;
 import org.sonar.server.exceptions.Message;
 import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.db.permission.OrganizationPermission;
 import org.sonar.server.user.UserSession;
 import org.sonar.server.util.Validation;
 
@@ -140,12 +140,9 @@ public class QualityGates {
   }
 
   public void setDefault(@Nullable Long idToUseAsDefault) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       setDefault(dbSession, idToUseAsDefault);
       dbSession.commit();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index fd35142e2678c9a2ae5bd24ece92ec4cd7bf0560..8c30643ff6573df628e1e59bf711a9c4c68b9b91 100644 (file)
@@ -56,15 +56,12 @@ public class RegisterQualityGates implements Startable {
 
   @Override
   public void start() {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       if (shouldRegisterBuiltinQualityGate(dbSession)) {
         createBuiltinQualityGate(dbSession);
         registerBuiltinQualityGate(dbSession);
         dbSession.commit();
       }
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index c48a8348427118f6ac7968b9978755252491a5a9..324611084cfeccdec3343b309a10f099d14751a3 100644 (file)
@@ -86,14 +86,11 @@ public class AppAction implements QualityGatesWsAction {
   }
 
   private Collection<MetricDto> loadMetrics() {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       return dbClient.metricDao().selectEnabled(dbSession).stream()
         .filter(metric -> !metric.isDataType() && !ALERT_STATUS_KEY.equals(metric.getKey()) &&
           (!RATING.name().equals(metric.getValueType()) || isCoreRatingMetric(metric.getKey())))
         .collect(Collectors.toList());
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index b409a693327d4b9683be540b53fb64b47e012b15..66bef0377e2a384d619548ea6e877ec3577d6a3c 100644 (file)
@@ -77,14 +77,11 @@ public class GetByProjectAction implements QualityGatesWsAction {
 
   @Override
   public void handle(Request request, Response response) throws Exception {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto project = getProject(dbSession, request.param(PARAM_PROJECT_ID), request.param(PARAM_PROJECT_KEY));
       Optional<QualityGateData> data = qualityGateFinder.getQualityGate(dbSession, project.getId());
 
       writeProtobuf(buildResponse(data), request, response);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 6b220b99300b0d4ef8df208d6fadbe35cfe3e120..1e1ffe3403266e628559064801e191cb9727373e 100644 (file)
@@ -111,8 +111,7 @@ public class ProjectStatusAction implements QualityGatesWsAction {
   }
 
   private ProjectStatusWsResponse doHandle(ProjectStatusWsRequest request) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ProjectAndSnapshot projectAndSnapshot = getProjectAndSnapshot(dbSession, request);
       checkPermission(projectAndSnapshot.project);
       Optional<String> measureData = getQualityGateDetailsMeasureData(dbSession, projectAndSnapshot.project);
@@ -120,8 +119,6 @@ public class ProjectStatusAction implements QualityGatesWsAction {
       return ProjectStatusWsResponse.newBuilder()
         .setProjectStatus(new QualityGateDetailsFormatter(measureData, projectAndSnapshot.snapshotDto).format())
         .build();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 65eb76af0c958cd1bc99ca5d7176029433638a23..3d9c23674244ffed1a53a8369a8bbff03ed1a55d 100644 (file)
@@ -50,15 +50,11 @@ public class QProfileComparison {
   }
 
   public QProfileComparisonResult compare(String leftKey, String rightKey) {
-    QProfileComparisonResult result = new QProfileComparisonResult();
-
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      QProfileComparisonResult result = new QProfileComparisonResult();
       compare(dbSession, leftKey, rightKey, result);
-    } finally {
-      dbClient.closeSession(dbSession);
+      return result;
     }
-    return result;
   }
 
   private void compare(DbSession session, String leftKey, String rightKey, QProfileComparisonResult result) {
index f5fa40c44026547d0fe7530b96577bed026bab08..81463fc2126d72c43de819e71f94264955938745 100644 (file)
@@ -107,9 +107,8 @@ public class QProfileExporters {
   }
 
   private RulesProfile wrap(QualityProfileDto profile) {
-    DbSession dbSession = dbClient.openSession(false);
-    RulesProfile target = new RulesProfile(profile.getName(), profile.getLanguage());
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      RulesProfile target = new RulesProfile(profile.getName(), profile.getLanguage());
       List<ActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfileKey(dbSession, profile.getKey());
       List<ActiveRuleParamDto> activeRuleParamDtos = dbClient.activeRuleDao().selectParamsByActiveRuleIds(dbSession, Lists.transform(activeRuleDtos, ActiveRuleDto::getId));
       ListMultimap<Integer, ActiveRuleParamDto> activeRuleParamsByActiveRuleId = FluentIterable.from(activeRuleParamDtos).index(ActiveRuleParamDto::getActiveRuleId);
@@ -123,10 +122,8 @@ public class QProfileExporters {
           wrappedActiveRule.setParameter(activeRuleParamDto.getKey(), activeRuleParamDto.getValue());
         }
       }
-    } finally {
-      dbClient.closeSession(dbSession);
+      return target;
     }
-    return target;
   }
 
   private ProfileExporter findExporter(String exporterKey) {
index 53a8436c57975c6d553102ff00a20c5c411231c3..315329233f8cd0e0a7bf8051b14369bb8a02ebd7 100644 (file)
@@ -103,14 +103,11 @@ public class CompareAction implements QProfileWsAction {
 
     QProfileComparisonResult result = comparator.compare(leftKey, rightKey);
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<RuleDto> referencedRules = dbClient.ruleDao().selectByKeys(dbSession, new ArrayList<>(result.collectRuleKeys()));
       Map<RuleKey, RuleDto> rulesByKey = Maps.uniqueIndex(referencedRules, RuleDtoToRuleKey.INSTANCE);
       Map<String, RuleRepositoryDto> repositoriesByKey = Maps.uniqueIndex(dbClient.ruleRepositoryDao().selectAll(dbSession), RuleRepositoryDto::getKey);
       writeResult(response.newJsonWriter(), result, rulesByKey, repositoriesByKey);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index bf650d68de51fb0efb26343c464cbbb35d3b3e9d..51ef56f3360039df6629f8940c0bb48b60aa0b03 100644 (file)
@@ -59,15 +59,12 @@ public class DefaultRuleFinder implements RuleFinder {
   @Override
   @CheckForNull
   public org.sonar.api.rules.Rule findById(int ruleId) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<RuleDto> rule = ruleDao.selectById(ruleId, dbSession);
       if (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED) {
         return toRule(rule.get(), ruleDao.selectRuleParamsByRuleKey(dbSession, rule.get().getKey()));
       }
       return null;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -77,12 +74,9 @@ public class DefaultRuleFinder implements RuleFinder {
       return rules;
     }
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<RuleDto> ruleDtos = ruleDao.selectByIds(dbSession, new ArrayList<>(ruleIds));
       return convertToRuleApi(dbSession, ruleDtos);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -92,28 +86,22 @@ public class DefaultRuleFinder implements RuleFinder {
       return rules;
     }
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<RuleDto> ruleDtos = ruleDao.selectByKeys(dbSession, new ArrayList<>(ruleKeys));
       return convertToRuleApi(dbSession, ruleDtos);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
   @Override
   @CheckForNull
   public org.sonar.api.rules.Rule findByKey(RuleKey key) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<RuleDto> rule = ruleDao.selectByKey(dbSession, key);
       if (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED) {
         return toRule(rule.get(), ruleDao.selectRuleParamsByRuleKey(dbSession, rule.get().getKey()));
       } else {
         return null;
       }
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
@@ -125,30 +113,24 @@ public class DefaultRuleFinder implements RuleFinder {
 
   @Override
   public final org.sonar.api.rules.Rule find(org.sonar.api.rules.RuleQuery query) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<RuleDto> rules = ruleDao.selectByQuery(dbSession, query);
       if (!rules.isEmpty()) {
         RuleDto rule = rules.get(0);
         return toRule(rule, ruleDao.selectRuleParamsByRuleKey(dbSession, rule.getKey()));
       }
       return null;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
   @Override
   public final Collection<org.sonar.api.rules.Rule> findAll(org.sonar.api.rules.RuleQuery query) {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<RuleDto> rules = ruleDao.selectByQuery(dbSession, query);
       if (rules.isEmpty()) {
         return Collections.emptyList();
       }
       return convertToRuleApi(dbSession, rules);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 1bff020d96496a4a8e6b0d9a34b6bb50a6c72d27..5a2fd5f6024eaa350bb1c741c4256ca4e9186a12 100644 (file)
@@ -51,15 +51,12 @@ public class RuleIndexer extends BaseIndexer {
   }
 
   private long doIndex(BulkIndexer bulk, long lastUpdatedAt) {
-    DbSession dbSession = dbClient.openSession(false);
     long maxDate;
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       RuleResultSetIterator rowIt = RuleResultSetIterator.create(dbClient, dbSession, lastUpdatedAt);
       maxDate = doIndex(bulk, rowIt);
       rowIt.close();
       return maxDate;
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 70c271b5fe76d269b862d28b9a05817f5da1b9c7..992563fac13199cbdb2122999ed1e9c92ada3265 100644 (file)
@@ -132,8 +132,7 @@ public class CreateAction implements RulesWsAction {
   @Override
   public void handle(Request request, Response response) throws Exception {
     String customKey = request.mandatoryParam(PARAM_CUSTOM_KEY);
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       try {
         NewCustomRule newRule = NewCustomRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
           .setName(request.mandatoryParam(PARAM_NAME))
@@ -149,8 +148,6 @@ public class CreateAction implements RulesWsAction {
       } catch (ReactivationException e) {
         write409(dbSession, request, response, e.ruleKey());
       }
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index db7e225930068f4e2833d4e8d3db0f2ef82c4e68..dd3500a9ef528a5eadad266d99fb756851cbe187 100644 (file)
@@ -51,10 +51,9 @@ public class ListAction implements RulesWsAction {
 
   @Override
   public void handle(Request wsRequest, Response wsResponse) throws Exception {
-    DbSession dbSession = dbClient.openSession(false);
     final ListResponse.Builder listResponseBuilder = ListResponse.newBuilder();
     final ListResponse.Rule.Builder ruleBuilder = ListResponse.Rule.newBuilder();
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       dbClient.ruleDao().selectEnabled(dbSession, resultContext -> {
         RuleDto dto = (RuleDto) resultContext.getResultObject();
         ruleBuilder
@@ -65,8 +64,6 @@ public class ListAction implements RulesWsAction {
           .setInternalKey(nullToEmpty(dto.getConfigKey()));
         listResponseBuilder.addRules(ruleBuilder.build());
       });
-    } finally {
-      dbClient.closeSession(dbSession);
     }
 
     // JSON response is voluntarily not supported. This WS is for internal use.
index 4987f08f35417978e5a771e9cec79a6ab869c36c..44f1f340f789f8321cdaa32739186dfcfb5f3b4f 100644 (file)
@@ -151,16 +151,13 @@ public class SearchAction implements RulesWsAction {
 
   @Override
   public void handle(Request request, Response response) throws Exception {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       SearchWsRequest searchWsRequest = toSearchWsRequest(request);
       SearchOptions context = buildSearchOptions(searchWsRequest);
       RuleQuery query = ruleQueryFactory.createRuleQuery(request);
       SearchResult searchResult = doSearch(dbSession, query, context);
       SearchResponse responseBuilder = buildResponse(dbSession, searchWsRequest, context, searchResult, query);
       writeProtobuf(responseBuilder, request, response);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 696ea5efd1fc589b38aa5b25f374e33ef563bb76..09b7392b24ea81f8a19699834bb5f59a63cd5cbb 100644 (file)
@@ -90,8 +90,7 @@ public class ShowAction implements RulesWsAction {
   @Override
   public void handle(Request request, Response response) throws Exception {
     RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY));
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<RuleDto> optionalRule = dbClient.ruleDao().selectByKey(dbSession, key);
       checkFoundWithOptional(optionalRule, "Rule not found: " + key);
       RuleDto rule = optionalRule.get();
@@ -110,8 +109,6 @@ public class ShowAction implements RulesWsAction {
           .setRuleParameters(ruleParameters)
           .setTotal(1L));
       writeProtobuf(showResponse, request, response);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 1c6131d381ec02483eb6414244ec62935d52bee4..539917950b79c0b169ad2a64dac16406684882fe 100644 (file)
@@ -101,16 +101,13 @@ public class ScmAction implements SourcesWsAction {
     int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE);
     boolean commitsByLine = request.mandatoryParamAsBoolean("commits_by_line");
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
       userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
       Iterable<DbFileSources.Line> sourceLines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "File '%s' has no sources", fileKey);
       JsonWriter json = response.newJsonWriter().beginObject();
       writeSource(sourceLines, commitsByLine, json);
       json.endObject().close();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 9a2db25f89795ed58dd1601b3542d2d1caf88b33..419fc30282b75d93d5ba5c76b537289d3ebd523b 100644 (file)
@@ -61,19 +61,16 @@ public class ClearRulesOverloadedDebt implements Startable {
 
   @Override
   public void start() {
-    DbSession session = dbClient.openSession(false);
-    try {
-      if (hasAlreadyBeenExecuted(session)) {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      if (hasAlreadyBeenExecuted(dbSession)) {
         return;
       }
-      if (!isSqalePluginInstalled(session)) {
-        clearDebt(session);
+      if (!isSqalePluginInstalled(dbSession)) {
+        clearDebt(dbSession);
       }
-      markAsExecuted(session);
-      session.commit();
+      markAsExecuted(dbSession);
+      dbSession.commit();
       ruleIndexer.index();
-    } finally {
-      dbClient.closeSession(session);
     }
   }
 
index ecacf890cd824f010606ad1316bd7956dac22fec..500c0fe7d49a17a4032dae227ebc75ab41cee3dd 100644 (file)
@@ -48,16 +48,13 @@ public class DisplayLogOnDeprecatedProjects implements Startable {
 
   @Override
   public void start() {
-    DbSession session = dbClient.openSession(false);
-    try {
-      if (!hasAlreadyBeenExecuted(session)) {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      if (!hasAlreadyBeenExecuted(dbSession)) {
         return;
       }
-      displayLogOnDeprecatedProjectKeys(session);
-      registerTasks(session);
-      session.commit();
-    } finally {
-      dbClient.closeSession(session);
+      displayLogOnDeprecatedProjectKeys(dbSession);
+      registerTasks(dbSession);
+      dbSession.commit();
     }
   }
 
index db39e62733ec4221f5654b09c5216267a20e93c1..59e0b451d7592812a91c13e99eb36bb33dead2fa 100644 (file)
@@ -103,12 +103,9 @@ public class CoveredFilesAction implements TestsWsAction {
 
   private Map<String, ComponentDto> buildComponentsByUuid(List<CoveredFileDoc> coveredFiles) {
     List<String> sourceFileUuids = Lists.transform(coveredFiles, new CoveredFileToFileUuidFunction());
-    DbSession dbSession = dbClient.openSession(false);
     List<ComponentDto> components;
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       components = dbClient.componentDao().selectByUuids(dbSession, sourceFileUuids);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
     return Maps.uniqueIndex(components, ComponentDto::uuid);
   }
index c1138d587cc8ac877544804011098912ce11949f..1a54f3efa379fe36fecf10b5d6c5b9caca0dc16b 100644 (file)
@@ -137,14 +137,11 @@ public class ListAction implements TestsWsAction {
       request.mandatoryParamAsInt(WebService.Param.PAGE),
       request.mandatoryParamAsInt(WebService.Param.PAGE_SIZE));
 
-    DbSession dbSession = dbClient.openSession(false);
     SearchResult<TestDoc> tests;
     Map<String, ComponentDto> componentsByTestFileUuid;
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       tests = searchTests(dbSession, testUuid, testFileUuid, testFileKey, sourceFileUuid, sourceFileKey, sourceFileLineNumber, searchOptions);
       componentsByTestFileUuid = buildComponentsByTestFileUuid(dbSession, tests.getDocs());
-    } finally {
-      dbClient.closeSession(dbSession);
     }
 
     WsTests.ListResponse.Builder responseBuilder = WsTests.ListResponse.newBuilder();
index b8744cbb460c588029ac83a2f3e34d1b2f1e8375..5cbd3511eb7bf54bff8cd2714194b5ff2ebabe32 100644 (file)
@@ -61,8 +61,7 @@ public class CurrentAction implements UsersWsAction {
 
   @Override
   public void handle(Request request, Response response) throws Exception {
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<UserDto> user = Optional.empty();
       Collection<String> groups = emptyList();
       if (userSession.isLoggedIn()) {
@@ -70,8 +69,6 @@ public class CurrentAction implements UsersWsAction {
         groups = selectGroups(dbSession);
       }
       writeResponse(response, user, groups);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 6d125106d19b481a6db61edeef826b3d822dc97f..1a0afb35b63e4086e7f2ce08d57860a92f4f12e0 100644 (file)
@@ -80,8 +80,7 @@ public class SearchAction implements UsersWsAction {
     List<String> fields = request.paramAsStrings(Param.FIELDS);
     SearchResult<UserDoc> result = userIndex.search(request.param(Param.TEXT_QUERY), options);
 
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       List<String> logins = Lists.transform(result.getDocs(), UserDocToLogin.INSTANCE);
       Multimap<String, String> groupsByLogin = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, logins);
       Map<String, Integer> tokenCountsByLogin = dbClient.userTokenDao().countTokensByLogins(dbSession, logins);
@@ -90,8 +89,6 @@ public class SearchAction implements UsersWsAction {
       List<UserDto> userDtos = dbClient.userDao().selectByOrderedLogins(dbSession, logins);
       writeUsers(json, userDtos, groupsByLogin, tokenCountsByLogin, fields);
       json.endObject().close();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 
index 50e43b43045a010879ccfc093b8222b4baf9869d..849342b8e16e25a7a400eb2885f3b39e4560b89d 100644 (file)
@@ -40,15 +40,12 @@ public class UserTokenAuthenticator {
    */
   public java.util.Optional<String> authenticate(String token) {
     String tokenHash = tokenGenerator.hash(token);
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+    try (DbSession dbSession = dbClient.openSession(false)) {
       Optional<UserTokenDto> userToken = dbClient.userTokenDao().selectByTokenHash(dbSession, tokenHash);
       if (userToken.isPresent()) {
         return java.util.Optional.of(userToken.get().getLogin());
       }
       return java.util.Optional.empty();
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 }