]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-8716 Use UserSession#checkComponentPermission(String,ComponentDto)
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Sun, 29 Jan 2017 18:52:26 +0000 (19:52 +0100)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Wed, 1 Feb 2017 16:11:52 +0000 (17:11 +0100)
34 files changed:
server/sonar-server/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java
server/sonar-server/src/main/java/org/sonar/server/ce/ws/ComponentAction.java
server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java
server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java
server/sonar-server/src/main/java/org/sonar/server/component/ws/BulkUpdateKeyAction.java
server/sonar-server/src/main/java/org/sonar/server/computation/queue/ReportSubmitter.java
server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java
server/sonar-server/src/main/java/org/sonar/server/favorite/ws/AddAction.java
server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/CustomMeasureValidator.java
server/sonar-server/src/main/java/org/sonar/server/measure/custom/ws/DeleteAction.java
server/sonar-server/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.java
server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.java
server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchAction.java
server/sonar-server/src/main/java/org/sonar/server/projectanalysis/ws/SearchResults.java
server/sonar-server/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java
server/sonar-server/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.java
server/sonar-server/src/main/java/org/sonar/server/setting/ws/ResetAction.java
server/sonar-server/src/main/java/org/sonar/server/setting/ws/SetAction.java
server/sonar-server/src/main/java/org/sonar/server/setting/ws/ValuesAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/HashAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/IndexAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/LinesAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/RawAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/ScmAction.java
server/sonar-server/src/main/java/org/sonar/server/source/ws/ShowAction.java
server/sonar-server/src/main/java/org/sonar/server/test/ws/ListAction.java
server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveriesAction.java
server/sonar-server/src/main/java/org/sonar/server/webhook/ws/WebhookDeliveryAction.java
server/sonar-server/src/test/java/org/sonar/server/duplication/ws/DuplicationsWsTest.java
server/sonar-server/src/test/java/org/sonar/server/duplication/ws/ShowActionTest.java
server/sonar-server/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/source/ws/IndexActionTest.java
server/sonar-server/src/test/java/org/sonar/server/tester/UserSessionRule.java

index b8e09db8b56acc64fb886b7f1847618779a2c13c..0e6191e460dd59ae7a078609e0020a7b549b5e86 100644 (file)
@@ -21,7 +21,6 @@
 package org.sonar.server.ce.ws;
 
 import com.google.common.base.Optional;
-import javax.annotation.Nullable;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
@@ -85,7 +84,7 @@ public class ActivityStatusAction implements CeWsAction {
     try {
       Optional<ComponentDto> component = searchComponent(dbSession, request);
       String componentUuid = component.isPresent() ? component.get().uuid() : null;
-      checkPermissions(componentUuid);
+      checkPermissions(component);
       int pendingCount = dbClient.ceQueueDao().countByStatusAndComponentUuid(dbSession, CeQueueDto.Status.PENDING, componentUuid);
       int failingCount = dbClient.ceActivityDao().countLastByStatusAndComponentUuid(dbSession, CeActivityDto.Status.FAILED, componentUuid);
 
@@ -106,11 +105,11 @@ public class ActivityStatusAction implements CeWsAction {
     return Optional.fromNullable(component);
   }
 
-  private void checkPermissions(@Nullable String componentUuid) {
-    if (componentUuid == null) {
-      userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);
+  private void checkPermissions(Optional<ComponentDto> component) {
+    if (component.isPresent()) {
+      userSession.checkComponentPermission(UserRole.ADMIN, component.get());
     } else {
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, componentUuid);
+      userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);
     }
   }
 
index a994c25cecb2d74737dca223a85b04d240b9fe9f..1c871e3331bd567c800b9f68b06901fc76fca791 100644 (file)
@@ -83,7 +83,7 @@ public class ComponentAction implements CeWsAction {
     DbSession dbSession = dbClient.openSession(false);
     try {
       ComponentDto component = componentFinder.getByUuidOrKey(dbSession, wsRequest.param(PARAM_COMPONENT_ID), wsRequest.param(PARAM_COMPONENT_KEY), COMPONENT_ID_AND_KEY);
-      userSession.checkComponentUuidPermission(UserRole.USER, component.uuid());
+      userSession.checkComponentPermission(UserRole.USER, component);
       List<CeQueueDto> queueDtos = dbClient.ceQueueDao().selectByComponentUuid(dbSession, component.uuid());
       CeTaskQuery activityQuery = new CeTaskQuery()
         .setComponentUuid(component.uuid())
index 18f973d2c1c58a89581133d3b30e5012233d2979..484024826f1d29c5780206e230ba220476a0e2cf 100644 (file)
@@ -57,7 +57,7 @@ public class ComponentService {
 
   // TODO should be moved to ComponentUpdater
   public void updateKey(DbSession dbSession, ComponentDto component, String newKey) {
-    userSession.checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid());
+    userSession.checkComponentPermission(UserRole.ADMIN, component);
     checkIsProjectOrModule(component);
     checkProjectOrModuleKeyFormat(newKey);
     dbClient.componentKeyUpdaterDao().updateKey(component.uuid(), newKey);
index 8b0adf82cfba01c4efab1fd2518b03f9e683a6ba..eb9dee249a16cbde791212191d8907ff90630f2e 100644 (file)
@@ -100,7 +100,7 @@ public class AppAction implements RequestHandler {
     DbSession session = dbClient.openSession(false);
     try {
       ComponentDto component = componentFinder.getByUuid(session, componentUuid);
-      userSession.checkComponentUuidPermission(UserRole.USER, component.uuid());
+      userSession.checkComponentPermission(UserRole.USER, component);
 
       Map<String, MeasureDto> measuresByMetricKey = measuresByMetricKey(component, session);
       appendComponent(json, component, userSession, session);
index 76f4e4c6036d6ee1bc83f6daf6233d77d905b847..52116dbe2e1cabe9874deb0cadf1c6f750526f07 100644 (file)
@@ -124,7 +124,7 @@ public class BulkUpdateKeyAction implements ComponentsWsAction {
     try {
       ComponentDto projectOrModule = componentFinder.getByUuidOrKey(dbSession, request.getId(), request.getKey(), ParamNames.ID_AND_KEY);
       checkIsProjectOrModule(projectOrModule);
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, projectOrModule.uuid());
+      userSession.checkComponentPermission(UserRole.ADMIN, projectOrModule);
 
       Map<String, String> newKeysByOldKeys = componentKeyUpdater.simulateBulkUpdateKey(dbSession, projectOrModule.uuid(), request.getFrom(), request.getTo());
       Map<String, Boolean> newKeysWithDuplicateMap = componentKeyUpdater.checkComponentKeys(dbSession, ImmutableList.copyOf(newKeysByOldKeys.values()));
index fe3170cfc73988e25ab78323217fc45e496744d0..a3c345a1f680ccbe6c2a65c45cb2c8a87650c77d 100644 (file)
@@ -76,7 +76,7 @@ public class ReportSubmitter {
       Optional<ComponentDto> opt = dbClient.componentDao().selectByKey(dbSession, effectiveProjectKey);
       ensureOrganizationIsConsistent(opt, organizationDto);
       ComponentDto project = opt.or(() -> createProject(dbSession, organizationDto.getUuid(), projectKey, projectBranch, projectName));
-      userSession.checkComponentUuidPermission(SCAN_EXECUTION, project.uuid());
+      userSession.checkComponentPermission(SCAN_EXECUTION, project);
       return submitReport(dbSession, reportInput, project);
     }
   }
index b052a8a806825b06fa1b2a98a36ab372d5aa57aa..3f0aa8f9adec792221496a52f351324a6aabcdb9 100644 (file)
@@ -33,7 +33,6 @@ import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.measure.MeasureDao;
 import org.sonar.db.measure.MeasureDto;
 import org.sonar.db.measure.MeasureQuery;
 import org.sonar.server.component.ComponentFinder;
@@ -44,16 +43,14 @@ import static org.sonar.server.component.ComponentFinder.ParamNames.UUID_AND_KEY
 public class ShowAction implements RequestHandler {
 
   private final DbClient dbClient;
-  private final MeasureDao measureDao;
   private final DuplicationsParser parser;
   private final DuplicationsJsonWriter duplicationsJsonWriter;
   private final UserSession userSession;
   private final ComponentFinder componentFinder;
 
-  public ShowAction(DbClient dbClient, MeasureDao measureDao, DuplicationsParser parser,
-                    DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) {
+  public ShowAction(DbClient dbClient, DuplicationsParser parser,
+    DuplicationsJsonWriter duplicationsJsonWriter, UserSession userSession, ComponentFinder componentFinder) {
     this.dbClient = dbClient;
-    this.measureDao = measureDao;
     this.parser = parser;
     this.duplicationsJsonWriter = duplicationsJsonWriter;
     this.userSession = userSession;
@@ -83,7 +80,7 @@ public class ShowAction implements RequestHandler {
     DbSession dbSession = dbClient.openSession(false);
     try {
       ComponentDto component = componentFinder.getByUuidOrKey(dbSession, request.param("uuid"), request.param("key"), UUID_AND_KEY);
-      userSession.checkComponentPermission(UserRole.CODEVIEWER, component.key());
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, component);
       JsonWriter json = response.newJsonWriter().beginObject();
       String duplications = findDataFromComponent(dbSession, component);
       List<DuplicationsParser.Block> blocks = parser.parse(component, duplications, dbSession);
@@ -100,7 +97,7 @@ public class ShowAction implements RequestHandler {
       .setComponentUuid(component.uuid())
       .setMetricKey(CoreMetrics.DUPLICATIONS_DATA_KEY)
       .build();
-    Optional<MeasureDto> measure = measureDao.selectSingle(dbSession, query);
+    Optional<MeasureDto> measure = dbClient.measureDao().selectSingle(dbSession, query);
     return measure.isPresent() ? measure.get().getData() : null;
   }
 }
index 94919aa1cff6d139732c5aee55110f29119edfb6..6689fe62f6405f246e76057cca977a4e2529bc6a 100644 (file)
@@ -75,7 +75,7 @@ public class AddAction implements FavoritesWsAction {
         ComponentDto componentDto = componentFinder.getByKey(dbSession, request.mandatoryParam(PARAM_COMPONENT));
         userSession
           .checkLoggedIn()
-          .checkComponentUuidPermission(UserRole.USER, componentDto.uuid());
+          .checkComponentPermission(UserRole.USER, componentDto);
         favoriteUpdater.add(dbSession, componentDto, userSession.isLoggedIn() ? userSession.getUserId().longValue() : null);
         dbSession.commit();
       }
index 8d215e83dc98238c9fda858a1c748678079e223a..35afa3e91a760985933ef64dd63ef5288938653c 100644 (file)
@@ -99,6 +99,6 @@ public class CustomMeasureValidator {
       return;
     }
 
-    userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid());
+    userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component);
   }
 }
index 980d9552cb8a4541277eb54f88c0dfb03ea4be3d..58e0a7dd55eec3a3095b2e1a1fe0cb5e992e12b5 100644 (file)
@@ -81,6 +81,6 @@ public class DeleteAction implements CustomMeasuresWsAction {
     }
 
     ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, customMeasure.getComponentUuid());
-    userSession.checkLoggedIn().checkComponentUuidPermission(UserRole.ADMIN, component.projectUuid());
+    userSession.checkLoggedIn().checkComponentPermission(UserRole.ADMIN, component);
   }
 }
index 9b9992e5ec77bdbd6fda1dcf89d0d3369a689ac9..2fe2c3ee1210f8ff2c51a7dd346ad7d7a6c03afb 100644 (file)
@@ -143,7 +143,7 @@ public class SearchHistoryAction implements MeasuresWsAction {
 
   private ComponentDto searchComponent(SearchHistoryRequest request, DbSession dbSession) {
     ComponentDto component = componentFinder.getByKey(dbSession, request.getComponent());
-    userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid());
+    userSession.checkComponentPermission(UserRole.USER, component);
     return component;
   }
 
index 078ca3cf5a513c4bf96bbf9fca81bc4f3c9de7c1..fbe5927ba402bdaf3a891b63809ba88213ead0b7 100644 (file)
@@ -113,18 +113,13 @@ public class CreateEventAction implements ProjectAnalysesWsAction {
   private CreateEventResponse doHandle(CreateEventRequest request) {
     try (DbSession dbSession = dbClient.openSession(false)) {
       SnapshotDto analysis = getAnalysis(dbSession, request);
-      checkPermissions(analysis);
       checkExistingDbEvents(dbSession, request, analysis);
       EventDto dbEvent = insertDbEvent(dbSession, request, analysis);
       return toCreateEventResponse(dbEvent);
     }
   }
 
-  private void checkPermissions(SnapshotDto analysis) {
-    userSession.checkComponentUuidPermission(UserRole.ADMIN, analysis.getComponentUuid());
-  }
-
-  private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) {
+    private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) {
     EventDto dbEvent = dbClient.eventDao().insert(dbSession, toDbEvent(request, analysis));
     if (VERSION.equals(request.getCategory())) {
       analysis.setVersion(request.getName());
@@ -139,6 +134,7 @@ public class CreateEventAction implements ProjectAnalysesWsAction {
       .orElseThrow(() -> new NotFoundException(format("Analysis '%s' is not found", request.getAnalysis())));
     ComponentDto project = dbClient.componentDao().selectByUuid(dbSession, analysis.getComponentUuid()).orNull();
     checkState(project != null, "Project of analysis '%s' is not found", analysis.getUuid());
+    userSession.checkComponentPermission(UserRole.ADMIN, project);
     checkArgument(Qualifiers.PROJECT.equals(project.qualifier()) && Scopes.PROJECT.equals(project.scope()),
       "An event must be created on a project");
     return analysis;
index 39235dd8e56f765dc06814b23ba17c72a42cd292..d8ea7986946dcf95f0ceb8b657e78c8432d702a6 100644 (file)
@@ -125,7 +125,7 @@ public class SearchAction implements ProjectAnalysesWsAction {
   private Consumer<SearchResults.Builder> addAnalyses() {
     return data -> {
       SnapshotQuery dbQuery = new SnapshotQuery()
-        .setComponentUuid(data.getProjectUuid())
+        .setComponentUuid(data.getProject().uuid())
         .setStatus(SnapshotDto.STATUS_PROCESSED)
         .setSort(BY_DATE, DESC);
       data.setAnalyses(dbClient.snapshotDao().selectAnalysesByQuery(data.getDbSession(), dbQuery));
@@ -140,14 +140,14 @@ public class SearchAction implements ProjectAnalysesWsAction {
   }
 
   private Consumer<SearchResults.Builder> checkPermission() {
-    return data -> userSession.checkComponentUuidPermission(UserRole.USER, data.getProjectUuid());
+    return data -> userSession.checkComponentPermission(UserRole.USER, data.getProject());
   }
 
   private Consumer<SearchResults.Builder> addProject() {
     return data -> {
       ComponentDto project = componentFinder.getByKey(data.getDbSession(), data.getRequest().getProject());
       checkArgument(Scopes.PROJECT.equals(project.scope()) && Qualifiers.PROJECT.equals(project.qualifier()), "A project is required");
-      data.setProjectUuid(project.uuid());
+      data.setProject(project);
     };
   }
 
index 30d1d9afe3fcf455d083d51ec39beebbd5f3c663..9a262ebe6b11d6307c7583d02a202445b15e8a8c 100644 (file)
@@ -27,6 +27,7 @@ import java.util.stream.Stream;
 import org.sonar.api.utils.Paging;
 import org.sonar.core.util.stream.Collectors;
 import org.sonar.db.DbSession;
+import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
 import org.sonar.db.event.EventDto;
 import org.sonarqube.ws.client.projectanalysis.SearchRequest;
@@ -58,7 +59,7 @@ class SearchResults {
   static class Builder {
     private final DbSession dbSession;
     private final SearchRequest request;
-    private String projectUuid;
+    private ComponentDto project;
     private List<SnapshotDto> analyses;
     private int countAnalyses;
     private List<EventDto> events;
@@ -68,8 +69,8 @@ class SearchResults {
       this.request = request;
     }
 
-    Builder setProjectUuid(String projectUuid) {
-      this.projectUuid = projectUuid;
+    Builder setProject(ComponentDto project) {
+      this.project = project;
       return this;
     }
 
@@ -100,8 +101,8 @@ class SearchResults {
       return request;
     }
 
-    String getProjectUuid() {
-      return projectUuid;
+    ComponentDto getProject() {
+      return project;
     }
 
     List<SnapshotDto> getAnalyses() {
index bc49aa366364226e778d41997e5d800c137885a0..6fbf10865dd97bd1f214cb2a29e709d7fc4bc0b6 100644 (file)
@@ -106,7 +106,7 @@ public class CreateAction implements ProjectLinksWsAction {
     try {
       ComponentDto component = getComponentByUuidOrKey(dbSession, createWsRequest);
 
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid());
+      userSession.checkComponentPermission(UserRole.ADMIN, component);
 
       ComponentLinkDto link = new ComponentLinkDto()
         .setComponentUuid(component.uuid())
index 4e99ea40af0d028518092fee503c4c82ceba9244..2d604e41001edfee69424aa960fa6b006da5370b 100644 (file)
@@ -46,7 +46,7 @@ public class QProfileProjectOperations {
   }
 
   public void addProject(DbSession dbSession, String profileKey, ComponentDto project) {
-    checkAdminOnProject(project.key());
+    checkAdminOnProject(project);
     QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey);
 
     QualityProfileDto currentProfile = db.qualityProfileDao().selectByProjectAndLanguage(dbSession, project.key(), qualityProfile.getLanguage());
@@ -65,7 +65,7 @@ public class QProfileProjectOperations {
   }
 
   public void removeProject(DbSession dbSession, String profileKey, ComponentDto project) {
-    checkAdminOnProject(project.key());
+    checkAdminOnProject(project);
     QualityProfileDto qualityProfile = selectProfileByKey(dbSession, profileKey);
 
     db.qualityProfileDao().deleteProjectProfileAssociation(project.uuid(), qualityProfile.getKey(), dbSession);
@@ -77,8 +77,9 @@ public class QProfileProjectOperations {
     return WsUtils.checkFound(qualityProfile, "Quality profile does not exist");
   }
 
-  private void checkAdminOnProject(String projectKey) {
-    if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && !userSession.hasComponentPermission(UserRole.ADMIN, projectKey)) {
+  private void checkAdminOnProject(ComponentDto project) {
+    if (!userSession.hasPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) &&
+      !userSession.hasComponentPermission(UserRole.ADMIN, project)) {
       throw new ForbiddenException("Insufficient privileges");
     }
   }
index 64c579df94b1a41c81eea4af257edec5cbb77a7d..5828bf7f105280139c498bd03d728c503aa4bce8 100644 (file)
@@ -115,7 +115,7 @@ public class ListDefinitionsAction implements SettingsWsAction {
         return Optional.empty();
       }
       ComponentDto component = componentFinder.getByKey(dbSession, componentKey);
-      userSession.checkComponentUuidPermission(USER, component.projectUuid());
+      userSession.checkComponentPermission(USER, component);
       return Optional.of(component);
     }
   }
index d5bb53bbd4bd1833de84ae6b192bd5409946881b..10e76bb1583bfb0185215e5fb4283f98750bc6af 100644 (file)
@@ -140,7 +140,7 @@ public class ResetAction implements SettingsWsAction {
 
   private void checkPermissions(Optional<ComponentDto> component) {
     if (component.isPresent()) {
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid());
+      userSession.checkComponentPermission(UserRole.ADMIN, component.get());
     } else {
       userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);
     }
index 72c86c5a6a2f3aaad8bc36f0454a5b03e0030f6b..7ac07f678afc98994749cacfd6b16c4eca679101 100644 (file)
@@ -271,7 +271,7 @@ public class SetAction implements SettingsWsAction {
 
   private void checkPermissions(Optional<ComponentDto> component) {
     if (component.isPresent()) {
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, component.get().uuid());
+      userSession.checkComponentPermission(UserRole.ADMIN, component.get());
     } else {
       userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);
     }
index 0c5f07695afa6b550c51a1dffd7a466b41b6ebb7..175d494989d6f1b106febfc02bf6ab08c4b1184a 100644 (file)
@@ -143,7 +143,7 @@ public class ValuesAction implements SettingsWsAction {
       return Optional.empty();
     }
     ComponentDto component = componentFinder.getByKey(dbSession, componentKey);
-    userSession.checkComponentUuidPermission(USER, component.projectUuid());
+    userSession.checkComponentPermission(USER, component);
     return Optional.of(component);
   }
 
index d68548fe9fb862b86c533accc53db8a5c5aa7278..4067064ffcf7eed72b512db3041070c3c562ad66 100644 (file)
@@ -68,25 +68,19 @@ public class HashAction implements SourcesWsAction {
 
   @Override
   public void handle(Request request, Response response) throws Exception {
-    DbSession session = dbClient.openSession(false);
-    try {
-      final String componentKey = request.mandatoryParam("key");
-      final ComponentDto component = componentFinder.getByKey(session, componentKey);
-      userSession.checkComponentUuidPermission(UserRole.USER, component.projectUuid());
+    try (DbSession session = dbClient.openSession(false)) {
+      String componentKey = request.mandatoryParam("key");
+      ComponentDto component = componentFinder.getByKey(session, componentKey);
+      userSession.checkComponentPermission(UserRole.USER, component);
 
       response.stream().setMediaType("text/plain");
-      OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8);
-      try {
+      try (OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8)) {
         HashFunction hashFunction = new HashFunction(writer, componentKey);
         dbClient.fileSourceDao().readLineHashesStream(session, component.uuid(), hashFunction);
         if (!hashFunction.hasData()) {
           response.noContent();
         }
-      } finally {
-        writer.close();
       }
-    } finally {
-      session.close();
     }
   }
 
index 3cce651eb11ce72a6038c4e64b857458d8c7aacf..3a1140f65ca8083a6c0b81e8e0fd209c15ca21f0 100644 (file)
@@ -75,12 +75,12 @@ public class IndexAction implements SourcesWsAction {
   @Override
   public void handle(Request request, Response response) {
     String fileKey = request.mandatoryParam("resource");
-    userSession.checkComponentPermission(UserRole.CODEVIEWER, fileKey);
     int from = request.mandatoryParamAsInt("from");
     Integer to = request.paramAsInt("to");
     try (DbSession session = dbClient.openSession(false)) {
-      ComponentDto componentDto = componentFinder.getByKey(session, fileKey);
-      Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(session, componentDto.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1);
+      ComponentDto component = componentFinder.getByKey(session, fileKey);
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, component);
+      Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(session, component.uuid(), from, to == null ? Integer.MAX_VALUE : to - 1);
       JsonWriter json = response.newJsonWriter().beginArray().beginObject();
       if (lines.isPresent()) {
         int lineCounter = from;
index 0d24edaa0f963a59c42b371ef3d08d590b65b23f..fc9fa8590951471d7395dcfaf9c359e458dc17fe 100644 (file)
@@ -115,7 +115,7 @@ public class LinesAction implements SourcesWsAction {
     DbSession dbSession = dbClient.openSession(false);
     try {
       ComponentDto file = componentFinder.getByUuidOrKey(dbSession, request.param(PARAM_UUID), request.param(PARAM_KEY), UUID_AND_KEY);
-      userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid());
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
 
       int from = request.mandatoryParamAsInt(PARAM_FROM);
       int to = MoreObjects.firstNonNull(request.paramAsInt(PARAM_TO), Integer.MAX_VALUE);
index 5ac187b899922d9d9f2465a7ef621e0a198fa1cc..97b65e84f4b0d1605126cd098937428a28feaeb0 100644 (file)
@@ -67,10 +67,10 @@ public class RawAction implements SourcesWsAction {
   @Override
   public void handle(Request request, Response response) {
     String fileKey = request.mandatoryParam("key");
-    DbSession dbSession = dbClient.openSession(false);
-    try {
+
+    try (DbSession dbSession = dbClient.openSession(false)) {
       ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
-      userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid());
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
 
       Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(dbSession, file.uuid(), 1, Integer.MAX_VALUE);
       response.stream().setMediaType("text/plain");
@@ -83,8 +83,6 @@ public class RawAction implements SourcesWsAction {
       }
     } catch (IOException e) {
       throw new IllegalStateException("Fail to write raw source of file " + fileKey, e);
-    } finally {
-      dbClient.closeSession(dbSession);
     }
   }
 }
index 22b9d6d9db65b3d503170e3a53b61c9bc5c3b258..e857f2e585777b18d8131cab0450c599fd80a357 100644 (file)
@@ -104,7 +104,7 @@ public class ScmAction implements SourcesWsAction {
     DbSession dbSession = dbClient.openSession(false);
     try {
       ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
-      userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid());
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
       Optional<Iterable<DbFileSources.Line>> sourceLines = sourceService.getLines(dbSession, file.uuid(), from, to);
       if (!sourceLines.isPresent()) {
         throw new NotFoundException(String.format("File '%s' has no sources", fileKey));
index 9f76747a8b7c6f3f1148d4b43322807e32b97680..56ba7b260b11a74d43c0b3007de4932b17d82614 100644 (file)
@@ -89,7 +89,7 @@ public class ShowAction implements SourcesWsAction {
     DbSession dbSession = dbClient.openSession(false);
     try {
       ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
-      userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, file.projectUuid());
+      userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
 
       Optional<Iterable<String>> linesHtml = sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to);
       if (linesHtml.isPresent()) {
index a9f1251e82df80d9ee64a5f8a7b38eac88f9c304..5c824be26517f258176cbaa2b031bfce90fb6403 100644 (file)
@@ -228,7 +228,7 @@ public class ListAction implements TestsWsAction {
 
   private SearchResult<TestDoc> searchTestsByTestFileKey(DbSession dbSession, String testFileKey, SearchOptions searchOptions) {
     ComponentDto testFile = componentFinder.getByKey(dbSession, testFileKey);
-    userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, testFile.projectUuid());
+    userSession.checkComponentPermission(UserRole.CODEVIEWER, testFile);
     return testIndex.searchByTestFileUuid(testFile.uuid(), searchOptions);
   }
 
@@ -245,7 +245,7 @@ public class ListAction implements TestsWsAction {
 
   private void checkComponentUuidPermission(DbSession dbSession, String componentUuid) {
     ComponentDto component = componentFinder.getByUuid(dbSession, componentUuid);
-    userSession.checkComponentUuidPermission(UserRole.CODEVIEWER, component.projectUuid());
+    userSession.checkComponentPermission(UserRole.CODEVIEWER, component);
   }
 
   private static class TestToFileUuidFunction implements Function<TestDoc, String> {
index 680a2e186f2c64857ece8b1a4521380b16479fc5..6ea749b11600188e440522b645e90e28a6ea4526 100644 (file)
@@ -126,7 +126,7 @@ public class WebhookDeliveriesAction implements WebhooksWsAction {
 
     void ensureAdminPermission(UserSession userSession) {
       if (component != null) {
-        userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid());
+        userSession.checkComponentPermission(UserRole.ADMIN, component);
       }
     }
 
index cec10909c9570199aef176981e649140bb9969e5..af891c9b51e05d96438b07ea515d385046540b5f 100644 (file)
@@ -98,7 +98,7 @@ public class WebhookDeliveryAction implements WebhooksWsAction {
     }
 
     void ensureAdminPermission(UserSession userSession) {
-      userSession.checkComponentUuidPermission(UserRole.ADMIN, component.uuid());
+      userSession.checkComponentPermission(UserRole.ADMIN, component);
     }
 
     void writeTo(Request request, Response response) {
index 4672e4273f7c9e01f6b75cb193e75a1792a315ad..6c21339b8abca855eb0f124035766c7e4eb28f6c 100644 (file)
@@ -23,7 +23,6 @@ import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.db.DbClient;
-import org.sonar.db.measure.MeasureDao;
 import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.tester.UserSessionRule;
 import org.sonar.server.ws.WsTester;
@@ -36,7 +35,7 @@ public class DuplicationsWsTest {
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
   WsTester tester = new WsTester(new DuplicationsWs(
-    new ShowAction(mock(DbClient.class), mock(MeasureDao.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule,
+    new ShowAction(mock(DbClient.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class), userSessionRule,
       mock(ComponentFinder.class))));
 
   @Test
index 8e11b903df537b2b18f73fa4811bf24887c5e864..a89f499fea97c88bde0db1239ea5d14f01a8f793 100644 (file)
  */
 package org.sonar.server.duplication.ws;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.util.List;
+import java.util.function.Function;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.sonar.api.utils.text.JsonWriter;
+import org.junit.rules.ExpectedException;
+import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.web.UserRole;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.component.ComponentDao;
+import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.measure.MeasureDao;
-import org.sonar.db.measure.MeasureDto;
-import org.sonar.db.measure.MeasureQuery;
+import org.sonar.db.component.SnapshotDto;
+import org.sonar.db.metric.MetricDto;
 import org.sonar.server.component.ComponentFinder;
+import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.startup.RegisterMetrics;
 import org.sonar.server.tester.UserSessionRule;
 import org.sonar.server.ws.WsTester;
 
-import static com.google.common.collect.Lists.newArrayList;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
+import static org.sonar.db.component.ComponentTesting.newFileDto;
+import static org.sonar.db.component.SnapshotTesting.newAnalysis;
+import static org.sonar.db.measure.MeasureTesting.newMeasureDto;
 
-@RunWith(MockitoJUnitRunner.class)
 public class ShowActionTest {
 
   @Rule
-  public UserSessionRule userSessionRule = UserSessionRule.standalone();
-
-  @Mock
-  DbSession session;
-
-  @Mock
-  DbClient dbClient;
+  public ExpectedException expectedException = ExpectedException.none();
 
-  @Mock
-  ComponentDao componentDao;
-
-  @Mock
-  MeasureDao measureDao;
-
-  @Mock
-  DuplicationsParser parser;
+  @Rule
+  public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
-  @Mock
-  DuplicationsJsonWriter duplicationsJsonWriter;
+  @Rule
+  public DbTester db = DbTester.create();
 
-  WsTester tester;
+  private DuplicationsParser parser = new DuplicationsParser(db.getDbClient().componentDao());
+  private DuplicationsJsonWriter duplicationsJsonWriter = new DuplicationsJsonWriter(db.getDbClient().componentDao());
+  private WsTester tester;
+  private MetricDto dataMetric = RegisterMetrics.MetricToDto.INSTANCE.apply(CoreMetrics.DUPLICATIONS_DATA);
 
   @Before
   public void setUp() {
-    when(dbClient.openSession(false)).thenReturn(session);
-    when(dbClient.componentDao()).thenReturn(componentDao);
-    tester = new WsTester(new DuplicationsWs(new ShowAction(dbClient, measureDao, parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(dbClient))));
+    tester = new WsTester(new DuplicationsWs(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, new ComponentFinder(db.getDbClient()))));
+
+    db.getDbClient().metricDao().insert(db.getSession(), dataMetric);
+    db.commit();
   }
 
   @Test
-  public void show_duplications() throws Exception {
-    String componentKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey);
-
-    ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey);
-    when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto));
-
-    String data = "{duplications}";
-    when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn(
-      java.util.Optional.of(new MeasureDto().setData("{duplications}"))
-    );
-
-    List<DuplicationsParser.Block> blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2))));
-    when(parser.parse(componentDto, data, session)).thenReturn(blocks);
-
-    WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey);
-    request.execute();
-
-    verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session));
+  public void get_duplications_by_file_key() throws Exception {
+    WsTester.TestRequest request = newBaseRequest();
+    verifyCallToFileWithDuplications(file -> request.setParam("key", file.key()));
   }
 
   @Test
-  public void show_duplications_by_uuid() throws Exception {
-    String uuid = "ABCD";
-    String componentKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey);
-
-    ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey);
-    when(componentDao.selectByUuid(session, uuid)).thenReturn(Optional.of(componentDto));
+  public void get_duplications_by_file_id() throws Exception {
+    WsTester.TestRequest request = newBaseRequest();
+    verifyCallToFileWithDuplications(file -> request.setParam("uuid", file.uuid()));
+  }
 
-    String data = "{duplications}";
-    when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn(
-      java.util.Optional.of(new MeasureDto().setData("{duplications}"))
-    );
+  @Test
+  public void return_file_with_missing_duplication_data() throws Exception {
+    ComponentDto project = db.components().insertProject();
+    ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js"));
+    db.components().insertSnapshot(newAnalysis(project));
 
-    List<DuplicationsParser.Block> blocks = newArrayList(new DuplicationsParser.Block(newArrayList(new DuplicationsParser.Duplication(componentDto, 1, 2))));
-    when(parser.parse(componentDto, data, session)).thenReturn(blocks);
+    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
 
-    WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("uuid", uuid);
-    request.execute();
+    WsTester.Result result = newBaseRequest().setParam("key", file.key()).execute();
 
-    verify(duplicationsJsonWriter).write(eq(blocks), any(JsonWriter.class), eq(session));
+    result.assertJson("{\n" +
+      "  \"duplications\": [],\n" +
+      "  \"files\": {}\n" +
+      "}");
   }
 
   @Test
-  public void no_duplications_when_no_data() throws Exception {
-    String componentKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "org.codehaus.sonar:sonar", componentKey);
+  public void return_404_if_file_does_not_exist() throws Exception {
+    expectedException.expect(NotFoundException.class);
 
-    ComponentDto componentDto = new ComponentDto().setId(10L).setKey(componentKey);
-    when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.of(componentDto));
+    newBaseRequest().setParam("key", "missing").execute();
+  }
 
-    when(measureDao.selectSingle(eq(session), any(MeasureQuery.class))).thenReturn(java.util.Optional.empty());
+  @Test
+  public void return_403_if_user_is_not_allowed_to_access_project() throws Exception {
+    ComponentDto project = db.components().insertProject();
+    ComponentDto file = db.components().insertComponent(newFileDto(project));
 
-    WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey);
-    request.execute();
+    expectedException.expect(ForbiddenException.class);
 
-    verify(duplicationsJsonWriter).write(eq(Lists.newArrayList()), any(JsonWriter.class), eq(session));
+    newBaseRequest().setParam("key", file.key()).execute();
   }
 
-  @Test(expected = NotFoundException.class)
-  public void fail_when_file_not_found() throws Exception {
-    String componentKey = "src/Foo.java";
-
-    when(componentDao.selectByKey(session, componentKey)).thenReturn(Optional.absent());
-
-    WsTester.TestRequest request = tester.newGetRequest("api/duplications", "show").setParam("key", componentKey);
-    request.execute();
+  private WsTester.TestRequest newBaseRequest() {
+    return tester.newGetRequest("api/duplications", "show");
   }
 
+  private void verifyCallToFileWithDuplications(Function<ComponentDto, WsTester.TestRequest> requestFactory) throws Exception {
+    ComponentDto project = db.components().insertProject();
+    ComponentDto file = db.components().insertComponent(newFileDto(project).setKey("foo.js"));
+    SnapshotDto snapshot = db.components().insertSnapshot(newAnalysis(project));
+    String xml = "<duplications>\n" +
+      "  <g>\n" +
+      "    <b s=\"31\" l=\"5\" r=\"foo.js\"/>\n" +
+      "    <b s=\"20\" l=\"5\" r=\"foo.js\"/>\n" +
+      "  </g>\n" +
+      "</duplications>\n";
+    db.getDbClient().measureDao().insert(db.getSession(), newMeasureDto(dataMetric, file, snapshot).setData(xml));
+    db.commit();
+
+    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
+
+    WsTester.TestRequest request = requestFactory.apply(file);
+    WsTester.Result result = request.execute();
+
+    result.assertJson("{\"duplications\":[" +
+      "{\"blocks\":[{\"from\":20,\"size\":5,\"_ref\":\"1\"},{\"from\":31,\"size\":5,\"_ref\":\"1\"}]}]," +
+      "\"files\":{\"1\":{\"key\":\"foo.js\",\"uuid\":\"" + file.uuid() + "\"}}}");
+  }
 }
index c8fcd53f8a682defe4dd12ccbd882b0adcaa582b..36ac14209990d8ed2c070c680910cb9acf6cd7e9 100644 (file)
@@ -33,6 +33,7 @@ import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentLinkDto;
+import org.sonar.db.component.ComponentTesting;
 import org.sonar.db.organization.OrganizationDto;
 import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.exceptions.ForbiddenException;
@@ -65,12 +66,12 @@ public class CreateActionTest {
 
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
-  DbClient dbClient = db.getDbClient();
-  DbSession dbSession = db.getSession();
+  private DbClient dbClient = db.getDbClient();
+  private DbSession dbSession = db.getSession();
 
-  WsActionTester ws;
+  private WsActionTester ws;
 
-  CreateAction underTest;
+  private CreateAction underTest;
 
   @Before
   public void setUp() {
@@ -83,11 +84,11 @@ public class CreateActionTest {
 
   @Test
   public void example_with_key() {
-    insertProject();
+    ComponentDto project = insertProject();
 
     String result = ws.newRequest()
       .setMethod("POST")
-      .setParam(PARAM_PROJECT_KEY, PROJECT_KEY)
+      .setParam(PARAM_PROJECT_KEY, project.key())
       .setParam(PARAM_NAME, "Custom")
       .setParam(PARAM_URL, "http://example.org")
       .execute().getInput();
@@ -97,11 +98,11 @@ public class CreateActionTest {
 
   @Test
   public void example_with_id() {
-    insertProject();
+    ComponentDto project = insertProject();
 
     String result = ws.newRequest()
       .setMethod("POST")
-      .setParam(PARAM_PROJECT_ID, PROJECT_UUID)
+      .setParam(PARAM_PROJECT_ID, project.uuid())
       .setParam(PARAM_NAME, "Custom")
       .setParam(PARAM_URL, "http://example.org")
       .execute().getInput();
@@ -111,26 +112,26 @@ public class CreateActionTest {
 
   @Test
   public void global_admin() throws IOException {
-    userSession.login("login").setGlobalPermissions(SYSTEM_ADMIN);
-    insertProject();
-    createAndTest();
+    userSession.login().setGlobalPermissions(SYSTEM_ADMIN);
+    ComponentDto project = insertProject();
+    createAndTest(project);
   }
 
   @Test
-  public void project_admin() throws IOException {
-    userSession.login("login");
+  public void require_project_admin() throws IOException {
+    userSession.login();
     ComponentDto project = insertProject();
     userSession.addProjectUuidPermissions(UserRole.ADMIN, project.uuid());
-    createAndTest();
+    createAndTest(project);
   }
 
   @Test
   public void with_long_name() throws IOException {
-    insertProject();
+    ComponentDto project = insertProject();
 
     String longName = StringUtils.leftPad("", 60, "a");
     String expectedType = StringUtils.leftPad("", 20, "a");
-    createAndTest(longName, "http://example.org", expectedType);
+    createAndTest(project, longName, "http://example.org", expectedType);
   }
 
   @Test
@@ -196,7 +197,7 @@ public class CreateActionTest {
 
   @Test
   public void fail_if_not_project_admin() {
-    userSession.login("login");
+    userSession.login();
     insertProject();
 
     expectedException.expect(ForbiddenException.class);
@@ -208,17 +209,15 @@ public class CreateActionTest {
   }
 
   private ComponentDto insertProject() {
-    OrganizationDto organizationDto = db.organizations().insert();
-    return db.components().insertProject(
-      organizationDto,
-      (t) -> t.setUuid(PROJECT_UUID)
-        .setKey(PROJECT_KEY));
+    OrganizationDto org = db.organizations().insert();
+    return db.components().insertComponent(
+      ComponentTesting.newProjectDto(org, PROJECT_UUID).setKey(PROJECT_KEY));
   }
 
-  private void createAndTest(String name, String url, String type) throws IOException {
+  private void createAndTest(ComponentDto project, String name, String url, String type) throws IOException {
     InputStream responseStream = ws.newRequest()
       .setMethod("POST")
-      .setParam(PARAM_PROJECT_KEY, PROJECT_KEY)
+      .setParam(PARAM_PROJECT_KEY, project.key())
       .setParam(PARAM_NAME, name)
       .setParam(PARAM_URL, url)
       .setMediaType(PROTOBUF)
@@ -234,7 +233,7 @@ public class CreateActionTest {
     assertThat(link.getType()).isEqualTo(type);
   }
 
-  private void createAndTest() throws IOException {
-    createAndTest("Custom", "http://example.org", "custom");
+  private void createAndTest(ComponentDto project) throws IOException {
+    createAndTest(project, "Custom", "http://example.org", "custom");
   }
 }
index 979faeb0ec1be7d5febef22488bbca7dac6f3d8a..e9e74fee090ce567f4e5b7861228dbd692d061b7 100644 (file)
@@ -77,7 +77,7 @@ public class IndexActionTest {
   @Test
   public void get_json() throws Exception {
     String fileKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey);
+    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
     when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
 
     when(sourceService.getLinesAsRawText(session, file.uuid(), 1, Integer.MAX_VALUE)).thenReturn(Optional.of((Iterable<String>) newArrayList(
@@ -91,7 +91,7 @@ public class IndexActionTest {
   @Test
   public void limit_range() throws Exception {
     String fileKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey);
+    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
     when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
 
     when(sourceService.getLinesAsRawText(session, file.uuid(), 1, 2)).thenReturn(Optional.of((Iterable<String>) newArrayList(
@@ -105,13 +105,14 @@ public class IndexActionTest {
 
   @Test(expected = ForbiddenException.class)
   public void requires_code_viewer_permission() throws Exception {
-    tester.newGetRequest("api/sources", "index").setParam("resource", "any").execute();
+    when(componentDao.selectByKey(session, "foo")).thenReturn(Optional.of(file));
+    tester.newGetRequest("api/sources", "index").setParam("resource", "foo").execute();
   }
 
   @Test
   public void close_db_session() throws Exception {
     String fileKey = "src/Foo.java";
-    userSessionRule.addComponentPermission(UserRole.CODEVIEWER, "polop", fileKey);
+    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
     when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.<ComponentDto>absent());
 
     WsTester.TestRequest request = tester.newGetRequest("api/sources", "index").setParam("resource", fileKey);
index d2ebacdd2b05e75cbd8b77d1a6f15007b13b6144..2941eabb8fc4a360d740fa4ec079d92aed9e9b21 100644 (file)
@@ -258,7 +258,7 @@ public class UserSessionRule implements TestRule, UserSession {
 
   @Override
   public boolean hasComponentPermission(String permission, ComponentDto component) {
-    return hasComponentUuidPermission(permission, component.projectUuid());
+    return currentUserSession.hasComponentPermission(permission, component);
   }
 
   @Override