]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-19558 Refactor 'issues', 'issue_changes', Components and view indexes
authorDuarte Meneses <duarte.meneses@sonarsource.com>
Fri, 16 Jun 2023 19:48:59 +0000 (14:48 -0500)
committersonartech <sonartech@sonarsource.com>
Thu, 29 Jun 2023 20:05:14 +0000 (20:05 +0000)
113 files changed:
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/IndexAnalysisStep.java
server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java
server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java
server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java
server/sonar-db-dao/src/it/java/org/sonar/db/entity/EntityDaoIT.java
server/sonar-db-dao/src/it/java/org/sonar/db/measure/ProjectMeasuresIndexerIteratorIT.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/BranchDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/BranchMapper.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentKeyUpdaterDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotMapper.java
server/sonar-db-dao/src/main/java/org/sonar/db/component/UuidWithBranchUuidDto.java
server/sonar-db-dao/src/main/java/org/sonar/db/entity/EntityDao.java
server/sonar-db-dao/src/main/java/org/sonar/db/entity/EntityMapper.java
server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java
server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java
server/sonar-db-dao/src/main/java/org/sonar/db/measure/ProjectMeasuresIndexerIterator.java
server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectDao.java
server/sonar-db-dao/src/main/resources/org/sonar/db/component/BranchMapper.xml
server/sonar-db-dao/src/main/resources/org/sonar/db/component/SnapshotMapper.xml
server/sonar-db-dao/src/main/resources/org/sonar/db/entity/EntityMapper.xml
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java
server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java
server/sonar-server-common/src/it/java/org/sonar/server/view/index/ViewIndexIT.java
server/sonar-server-common/src/it/java/org/sonar/server/view/index/ViewIndexerIT.java
server/sonar-server-common/src/main/java/org/sonar/server/component/index/ComponentIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/es/ProjectIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/es/ProjectIndexers.java
server/sonar-server-common/src/main/java/org/sonar/server/es/ResilientIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/SearchRequest.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/permission/index/AuthorizationDoc.java
server/sonar-server-common/src/main/java/org/sonar/server/permission/index/IndexPermissions.java
server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewDoc.java
server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndex.java
server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndexer.java
server/sonar-server-common/src/test/java/org/sonar/server/issue/SearchRequestTest.java
server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java
server/sonar-webserver-es/src/it/java/org/sonar/server/permission/index/PermissionIndexerDaoIT.java
server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQuery.java
server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQueryFactory.java
server/sonar-webserver-es/src/main/java/org/sonar/server/permission/index/PermissionIndexer.java
server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.java
server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.java
server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java
server/sonar-webserver-es/src/testFixtures/java/org/sonar/server/permission/index/PermissionIndexerTester.java
server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/issues/IssueChangeEventServiceImplTest.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/authentication/ws/LoginActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/branch/ws/ListActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ComponentCleanerServiceIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ComponentServiceUpdateKeyIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ComponentUpdaterIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SearchProjectsActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SuggestionsActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AddCommentActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ChangeStatusActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/DeleteCommentActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/EditCommentActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/PullActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueChangeWSSupportIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueFinderIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/WebIssueStorageIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/AddCommentActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/AssignActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/AuthorsActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/ChangelogActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/DoTransitionActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullTaintActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionFacetsIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SetTagsActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/TagsActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/metric/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/CreateActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/DeleteActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/GetByProjectActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.java
server/sonar-webserver-webapi/src/it/java/org/sonar/server/scannercache/ws/ClearActionIT.java
server/sonar-webserver-webapi/src/it/resources/org/sonar/server/source/ws/IssueSnippetsActionIT/issue_snippets_close_to_each_other.json
server/sonar-webserver-webapi/src/it/resources/org/sonar/server/source/ws/IssueSnippetsActionIT/issue_snippets_multiple_locations.json
server/sonar-webserver-webapi/src/it/resources/org/sonar/server/source/ws/IssueSnippetsActionIT/issue_snippets_single_location.json
server/sonar-webserver-webapi/src/it/resources/org/sonar/server/source/ws/IssueSnippetsActionIT/issue_snippets_with_measures.json
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentService.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/AppAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentViewerJsonWriter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotWsResponseFormatter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotWsSupport.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/ShowAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AuthorsAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/BulkChangeAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/IssueUpdater.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/OperationResponseWriter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/TagsAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/SearchAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/IssueSnippetsAction.java
server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java

index 6874fc40ffbb4eac4d7bfc4457f93e3ddff74aa1..fc47c64a7391007e37156eff5f0b864bde1a97b4 100644 (file)
@@ -39,7 +39,7 @@ public class IndexAnalysisStep implements ComputationStep {
   private final ProjectIndexer[] indexers;
   private final DbClient dbClient;
 
-  public IndexAnalysisStep(TreeRootHolder treeRootHolder, FileStatuses fileStatuses, DbClient dbClient,ProjectIndexer... indexers) {
+  public IndexAnalysisStep(TreeRootHolder treeRootHolder, FileStatuses fileStatuses, DbClient dbClient, ProjectIndexer... indexers) {
     this.treeRootHolder = treeRootHolder;
     this.fileStatuses = fileStatuses;
     this.indexers = indexers;
index b9b9934f3cf32f12d83cb27095db65be4b926d59..688190bac7bb95e9c8f0a8c79f00b0eb81e5e8f2 100644 (file)
@@ -879,11 +879,11 @@ public class ComponentDaoIT {
     db.components().insertComponent(newProjectCopy(project1, subView));
     ComponentDto viewWithoutProject = db.components().insertPrivatePortfolio();
 
-    assertThat(underTest.selectProjectsFromView(dbSession, view.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid());
-    assertThat(underTest.selectProjectsFromView(dbSession, viewWithSubView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
-    assertThat(underTest.selectProjectsFromView(dbSession, subView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid());
-    assertThat(underTest.selectProjectsFromView(dbSession, viewWithoutProject.uuid(), viewWithoutProject.uuid())).isEmpty();
-    assertThat(underTest.selectProjectsFromView(dbSession, "Unknown", "Unknown")).isEmpty();
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, view.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid());
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, viewWithSubView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid());
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, viewWithoutProject.uuid(), viewWithoutProject.uuid())).isEmpty();
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, "Unknown", "Unknown")).isEmpty();
   }
 
   @Test
@@ -915,8 +915,8 @@ public class ComponentDaoIT {
     ComponentDto subView2 = db.components().insertComponent(newSubPortfolio(view, "ABC", "ABC-key"));
     db.components().insertComponent(newProjectCopy(project3, subView2));
 
-    assertThat(underTest.selectProjectsFromView(dbSession, subView1.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
-    assertThat(underTest.selectProjectsFromView(dbSession, subView2.uuid(), view.uuid())).containsExactlyInAnyOrder(project3.uuid());
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView1.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
+    assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView2.uuid(), view.uuid())).containsExactlyInAnyOrder(project3.uuid());
   }
 
   @Test
index 13d60db267f8c79c26e69600505fd5321f7a1a7c..e81aa17ef533e92bb57d8d9e90fe12d72ed5048e 100644 (file)
@@ -59,7 +59,7 @@ public class ComponentKeyUpdaterDaoIT {
   public void updateKey_changes_the_key_of_tree_of_components() {
     populateSomeData();
 
-    underTest.updateKey(dbSession, "A", "struts:core");
+    underTest.updateKey(dbSession, "A", "org.struts:struts", "struts:core");
     dbSession.commit();
 
     assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from components"))
@@ -73,9 +73,7 @@ public class ComponentKeyUpdaterDaoIT {
 
   @Test
   public void updateKey_updates_disabled_components() {
-    ComponentDto project = db.components().insertComponent(
-      newPrivateProjectDto("A")
-        .setKey("my_project"));
+    ComponentDto project = db.components().insertPrivateProject("A", p -> p.setKey("my_project")).getMainBranchComponent();
     ComponentDto directory = db.components().insertComponent(
       newDirectory(project, "B")
         .setKey("my_project:directory"));
@@ -83,7 +81,7 @@ public class ComponentKeyUpdaterDaoIT {
     ComponentDto inactiveDirectory = db.components().insertComponent(newDirectory(project, "/inactive_directory").setKey("my_project:inactive_directory").setEnabled(false));
     db.components().insertComponent(newFileDto(project, inactiveDirectory).setKey("my_project:inactive_directory/file").setEnabled(false));
 
-    underTest.updateKey(dbSession, "A", "your_project");
+    underTest.updateKey(dbSession, "A", "my_project", "your_project");
     dbSession.commit();
 
     List<ComponentDto> result = dbClient.componentDao().selectByBranchUuid("A", dbSession);
@@ -107,7 +105,7 @@ public class ComponentKeyUpdaterDaoIT {
     assertThat(dbClient.componentDao().selectByBranchUuid(branch.uuid(), dbSession)).hasSize(prComponentCount);
 
     String newProjectKey = "newKey";
-    underTest.updateKey(dbSession, project.uuid(), newProjectKey);
+    underTest.updateKey(dbSession, project.uuid(), project.getKey(), newProjectKey);
 
     assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
     assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
@@ -133,7 +131,7 @@ public class ComponentKeyUpdaterDaoIT {
     assertThat(dbClient.componentDao().selectByBranchUuid(pullRequest.uuid(), dbSession)).hasSize(prComponentCount);
 
     String newProjectKey = "newKey";
-    underTest.updateKey(dbSession, project.uuid(), newProjectKey);
+    underTest.updateKey(dbSession, project.uuid(), project.getKey(), newProjectKey);
 
     assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
     assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
@@ -150,19 +148,18 @@ public class ComponentKeyUpdaterDaoIT {
   public void updateKey_throws_IAE_if_component_with_specified_key_does_not_exist() {
     populateSomeData();
 
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, "A", "foo:struts-core"))
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, "A", "org.struts:struts", "foo:struts-core"))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("Impossible to update key: a component with key \"foo:struts-core\" already exists.");
   }
 
   @Test
   public void updateKey_throws_IAE_when_sub_component_key_is_too_long() {
-    ComponentDto project = newPrivateProjectDto("project-uuid").setKey("old-project-key");
-    db.components().insertComponent(project);
+    ComponentDto project = db.components().insertPrivateProject("project-uuid", p -> p.setKey("old-project-key")).getMainBranchComponent();
     db.components().insertComponent(newFileDto(project).setKey("old-project-key:file"));
     String newLongProjectKey = Strings.repeat("a", 400);
 
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, project.uuid(), newLongProjectKey))
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, project.uuid(), project.getKey(), newLongProjectKey))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("Component key length (405) is longer than the maximum authorized (400). '" + newLongProjectKey + ":file' was provided.");
   }
@@ -175,12 +172,11 @@ public class ComponentKeyUpdaterDaoIT {
 
   @Test
   public void updateKey_callsAuditPersister() {
-    db.components().insertComponent(newPrivateProjectDto("A").setKey("my_project"));
+    db.components().insertPrivateProject("A", p -> p.setKey("my_project"));
 
-    underTestWithAuditPersister.updateKey(dbSession, "A", "your_project");
+    underTestWithAuditPersister.updateKey(dbSession, "A", "my_project", "your_project");
 
-    verify(auditPersister, times(1))
-      .componentKeyUpdate(any(DbSession.class), any(ComponentKeyNewValue.class), anyString());
+    verify(auditPersister, times(1)).componentKeyUpdate(any(DbSession.class), any(ComponentKeyNewValue.class), anyString());
   }
 
   private void populateSomeData() {
index b0bf23234adb8e191ac74291a7a70f10bfc366fa..2361b2e81ed475d6046541a537fb7819b513190e 100644 (file)
@@ -163,37 +163,9 @@ public class SnapshotDaoIT {
     assertThat(result).extracting(SnapshotDto::getUuid).containsOnly(lastSnapshotOfFirstProject.getUuid(), lastSnapshotOfSecondProject.getUuid());
   }
 
-  @Test
-  public void selectLastAnalysisDateByProject_takes_all_branches_into_account() {
-    ComponentDto firstProject = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto branch1 = db.components().insertProjectBranch(firstProject);
-    ComponentDto branch2 = db.components().insertProjectBranch(firstProject);
-
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(firstProject).setLast(false).setCreatedAt(1L));
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(false).setCreatedAt(2L));
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(branch2).setLast(false).setCreatedAt(10L));
-
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(firstProject).setLast(true).setCreatedAt(7L));
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(true).setCreatedAt(8L));
-    dbClient.snapshotDao().insert(dbSession, newAnalysis(branch2).setLast(true).setCreatedAt(9L));
-
-    Optional<Long> date = underTest.selectLastAnalysisDateByProject(dbSession, firstProject.uuid());
-
-    assertThat(date).contains(9L);
-  }
-
-  @Test
-  public void selectLastAnalysisDateByProject_is_empty_if_no_snapshot() {
-    ComponentDto firstProject = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto branch1 = db.components().insertProjectBranch(firstProject);
-    ComponentDto branch2 = db.components().insertProjectBranch(firstProject);
-
-    assertThat(underTest.selectLastAnalysisDateByProject(dbSession, firstProject.uuid())).isEmpty();
-  }
-
   @Test
   public void selectLastAnalysisDateByProjects_is_empty_if_no_project_passed() {
-    assertThat(underTest.selectLastAnalysisDateByProjects(dbSession, emptyList())).isEmpty();
+    assertThat(underTest.selectLastAnalysisDateByProjectUuids(dbSession, emptyList())).isEmpty();
   }
 
   @Test
@@ -213,7 +185,7 @@ public class SnapshotDaoIT {
     dbClient.snapshotDao().insert(dbSession, newAnalysis(branch2).setLast(false).setCreatedAt(5L));
     dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(true).setCreatedAt(4L));
 
-    List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjects(dbSession,
+    List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjectUuids(dbSession,
       List.of(project1.uuid(), project2.uuid(), project3.uuid(), "non-existing"));
 
     assertThat(lastAnalysisByProject).extracting(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate)
@@ -230,7 +202,7 @@ public class SnapshotDaoIT {
     dbClient.snapshotDao().insert(dbSession, newAnalysis(portfolio).setLast(true).setCreatedAt(2L));
     dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(true).setCreatedAt(3L));
 
-    List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjects(dbSession,
+    List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjectUuids(dbSession,
       List.of(project1.uuid(), portfolio.uuid()));
 
     assertThat(lastAnalysisByProject).extracting(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate)
index 7b54d98409c6079d8a205fa627486a2ec23a0d32..3f6276ac35ca7df8c73d8bbc44cac1d8a7348ffd 100644 (file)
@@ -27,8 +27,12 @@ import org.junit.Test;
 import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
 import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
+import org.sonar.db.component.BranchDto;
+import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ComponentTesting;
 import org.sonar.db.component.ProjectData;
 import org.sonar.db.portfolio.PortfolioDto;
+import org.sonar.db.project.ProjectDto;
 
 import static java.util.Collections.emptyList;
 import static org.assertj.core.api.Assertions.assertThat;
@@ -41,6 +45,42 @@ public class EntityDaoIT {
 
   private final EntityDao entityDao = new EntityDao();
 
+  @Test
+  public void selectEntityByComponentUuid_shouldReturnProjectEntityBasedOnComponent() {
+    ProjectDto project = db.components().insertPrivateProject().getProjectDto();
+    BranchDto branchDto = db.components().insertProjectBranch(project);
+    ComponentDto fileInBranch = db.components().insertFile(branchDto);
+
+    assertThat(entityDao.selectByComponentUuid(db.getSession(), fileInBranch.uuid()).get())
+      .extracting(EntityDto::getUuid, EntityDto::getKey)
+      .containsOnly(project.getUuid(), project.getKey());
+  }
+
+  @Test
+  public void selectEntityByComponentUuid_shouldReturnPortfolioEntityBasedOnComponent() {
+    PortfolioDto portfolio = db.components().insertPublicPortfolioDto();
+    assertThat(entityDao.selectByComponentUuid(db.getSession(), portfolio.getUuid()).get())
+      .extracting(EntityDto::getUuid, EntityDto::getKey)
+      .containsOnly(portfolio.getUuid(), portfolio.getKey());
+  }
+
+  @Test
+  public void selectEntityByComponentUuid_whenPortfolioWithHierarchy_shouldReturnPortfolioEntityBasedOnComponent() {
+    ComponentDto projectBranch = db.components().insertPublicProject().getMainBranchComponent();
+    ComponentDto portfolio = db.components().insertPublicPortfolio();
+    ComponentDto subPortfolio = db.components().insertSubportfolio(portfolio);
+    ComponentDto projectCopy = db.components().insertComponent(ComponentTesting.newProjectCopy(projectBranch, subPortfolio));
+
+    assertThat(entityDao.selectByComponentUuid(db.getSession(), projectCopy.uuid()).get())
+      .extracting(EntityDto::getUuid, EntityDto::getKey)
+      .containsOnly(portfolio.uuid(), portfolio.getKey());
+  }
+
+  @Test
+  public void selectEntityByComponentUuid_whenUnknown_shouldReturnEmpty() {
+    assertThat(entityDao.selectByComponentUuid(db.getSession(), "unknown")).isEmpty();
+  }
+
   @Test
   public void selectEntitiesByKeys_shouldReturnAllEntities() {
     ProjectData application = db.components().insertPrivateApplication();
index a55affffc5099ccf8c272c1ee5db4899f3f2c03f..f8105bd490dde7b64cd034e7e831725821e79835 100644 (file)
@@ -165,17 +165,6 @@ public class ProjectMeasuresIndexerIteratorIT {
       .containsOnly(entry("<null>", 4), entry("java", 12), entry("xoo", 36));
   }
 
-  @Test
-  public void return_language_distribution_measure_from_project_with_no_branches() {
-    ComponentDto project = insertComponentAndProject(ComponentTesting.newPublicProjectDto(), false,
-      defaults(), defaults());
-
-    Map<String, ProjectMeasures> docsById = createResultSetAndReturnDocsById();
-
-    assertThat(docsById.get(project.uuid()).getMeasures().getNclocByLanguages())
-      .isEmpty();
-  }
-
   @Test
   public void does_not_return_none_numeric_metrics() {
     ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
@@ -309,18 +298,4 @@ public class ProjectMeasuresIndexerIteratorIT {
     it.close();
     return docsById;
   }
-
-  private ComponentDto insertComponentAndProject(ComponentDto component, @Nullable Boolean isPrivate,
-    Consumer<ComponentDto> componentDtoPopulator, Consumer<ProjectDto> projectDtoPopulator) {
-    componentDtoPopulator.accept(component);
-    checkState(isPrivate == null || component.isPrivate() == isPrivate, "Illegal modification of private flag");
-    dbClient.componentDao().insert(dbSession, component, true);
-
-    ProjectDto projectDto = toProjectDto(component, System2.INSTANCE.now());
-    projectDtoPopulator.accept(projectDto);
-    dbClient.projectDao().insert(dbSession, projectDto);
-
-    dbTester.commit();
-    return component;
-  }
 }
index d1792b273b9909311934e4f397ba8158a8a07dc9..6430ec203c135bcbac281f6f0586f136e5a55642 100644 (file)
@@ -77,6 +77,13 @@ public class BranchDao implements Dao {
     return mapper(dbSession).selectByBranchKeys(branchKeyByProjectUuid);
   }
 
+  public List<BranchDto> selectByPullRequestKeys(DbSession dbSession, Map<String, String> prKeyByProjectUuid) {
+    if (prKeyByProjectUuid.isEmpty()) {
+      return emptyList();
+    }
+    return mapper(dbSession).selectByPullRequestKeys(prKeyByProjectUuid);
+  }
+
   public Optional<BranchDto> selectByPullRequestKey(DbSession dbSession, String projectUuid, String key) {
     return selectByKey(dbSession, projectUuid, key, BranchType.PULL_REQUEST);
   }
@@ -115,7 +122,7 @@ public class BranchDao implements Dao {
     return mapper(dbSession).selectMainBranchByProjectUuid(projectUuid);
   }
 
-  public List<BranchDto> selectMainBranchesByProjectUuids(DbSession dbSession, Set<String> projectUuids) {
+  public List<BranchDto> selectMainBranchesByProjectUuids(DbSession dbSession, Collection<String> projectUuids) {
     if (projectUuids.isEmpty()) {
       return List.of();
     }
index 4aa4b32281facdd8f85768ada6ccdaef6cdb2733..4e252fe19d4886f4db2df8fc2de1a46b65b89890 100644 (file)
@@ -48,6 +48,8 @@ public interface BranchMapper {
 
   List<BranchDto> selectByBranchKeys(@Param("branchKeyByProjectUuid") Map<String, String> branchKeyByProjectUuid);
 
+  List<BranchDto> selectByPullRequestKeys(@Param("prKeyByProjectUuid") Map<String, String> prKeyByProjectUuid);
+
   List<BranchDto> selectByUuids(@Param("uuids") Collection<String> uuids);
 
   List<String> selectProjectUuidsWithIssuesNeedSync(@Param("projectUuids") Collection<String> uuids);
index db97dd953c819a6ac80ac044083c86914cabfc47..3774d62e061c7b04652a6fbfa8cde67cfd199173 100644 (file)
@@ -228,12 +228,11 @@ public class ComponentDao implements Dao {
    * Used by Governance
    */
   public Set<String> selectViewKeysWithEnabledCopyOfProject(DbSession session, Set<String> projectUuids) {
-    return executeLargeInputsIntoSet(projectUuids,
-      partition -> mapper(session).selectViewKeysWithEnabledCopyOfProject(partition),
-      i -> i);
+    return executeLargeInputsIntoSet(projectUuids, partition -> mapper(session).selectViewKeysWithEnabledCopyOfProject(partition), i -> i);
   }
 
-  public List<String> selectProjectsFromView(DbSession session, String viewUuid, String rootViewUuid) {
+  public List<String> selectProjectBranchUuidsFromView(DbSession session, String viewUuid, String rootViewUuid) {
+    // TODO why not query by scope/qualifier, using the view as the branchUuid?
     var escapedViewUuid = viewUuid.replace("_", "\\_").replace("%", "\\%");
     return mapper(session).selectProjectsFromView("%." + escapedViewUuid + ".%", rootViewUuid);
   }
index d9d7c280dc71d0414b80620f11aa8060fc86248c..f07753dc119ea3d1e5629e47548c4b616b3e6974 100644 (file)
@@ -21,6 +21,7 @@ package org.sonar.db.component;
 
 import com.google.common.annotations.VisibleForTesting;
 import java.util.Collection;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.function.BiConsumer;
 import javax.annotation.Nullable;
@@ -31,6 +32,7 @@ import org.sonar.db.Dao;
 import org.sonar.db.DbSession;
 import org.sonar.db.audit.AuditPersister;
 import org.sonar.db.audit.model.ComponentKeyNewValue;
+import org.sonar.db.project.ProjectDto;
 
 /**
  * Class used to rename the key of a project and its resources.
@@ -44,19 +46,15 @@ public class ComponentKeyUpdaterDao implements Dao {
     this.auditPersister = auditPersister;
   }
 
-  public void updateKey(DbSession dbSession, String projectUuid, String newKey) {
+  public void updateKey(DbSession dbSession, String projectUuid, String projectOldKey, String newKey) {
     ComponentKeyUpdaterMapper mapper = dbSession.getMapper(ComponentKeyUpdaterMapper.class);
     checkExistentKey(mapper, newKey);
 
     // must SELECT first everything
-    ResourceDto project = mapper.selectComponentByUuid(projectUuid);
-    String projectOldKey = project.getKey();
-    List<ResourceDto> resources = mapper.selectBranchResources(projectUuid);
-    resources.add(project);
+    List<ResourceDto> resources = new LinkedList<>();
 
-    // add branch components
-    dbSession.getMapper(BranchMapper.class).selectByProjectUuid(projectUuid).stream()
-      .filter(branch -> !projectUuid.equals(branch.getUuid()))
+    // add all branch components
+    dbSession.getMapper(BranchMapper.class).selectByProjectUuid(projectUuid)
       .forEach(branch -> {
         resources.addAll(mapper.selectBranchResources(branch.getUuid()));
         resources.add(mapper.selectComponentByUuid(branch.getUuid()));
index 9859d2370fa404f9df6fd0ed87bbf90e0aa41700..11e5544e4478fe19c41931911522447fbab47f13 100644 (file)
@@ -69,11 +69,11 @@ public class SnapshotDao implements Dao {
   /**
    * returns the last analysis of any branch for each existing project
    */
-  public List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjects(DbSession session, Collection<String> projectUuids) {
+  public List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjectUuids(DbSession session, Collection<String> projectUuids) {
     if (projectUuids.isEmpty()) {
       return Collections.emptyList();
     }
-    return mapper(session).selectLastAnalysisDateByProjects(projectUuids);
+    return mapper(session).selectLastAnalysisDateByProjectUuids(projectUuids);
   }
 
   public Optional<SnapshotDto> selectLastAnalysisByRootComponentUuid(DbSession session, String componentUuid) {
index acf6105d11a0f078e6f799750d6e971d7102d080..05186d5f7cfc96d6b9cb3c92f01539bfa0ada80e 100644 (file)
@@ -38,7 +38,7 @@ public interface SnapshotMapper {
   @CheckForNull
   SnapshotDto selectLastSnapshotByRootComponentUuid(@Param("componentUuid") String componentUuid);
 
-  List<SnapshotDto> selectLastSnapshotsByRootComponentUuids(@Param("componentUuids") Collection<String> componentIds);
+  List<SnapshotDto> selectLastSnapshotsByRootComponentUuids(@Param("componentUuids") Collection<String> componentUuids);
 
   List<SnapshotDto> selectSnapshotsByQuery(@Param("query") SnapshotQuery query);
 
@@ -57,5 +57,5 @@ public interface SnapshotMapper {
   @CheckForNull
   Long selectLastAnalysisDateByProject(String projectUuid);
 
-  List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjects(@Param("projectUuids") Collection<String> projectUuids);
+  List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjectUuids(@Param("projectUuids") Collection<String> projectUuids);
 }
index 6f7a53b4560b8d952758eacc04e2616ec3581a6e..33a4d75c5add8e3f862cd05cb8a50bc8939f2b12 100644 (file)
 package org.sonar.db.component;
 
 public class UuidWithBranchUuidDto {
-
   private String uuid;
   private String branchUuid;
 
+  /**
+   * branchUuid column in the components table for this component.
+   * It can be the UUID of a project or app branch, or the UUID of a portfolio.
+   */
   public String getBranchUuid() {
     return branchUuid;
   }
index f0268ec9de5b198ed95f5e634ef4725aa93beaef..d61cdcaf4fd65038f77d011f4349ff6b98859f9a 100644 (file)
@@ -54,6 +54,10 @@ public class EntityDao implements Dao {
     return executeLargeInputs(keys, partition -> mapper(dbSession).selectByKeys(partition));
   }
 
+  public Optional<EntityDto> selectByComponentUuid(DbSession dbSession, String componentUuid) {
+    return Optional.ofNullable(mapper(dbSession).selectByComponentUuid(componentUuid));
+  }
+
   public void scrollForIndexing(DbSession session, @Nullable String entityUuid, ResultHandler<EntityDto> handler) {
     mapper(session).scrollForIndexing(entityUuid, handler);
   }
index 1ca0041731acc1ee28c8179e8b46834bfee6b4e9..1131ef12ad48fcab9a1e0cd559e19be5ecf5999a 100644 (file)
@@ -35,6 +35,9 @@ public interface EntityMapper {
   @CheckForNull
   EntityDto selectByKey(String key);
 
+  @CheckForNull
+  EntityDto selectByComponentUuid(String componentUuid);
+
   List<EntityDto> selectByKeys(@Param("keys") Collection<String> keys);
 
   void scrollForIndexing(@Param("entityUuid") @Nullable String entityUuid, ResultHandler<EntityDto> handler);
index 41307b39273c2287f47c7d3d640d568c5625977e..88b351b71263c501d5e2f6a913d53f3f62545282 100644 (file)
@@ -214,6 +214,10 @@ public final class IssueDto implements Serializable {
     return this;
   }
 
+  /**
+   * The project branch where the issue is located.
+   * Note that the name is misleading - it should be branch.
+   */
   public IssueDto setProject(ComponentDto project) {
     this.projectKey = project.getKey();
     this.projectUuid = project.uuid();
@@ -572,6 +576,10 @@ public final class IssueDto implements Serializable {
     return this;
   }
 
+  /**
+   * The project branch where the issue is located.
+   * Note that the name is misleading - it should be 'branchUuid'.
+   */
   public String getProjectUuid() {
     return projectUuid;
   }
index 4836b3969cb2d251116561e01761c0faaa15a7e3..338e0e417290175c3ce35b56fc1cabee136d386c 100644 (file)
@@ -26,6 +26,7 @@ import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.rule.Severity;
 import org.sonar.core.util.UuidFactoryFast;
 import org.sonar.core.util.Uuids;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.project.ProjectDto;
 import org.sonar.db.rule.RuleDto;
@@ -48,8 +49,8 @@ public class IssueTesting {
     return newIssue(rule, branch.uuid(), branch.getKey(), file);
   }
 
-  public static IssueDto newIssue(RuleDto rule, ProjectDto project, ComponentDto file) {
-    return newIssue(rule, project.getUuid(), project.getKey(), file);
+  public static IssueDto newIssue(RuleDto rule, BranchDto branch, ComponentDto file) {
+    return newIssue(rule, branch.getUuid(), branch.getKey(), file);
   }
 
   public static IssueDto newIssue(RuleDto rule, String branchUuid, String projectKey, ComponentDto file) {
@@ -80,7 +81,7 @@ public class IssueTesting {
       .setUpdatedAt(System.currentTimeMillis() - 500);
   }
 
-  public static IssueChangeDto newIssuechangeDto(IssueDto issue) {
+  public static IssueChangeDto newIssueChangeDto(IssueDto issue) {
     return new IssueChangeDto()
       .setUuid(UuidFactoryFast.getInstance().create())
       .setKey(UuidFactoryFast.getInstance().create())
index 99e57c6a50db20a7134afd0dec6a9f7e15b6bce4..5cc3ea168a53f0f232a0974888cc0b083c56bbb2 100644 (file)
@@ -72,38 +72,47 @@ public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMea
     CoreMetrics.NEW_LINES_KEY,
     CoreMetrics.NEW_RELIABILITY_RATING_KEY);
 
-  private static final String SQL_PROJECTS = "SELECT p.uuid, p.kee, p.name, s.created_at, p.tags, p.qualifier " +
-    "FROM projects p " +
-    "LEFT OUTER JOIN snapshots s ON s.component_uuid=p.uuid AND s.islast=? " +
-    "WHERE p.qualifier in (?, ?)";
-
-  private static final String PROJECT_FILTER = " AND p.uuid=?";
-
-  private static final String SQL_MEASURES = "SELECT m.name, pm.value, pm.text_value FROM live_measures pm " +
-    "INNER JOIN metrics m ON m.uuid = pm.metric_uuid " +
-    "WHERE pm.component_uuid = ? " +
-    "AND m.name IN ({metricNames}) " +
-    "AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL) " +
-    "AND m.enabled = ? ";
-
-  private static final String SQL_NCLOC_LANGUAGE_DISTRIBUTION = "SELECT m.name, pm.value, pm.text_value FROM live_measures pm " +
-    "INNER JOIN metrics m ON m.uuid = pm.metric_uuid " +
-    "WHERE pm.component_uuid = ? " +
-    "AND m.name = ? " +
-    "AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL) " +
-    "AND m.enabled = ? ";
-
-  private static final String SQL_BIGGEST_NCLOC_VALUE = "SELECT max(lm.value) FROM metrics m " +
-    "INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid " +
-    "INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid " +
-    "WHERE pb.project_uuid = ? " +
-    "AND m.name = ? AND lm.value IS NOT NULL AND m.enabled = ? ";
-
-  private static final String SQL_BRANCH_BY_NCLOC = "SELECT lm.component_uuid FROM metrics m " +
-    "INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid " +
-    "INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid " +
-    "WHERE pb.project_uuid = ? " +
-    "AND m.name = ? AND lm.value = ? AND m.enabled = ? ";
+  private static final String SQL_PROJECTS = """
+    SELECT p.uuid, p.kee, p.name, s.created_at, p.tags, p.qualifier
+    FROM projects p
+    INNER JOIN project_branches pb on p.uuid = pb.project_uuid
+    LEFT OUTER JOIN snapshots s ON s.component_uuid=pb.uuid AND s.islast=?
+    WHERE pb.is_main = ?
+    AND p.qualifier in (?, ?)""";
+
+  private static final String PROJECT_FILTER = " AND pb.project_uuid=?";
+
+  private static final String SQL_MEASURES = """
+    SELECT m.name, pm.value, pm.text_value FROM live_measures pm
+    INNER JOIN metrics m ON m.uuid = pm.metric_uuid
+    INNER JOIN project_branches pb ON pb.uuid = pm.component_uuid
+    WHERE pb.project_uuid = ?
+    AND pb.is_main = ?
+    AND m.name IN ({metricNames})
+    AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL)
+    AND m.enabled = ?""";
+
+  private static final String SQL_NCLOC_LANGUAGE_DISTRIBUTION = """
+    SELECT m.name, pm.value, pm.text_value FROM live_measures pm
+    INNER JOIN metrics m ON m.uuid = pm.metric_uuid
+    WHERE pm.component_uuid = ?
+    AND m.name = ?
+    AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL)
+    AND m.enabled = ?""";
+
+  private static final String SQL_BIGGEST_NCLOC_VALUE = """
+    SELECT max(lm.value) FROM metrics m
+    INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid
+    INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid
+    WHERE pb.project_uuid = ?
+    AND m.name = ? AND lm.value IS NOT NULL AND m.enabled = ? """;
+
+  private static final String SQL_BRANCH_BY_NCLOC = """
+    SELECT lm.component_uuid FROM metrics m
+    INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid
+    INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid
+    WHERE pb.project_uuid = ?
+    AND m.name = ? AND lm.value = ? AND m.enabled = ?""";
 
   private static final boolean ENABLED = true;
   private static final int FIELD_METRIC_NAME = 1;
@@ -129,7 +138,7 @@ public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMea
   private static List<Project> selectProjects(DbSession session, @Nullable String projectUuid) {
     List<Project> projects = new ArrayList<>();
     try (PreparedStatement stmt = createProjectsStatement(session, projectUuid);
-         ResultSet rs = stmt.executeQuery()) {
+      ResultSet rs = stmt.executeQuery()) {
       while (rs.next()) {
         String uuid = rs.getString(1);
         String key = rs.getString(2);
@@ -154,10 +163,11 @@ public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMea
       }
       PreparedStatement stmt = session.getConnection().prepareStatement(sql.toString());
       stmt.setBoolean(1, true);
-      stmt.setString(2, Qualifiers.PROJECT);
-      stmt.setString(3, Qualifiers.APP);
+      stmt.setBoolean(2, true);
+      stmt.setString(3, Qualifiers.PROJECT);
+      stmt.setString(4, Qualifiers.APP);
       if (projectUuid != null) {
-        stmt.setString(4, projectUuid);
+        stmt.setString(5, projectUuid);
       }
       return stmt;
     } catch (SQLException e) {
@@ -219,6 +229,7 @@ public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMea
   private void prepareMeasuresStatement(String projectUuid) throws SQLException {
     AtomicInteger index = new AtomicInteger(1);
     measuresStatement.setString(index.getAndIncrement(), projectUuid);
+    measuresStatement.setBoolean(index.getAndIncrement(), true);
     METRIC_KEYS
       .stream()
       .filter(m -> !m.equals(NCLOC_LANGUAGE_DISTRIBUTION_KEY))
@@ -226,11 +237,11 @@ public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMea
     measuresStatement.setBoolean(index.getAndIncrement(), ENABLED);
   }
 
-  private static PreparedStatement prepareNclocByLanguageStatement(DbSession session, String projectUuid) {
+  private static PreparedStatement prepareNclocByLanguageStatement(DbSession session, String branchUuid) {
     try {
       PreparedStatement stmt = session.getConnection().prepareStatement(SQL_NCLOC_LANGUAGE_DISTRIBUTION);
       AtomicInteger index = new AtomicInteger(1);
-      stmt.setString(index.getAndIncrement(), projectUuid);
+      stmt.setString(index.getAndIncrement(), branchUuid);
       stmt.setString(index.getAndIncrement(), NCLOC_LANGUAGE_DISTRIBUTION_KEY);
       stmt.setBoolean(index.getAndIncrement(), ENABLED);
       return stmt;
index 474712584093c8dfe170edddc8158ff09f412da0..73f030a9d6bfd56eac10481bd00ba3497f00dc3d 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.db.project;
 
+import java.util.Collection;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
@@ -69,7 +70,7 @@ public class ProjectDao implements Dao {
     return mapper(session).selectAllApplications();
   }
 
-  public List<ProjectDto> selectProjectsByKeys(DbSession session, Set<String> keys) {
+  public List<ProjectDto> selectProjectsByKeys(DbSession session, Collection<String> keys) {
     if (keys.isEmpty()) {
       return emptyList();
     }
index 78da4219aef5cda6fa83b3b3568d3ee3c3b79231..6e056b19b641ee0ecedf8590bf4cb18f47305741 100644 (file)
     <foreach collection="branchKeyByProjectUuid" index="key" item="value" open="" separator=" or " close="">
         (pb.project_uuid=#{key,jdbcType=VARCHAR} and pb.kee=#{value,jdbcType=VARCHAR})
     </foreach>
+    and pb.branch_type='BRANCH'
   </select>
 
+    <select id="selectByPullRequestKeys" resultType="org.sonar.db.component.BranchDto">
+    select
+    <include refid="columns"/>
+    from project_branches pb
+    where
+    <foreach collection="prKeyByProjectUuid" index="key" item="value" open="" separator=" or " close="">
+        (pb.project_uuid=#{key,jdbcType=VARCHAR} and pb.kee=#{value,jdbcType=VARCHAR})
+    </foreach>
+    and pb.branch_type='PULL_REQUEST'
+  </select>
+
+
   <select id="selectBranchMeasuresWithCaycMetric" resultType="org.sonar.db.component.BranchMeasuresDto">
     select
     <include refid="telemetryColumns"/>
index da7a40f453d4b66b018029170fd13be2eac8f718..746a1efd27fe0809f18e08a0bf79cce9570a1a38 100644 (file)
@@ -54,7 +54,7 @@
       and coalesce(pb.project_uuid, p.branch_uuid) = #{projectUuid,jdbcType=VARCHAR}
   </select>
 
-  <select id="selectLastAnalysisDateByProjects" resultType="org.sonar.db.component.ProjectLastAnalysisDateDto">
+    <select id="selectLastAnalysisDateByProjectUuids" resultType="org.sonar.db.component.ProjectLastAnalysisDateDto">
     select
       result_with_duplicates.project_uuid as project_uuid ,
       max(result_with_duplicates.last_analysis_date) as last_analysis_date
       where
         s.islast = ${_true}
         and (
-          <!-- case of an analysis of a project or app, with entries in project_branches -->
-          (pb.uuid is not null and pb.project_uuid in
+      <!-- case of an analysis of a project or app, with entries in project_branches -->
+      (pb.uuid is not null and pb.project_uuid in
             <foreach collection="projectUuids" item="projectUuid" separator="," open="(" close=")">
               #{projectUuid,jdbcType=VARCHAR}
             </foreach>)
           or
-          <!-- case of an analysis of a portfolio, where there are no branches -->
-          (pb.uuid is null and c.branch_uuid in
+      <!-- case of an analysis of a portfolio, where there are no branches -->
+      (pb.uuid is null and c.branch_uuid in
             <foreach collection="projectUuids" item="projectUuid" separator="," open="(" close=")">
               #{projectUuid,jdbcType=VARCHAR}
             </foreach>)
@@ -86,7 +86,6 @@
     group by
       result_with_duplicates.project_uuid
   </select>
-
   <select id="selectLastSnapshotByRootComponentUuid" resultType="Snapshot">
     select <include refid="snapshotColumns" />
     from snapshots s
       <foreach collection="componentUuids" item="componentUuid" separator="," open="(" close=")">
         #{componentUuid,jdbcType=VARCHAR}
       </foreach>
-      </select>
+  </select>
 
   <select id="selectSnapshotsByQuery" parameterType="map" resultType="Snapshot">
     SELECT
index 5e071421ae0c4945da16f22254895653e59eabde..5b04f607600c7b4d619d8916ea6161c2049d23cc 100644 (file)
     where p.uuid = #{uuid,jdbcType=VARCHAR})
   </select>
 
-  <sql id="selectAll">
+  <select id="selectByComponentUuid" parameterType="string" resultType="Entity">
+    (select <include refid="entityProjectColumns"/>
+    from projects p
+    inner join project_branches pb on pb.project_uuid = p.uuid
+    inner join components c on c.branch_uuid = pb.uuid
+    where c.uuid = #{uuid,jdbcType=VARCHAR})
+    UNION
+    (select <include refid="entityPortfolioColumns"/>
+    from portfolios p
+    inner join components c on c.branch_uuid = p.uuid
+    where c.uuid = #{uuid,jdbcType=VARCHAR})
+  </select>
+
+    <sql id="selectAll">
     (select <include refid="org.sonar.db.entity.EntityMapper.entityProjectColumns"/>
     from projects p)
     UNION
index ff87690d1c3cce0c75c18ca03838f18eac7da867..9cbe6155a8c0ba7030b569bdd5c79a5d5ad22473 100644 (file)
@@ -93,7 +93,8 @@ public class ComponentDbTester {
   }
 
   public ComponentDto getComponentDto(ProjectDto project) {
-    return db.getDbClient().componentDao().selectByUuid(dbSession, project.getUuid())
+    BranchDto branchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(dbSession, project.getUuid()).get();
+    return db.getDbClient().componentDao().selectByUuid(dbSession, branchDto.getUuid())
       .orElseThrow(() -> new IllegalStateException("Can't find project"));
   }
 
index 96fdfcb5df9a838bad6b688b3af95c6d6484ad3c..f207b8e00dab7df77d11ac9be75ae57534315b17 100644 (file)
@@ -29,9 +29,9 @@ import org.sonar.core.issue.DefaultIssueComment;
 import org.sonar.core.issue.FieldDiffs;
 import org.sonar.core.util.Uuids;
 import org.sonar.db.DbTester;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ProjectData;
-import org.sonar.db.project.ProjectDto;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
 
@@ -101,8 +101,8 @@ public class IssueDbTester {
   }
 
   @SafeVarargs
-  public final IssueDto insert(RuleDto rule, ProjectDto project, ComponentDto file, Consumer<IssueDto>... populators) {
-    IssueDto issue = newIssue(rule, project, file);
+  public final IssueDto insert(RuleDto rule, BranchDto branch, ComponentDto file, Consumer<IssueDto>... populators) {
+    IssueDto issue = newIssue(rule, branch, file);
     stream(populators).forEach(p -> p.accept(issue));
     return insert(issue);
   }
@@ -180,9 +180,9 @@ public class IssueDbTester {
     return insertHotspot(rule, project.getMainBranchComponent(), file, populators);
   }
 
-  public final IssueDto insertHotspot(ProjectDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+  public final IssueDto insertHotspot(BranchDto branchDto, ComponentDto file, Consumer<IssueDto>... populators) {
     RuleDto rule = db.rules().insertHotspotRule();
-    IssueDto issue = newIssue(rule, project, file)
+    IssueDto issue = newIssue(rule, branchDto, file)
       .setType(SECURITY_HOTSPOT)
       .setStatus(Issue.STATUS_TO_REVIEW)
       .setResolution(null);
@@ -220,7 +220,7 @@ public class IssueDbTester {
 
   @SafeVarargs
   public final IssueChangeDto insertChange(IssueDto issueDto, Consumer<IssueChangeDto>... populators) {
-    IssueChangeDto dto = IssueTesting.newIssuechangeDto(issueDto);
+    IssueChangeDto dto = IssueTesting.newIssueChangeDto(issueDto);
     stream(populators).forEach(p -> p.accept(dto));
     return insertChange(dto);
   }
index dca9cd2a3a96dc6e13d606403eb442991f4f8ef9..769c2bfebc0fef92cb24126c5c0f7ea9d6c19348 100644 (file)
@@ -38,8 +38,8 @@ public class ViewIndexIT {
 
   @Test
   public void find_all_view_uuids() {
-    ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjects(singletonList("P1"));
-    ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjects(singletonList("P2"));
+    ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjectBranchUuids(singletonList("P1"));
+    ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjectBranchUuids(singletonList("P2"));
     es.putDocuments(TYPE_VIEW, view1);
     es.putDocuments(TYPE_VIEW, view2);
 
index f414222b43f52136e9445400e4532daf7af70264..33b454360853a91da3a84761ee09521408a34b08 100644 (file)
@@ -49,7 +49,7 @@ public class ViewIndexerIT {
   @Rule
   public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60));
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
 
@@ -94,10 +94,10 @@ public class ViewIndexerIT {
 
     Map<String, ViewDoc> viewsByUuid = Maps.uniqueIndex(docs, ViewDoc::uuid);
 
-    assertThat(viewsByUuid.get(view1.uuid()).projects()).containsOnly(project1.uuid());
-    assertThat(viewsByUuid.get(view2.uuid()).projects()).containsOnly(project2.uuid(), project3.uuid());
-    assertThat(viewsByUuid.get(subView.uuid()).projects()).containsOnly(project3.uuid());
-    assertThat(viewsByUuid.get(view3.uuid()).projects()).isEmpty();
+    assertThat(viewsByUuid.get(view1.uuid()).projectBranchUuids()).containsOnly(project1.uuid());
+    assertThat(viewsByUuid.get(view2.uuid()).projectBranchUuids()).containsOnly(project2.uuid(), project3.uuid());
+    assertThat(viewsByUuid.get(subView.uuid()).projectBranchUuids()).containsOnly(project3.uuid());
+    assertThat(viewsByUuid.get(view3.uuid()).projectBranchUuids()).isEmpty();
   }
 
   @Test
@@ -126,20 +126,20 @@ public class ViewIndexerIT {
 
     Map<String, ViewDoc> viewsByUuid = Maps.uniqueIndex(docs, ViewDoc::uuid);
 
-    assertThat(viewsByUuid.get(view2.uuid()).projects()).containsOnly(project2.uuid(), project3.uuid());
-    assertThat(viewsByUuid.get(subView.uuid()).projects()).containsOnly(project3.uuid());
+    assertThat(viewsByUuid.get(view2.uuid()).projectBranchUuids()).containsOnly(project2.uuid(), project3.uuid());
+    assertThat(viewsByUuid.get(subView.uuid()).projectBranchUuids()).containsOnly(project3.uuid());
   }
 
   @Test
   public void index_view_doc() {
-    underTest.index(new ViewDoc().setUuid("EFGH").setProjects(newArrayList("KLMN", "JKLM")));
+    underTest.index(new ViewDoc().setUuid("EFGH").setProjectBranchUuids(newArrayList("KLMN", "JKLM")));
 
     List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class);
 
     assertThat(result).hasSize(1);
     ViewDoc view = result.get(0);
     assertThat(view.uuid()).isEqualTo("EFGH");
-    assertThat(view.projects()).containsOnly("KLMN", "JKLM");
+    assertThat(view.projectBranchUuids()).containsOnly("KLMN", "JKLM");
   }
 
   @Test
@@ -154,7 +154,7 @@ public class ViewIndexerIT {
     assertThat(result).hasSize(1);
     ViewDoc resultApp = result.get(0);
     assertThat(resultApp.uuid()).isEqualTo(application.uuid());
-    assertThat(resultApp.projects()).containsExactlyInAnyOrder(project.uuid());
+    assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid());
   }
 
   @Test
@@ -169,7 +169,7 @@ public class ViewIndexerIT {
     assertThat(result).hasSize(1);
     ViewDoc resultApp = result.get(0);
     assertThat(resultApp.uuid()).isEqualTo(application.uuid());
-    assertThat(resultApp.projects()).containsExactlyInAnyOrder(project.uuid());
+    assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid());
   }
 
   @Test
@@ -184,7 +184,7 @@ public class ViewIndexerIT {
     assertThat(result).hasSize(1);
     ViewDoc resultApp = result.get(0);
     assertThat(resultApp.uuid()).isEqualTo(application.uuid());
-    assertThat(resultApp.projects()).containsExactlyInAnyOrder(project.uuid());
+    assertThat(resultApp.projectBranchUuids()).containsExactlyInAnyOrder(project.uuid());
   }
 
   @Test
@@ -207,16 +207,16 @@ public class ViewIndexerIT {
 
     List<ViewDoc> result = es.getDocuments(TYPE_VIEW, ViewDoc.class);
     assertThat(result)
-      .extracting(ViewDoc::uuid, ViewDoc::projects)
+      .extracting(ViewDoc::uuid, ViewDoc::projectBranchUuids)
       .containsExactlyInAnyOrder(
         tuple(applicationBranch1.uuid(), asList(project1Branch.uuid(), project2Branch.uuid())));
   }
 
   @Test
   public void delete_should_delete_the_view() {
-    ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjects(Collections.singletonList("P1"));
-    ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjects(asList("P2", "P3", "P4"));
-    ViewDoc view3 = new ViewDoc().setUuid("UUID3").setProjects(asList("P2", "P3", "P4"));
+    ViewDoc view1 = new ViewDoc().setUuid("UUID1").setProjectBranchUuids(Collections.singletonList("P1"));
+    ViewDoc view2 = new ViewDoc().setUuid("UUID2").setProjectBranchUuids(asList("P2", "P3", "P4"));
+    ViewDoc view3 = new ViewDoc().setUuid("UUID3").setProjectBranchUuids(asList("P2", "P3", "P4"));
     es.putDocuments(TYPE_VIEW, view1);
     es.putDocuments(TYPE_VIEW, view2);
     es.putDocuments(TYPE_VIEW, view3);
index 396c5149b999cc8353f5ccf4581f5a9ce64094ff..1fbda41ee1da4c0669cd707827471536939773b5 100644 (file)
@@ -20,7 +20,6 @@
 package org.sonar.server.component.index;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableSet;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
@@ -33,6 +32,7 @@ import org.elasticsearch.search.builder.SearchSourceBuilder;
 import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.entity.EntityDto;
 import org.sonar.db.es.EsQueueDto;
 import org.sonar.server.es.BaseDoc;
@@ -53,7 +53,7 @@ import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COM
 public class ComponentIndexer implements ProjectIndexer, NeedAuthorizationIndexer {
 
   private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_COMPONENT, project -> true);
-  private static final ImmutableSet<IndexType> INDEX_TYPES = ImmutableSet.of(TYPE_COMPONENT);
+  private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_COMPONENT);
 
   private final DbClient dbClient;
   private final EsClient esClient;
@@ -70,11 +70,11 @@ public class ComponentIndexer implements ProjectIndexer, NeedAuthorizationIndexe
 
   @Override
   public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
-    doIndexByProjectUuid(Size.LARGE);
+    doIndexByEntityUuid(Size.LARGE);
   }
 
   public void indexAll() {
-    doIndexByProjectUuid(Size.REGULAR);
+    doIndexByEntityUuid(Size.REGULAR);
   }
 
   @Override
@@ -83,8 +83,17 @@ public class ComponentIndexer implements ProjectIndexer, NeedAuthorizationIndexe
   }
 
   @Override
-  public void indexOnAnalysis(String entityUuid, Set<String> unchangedComponentUuids) {
-    doIndexByProjectUuid(entityUuid);
+  public void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids) {
+    try (DbSession dbSession = dbClient.openSession(false)) {
+      Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, branchUuid);
+
+      if (branchDto.isPresent() && !branchDto.get().isMain()) {
+        return;
+      }
+      EntityDto entity = dbClient.entityDao().selectByComponentUuid(dbSession, branchUuid)
+        .orElseThrow(() -> new IllegalStateException("Can't find entity " + branchUuid));
+      doIndexByEntityUuid(entity);
+    }
   }
 
   @Override
@@ -137,25 +146,18 @@ public class ComponentIndexer implements ProjectIndexer, NeedAuthorizationIndexe
   }
 
   /**
-   * @param entityUuid the uuid of the project to analyze, or {@code null} if all content should be indexed.<br/>
-   *                   <b>Warning:</b> only use {@code null} during startup.
+   * @param entity the entity to analyze, or {@code null} if all content should be indexed.<br/>
+   *               <b>Warning:</b> only use {@code null} during startup.
    */
-  private void doIndexByProjectUuid(String entityUuid) {
+  private void doIndexByEntityUuid(EntityDto entity) {
     BulkIndexer bulk = new BulkIndexer(esClient, TYPE_COMPONENT, Size.REGULAR);
     bulk.start();
 
     try (DbSession dbSession = dbClient.openSession(false)) {
-      Optional<EntityDto> entityDto = dbClient.entityDao().selectByUuid(dbSession, entityUuid);
-
-      if (entityDto.isEmpty()) {
-        return;
-      }
-      EntityDto entity = entityDto.get();
-
       bulk.add(toDocument(entity).toIndexRequest());
 
       if (entity.getQualifier().equals("VW")) {
-        dbClient.portfolioDao().selectTree(dbSession, entityUuid).forEach(sub ->
+        dbClient.portfolioDao().selectTree(dbSession, entity.getUuid()).forEach(sub ->
           bulk.add(toDocument(sub).toIndexRequest()));
       }
     }
@@ -163,7 +165,7 @@ public class ComponentIndexer implements ProjectIndexer, NeedAuthorizationIndexe
     bulk.stop();
   }
 
-  private void doIndexByProjectUuid(Size bulkSize) {
+  private void doIndexByEntityUuid(Size bulkSize) {
     BulkIndexer bulk = new BulkIndexer(esClient, TYPE_COMPONENT, bulkSize);
     bulk.start();
     try (DbSession dbSession = dbClient.openSession(false)) {
index bc50f2c0d93de5cd43dd186a8e6220f4ac093251..1db14f06614f79869baeae61c6b174179deaaa60 100644 (file)
@@ -48,8 +48,7 @@ public interface ProjectIndexer extends ResilientIndexer {
   /**
    * This method is called when an analysis must be indexed.
    *
-   * @param branchUuid non-null UUID of branch in table "projects". It can reference
-   *                   a non-main branch
+   * @param branchUuid UUID of a project or application branch, or the UUID of a portfolio.
    */
   void indexOnAnalysis(String branchUuid);
 
index ec4824fbc78b9a7eb1489de268f712762851b09c..abcbebb0d05ec287d0dc838cec0d10c658f55b95 100644 (file)
@@ -37,7 +37,7 @@ public interface ProjectIndexers {
    */
   void commitAndIndexByProjectUuids(DbSession dbSession, Collection<String> projectUuids, ProjectIndexer.Cause cause);
 
-  default void commitAndIndexEntities(DbSession dbSession, Collection<EntityDto> entities, ProjectIndexer.Cause cause) {
+  default void commitAndIndexEntities(DbSession dbSession, Collection<? extends EntityDto> entities, ProjectIndexer.Cause cause) {
     Collection<String> entityUuids = entities.stream()
       .map(EntityDto::getUuid)
       .collect(MoreCollectors.toSet(entities.size()));
@@ -45,10 +45,7 @@ public interface ProjectIndexers {
   }
 
   default void commitAndIndexProjects(DbSession dbSession, Collection<ProjectDto> projects, ProjectIndexer.Cause cause) {
-    Collection<String> projectUuids = projects.stream()
-      .map(ProjectDto::getUuid)
-      .collect(MoreCollectors.toSet(projects.size()));
-    commitAndIndexByProjectUuids(dbSession, projectUuids, cause);
+    commitAndIndexEntities(dbSession, projects, cause);
   }
 
   default void commitAndIndexComponents(DbSession dbSession, Collection<ComponentDto> projects, ProjectIndexer.Cause cause) {
index 60d4f9c6b70d9ae24e59d1e3471a6863dfab8b2f..6727f89825c59dfb86f1f1debaf907bff6e2fd35 100644 (file)
@@ -24,17 +24,17 @@ import org.sonar.db.DbSession;
 import org.sonar.db.es.EsQueueDto;
 
 /**
- * This kind of indexers that are resilient
+ * Indexers that are resilient
  */
 public interface ResilientIndexer extends StartupIndexer {
 
   /**
-   * Index the items and delete them from es_queue table when the indexation
-   * is done, keep it if there is a failure on the item of the collection
+   * Index the items and delete them from es_queue DB table when the indexation
+   * is done, keeping them if there is a failure on the item of the collection
    *
    * @param dbSession the db session
    * @param items     the items to be indexed
-   * @return the number of successful indexation
+   * @return the number of successful indexed items
    */
   IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items);
 }
index c4a0e3e59d6ab5b2428b1f7fc5d937fbdd393380..d22ab314330aaf16818db61012e425de4658e1aa 100644 (file)
@@ -33,7 +33,7 @@ public class SearchRequest {
   private List<String> assigneesUuid;
   private List<String> authors;
   private List<String> componentUuids;
-  private List<String> components;
+  private List<String> componentKeys;
   private String createdAfter;
   private String createdAt;
   private String createdBefore;
@@ -51,7 +51,7 @@ public class SearchRequest {
   private String pullRequest;
   private int page;
   private int pageSize;
-  private List<String> projects;
+  private List<String> projectKeys;
   private List<String> resolutions;
   private Boolean resolved;
   private List<String> rules;
@@ -435,22 +435,22 @@ public class SearchRequest {
   }
 
   @CheckForNull
-  public List<String> getComponents() {
-    return components;
+  public List<String> getComponentKeys() {
+    return componentKeys;
   }
 
-  public SearchRequest setComponents(@Nullable List<String> components) {
-    this.components = components;
+  public SearchRequest setComponentKeys(@Nullable List<String> componentKeys) {
+    this.componentKeys = componentKeys;
     return this;
   }
 
   @CheckForNull
-  public List<String> getProjects() {
-    return projects;
+  public List<String> getProjectKeys() {
+    return projectKeys;
   }
 
-  public SearchRequest setProjects(@Nullable List<String> projects) {
-    this.projects = projects;
+  public SearchRequest setProjectKeys(@Nullable List<String> projectKeys) {
+    this.projectKeys = projectKeys;
     return this;
   }
 
index 9cfb992b2a26ad83cf8daadbf0676226ef3122ee..fdfaba17578746dd46f242dc04452bacc8ec31c5 100644 (file)
@@ -63,27 +63,20 @@ public class IssueIndexDefinition implements IndexDefinition {
   public static final String FIELD_ISSUE_LINE = "line";
 
   /**
-   * The (real) project, equivalent of projects.main_branch_project_uuid | projects.project_uuid, so
+   * The (real) project, equivalent of projects.uuid, so
    * it's never empty.
-   * On main branches, it is the UUID of the project.
-   * On non-main branches, it is the UUID of the main branch (which represents the project).
    * This field maps the parent association with issues/authorization.
    */
   public static final String FIELD_ISSUE_PROJECT_UUID = "project";
 
   /**
-   * The branch, as represented by the component with TRK qualifier. It's never
-   * empty. It maps the DB column projects.project_uuid:
-   * - on main branches, it is the UUID of the project. It equals {@link #FIELD_ISSUE_PROJECT_UUID}.
-   * - on non-main branches, it is the UUID of the project representing the branch and it
-   * is different than {@link #FIELD_ISSUE_PROJECT_UUID}.
+   * The branch. It's never empty. It maps the DB column components.branch_uuid.
+   * It's the UUID of the branch and it's different than {@link #FIELD_ISSUE_PROJECT_UUID}.
    */
   public static final String FIELD_ISSUE_BRANCH_UUID = "branch";
 
   /**
    * Whether component is in a main branch or not.
-   * If true, then {@link #FIELD_ISSUE_BRANCH_UUID} equals {@link #FIELD_ISSUE_PROJECT_UUID}.
-   * If false, then {@link #FIELD_ISSUE_BRANCH_UUID} is different than {@link #FIELD_ISSUE_PROJECT_UUID}.
    */
   public static final String FIELD_ISSUE_IS_MAIN_BRANCH = "isMainBranch";
 
index 4f0c41073ffced11ebcd81c6034dafc67837005e..d446c4e491d5d539718381758e3011681f429235 100644 (file)
@@ -170,12 +170,12 @@ public class IssueIndexer implements ProjectIndexer, NeedAuthorizationIndexer {
   @Override
   public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) {
     ListMultimap<String, EsQueueDto> itemsByIssueKey = ArrayListMultimap.create();
-    ListMultimap<String, EsQueueDto> itemsByProjectKey = ArrayListMultimap.create();
+    ListMultimap<String, EsQueueDto> itemsByProjectUuid = ArrayListMultimap.create();
     items.forEach(i -> {
       if (ID_TYPE_ISSUE_KEY.equals(i.getDocIdType())) {
         itemsByIssueKey.put(i.getDocId(), i);
       } else if (ID_TYPE_PROJECT_UUID.equals(i.getDocIdType())) {
-        itemsByProjectKey.put(i.getDocId(), i);
+        itemsByProjectUuid.put(i.getDocId(), i);
       } else {
         LOGGER.error("Unsupported es_queue.doc_id_type for issues. Manual fix is required: " + i);
       }
@@ -183,7 +183,7 @@ public class IssueIndexer implements ProjectIndexer, NeedAuthorizationIndexer {
 
     IndexingResult result = new IndexingResult();
     result.add(doIndexIssueItems(dbSession, itemsByIssueKey));
-    result.add(doIndexProjectItems(dbSession, itemsByProjectKey));
+    result.add(doIndexProjectItems(dbSession, itemsByProjectUuid));
     return result;
   }
 
index d10d8210ecd1244e70e6403127db16fe88b5d0a3..45769e0fd597e3564faf2f2c6d95a02a333c297a 100644 (file)
@@ -31,15 +31,15 @@ import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIEL
 
 public class AuthorizationDoc extends BaseDoc {
   private static final String ID_PREFIX = "auth_";
-  private final String projectUuid;
+  private final String entityUuid;
 
-  private AuthorizationDoc(IndexType indexType, String projectUuid) {
+  private AuthorizationDoc(IndexType indexType, String entityUuid) {
     super(indexType);
-    this.projectUuid = projectUuid;
+    this.entityUuid = entityUuid;
   }
 
   public static AuthorizationDoc fromDto(IndexType indexType, IndexPermissions dto) {
-    AuthorizationDoc res = new AuthorizationDoc(indexType, dto.getProjectUuid());
+    AuthorizationDoc res = new AuthorizationDoc(indexType, dto.getEntityUuid());
     if (dto.isAllowAnyone()) {
       return res.setAllowAnyone();
     }
@@ -48,7 +48,7 @@ public class AuthorizationDoc extends BaseDoc {
 
   @Override
   public String getId() {
-    return idOf(projectUuid);
+    return idOf(entityUuid);
   }
 
   public static String idOf(String projectUuid) {
@@ -56,7 +56,7 @@ public class AuthorizationDoc extends BaseDoc {
     return ID_PREFIX + projectUuid;
   }
 
-  public static String projectUuidOf(String id) {
+  public static String entityUuidOf(String id) {
     if (id.startsWith(ID_PREFIX)) {
       return id.substring(ID_PREFIX.length());
     }
@@ -65,7 +65,7 @@ public class AuthorizationDoc extends BaseDoc {
 
   @Override
   protected Optional<String> getSimpleMainTypeRouting() {
-    return Optional.of(projectUuid);
+    return Optional.of(entityUuid);
   }
 
   private AuthorizationDoc setAllowAnyone() {
index ceff5c5d6e904b391df34a005e095437ffd6977b..0f34613b3a6a6fb0cf645849571f57db3de7e723 100644 (file)
@@ -23,19 +23,19 @@ import java.util.ArrayList;
 import java.util.List;
 
 public final class IndexPermissions {
-  private final String projectUuid;
+  private final String entityUuid;
   private final String qualifier;
   private final List<String> userUuids = new ArrayList<>();
   private final List<String> groupUuids = new ArrayList<>();
   private boolean allowAnyone = false;
 
-  public IndexPermissions(String projectUuid, String qualifier) {
-    this.projectUuid = projectUuid;
+  public IndexPermissions(String entityUuid, String qualifier) {
+    this.entityUuid = entityUuid;
     this.qualifier = qualifier;
   }
 
-  public String getProjectUuid() {
-    return projectUuid;
+  public String getEntityUuid() {
+    return entityUuid;
   }
 
   public String getQualifier() {
index d827ef417137a29624dbd54b3fa1ed021e833178..9dbd0616e264644aec212d3b2c7a5cc4e5571590 100644 (file)
@@ -41,22 +41,29 @@ public class ViewDoc extends BaseDoc {
     return uuid();
   }
 
+  /**
+   * Uuid of the view.
+   * It may or may not be the root view (Qualifiers SVW, SW, APP).
+   */
   public String uuid() {
     return getField(ViewIndexDefinition.FIELD_UUID);
   }
 
-  public List<String> projects() {
+  public List<String> projectBranchUuids() {
     return getField(ViewIndexDefinition.FIELD_PROJECTS);
   }
 
+  /**
+   * Uuid of the view.
+   * It may or may not be the root view (Qualifiers SVW, SW, APP).
+   */
   public ViewDoc setUuid(String s) {
     setField(ViewIndexDefinition.FIELD_UUID, s);
     return this;
   }
 
-  public ViewDoc setProjects(List<String> s) {
+  public ViewDoc setProjectBranchUuids(List<String> s) {
     setField(ViewIndexDefinition.FIELD_PROJECTS, s);
     return this;
   }
-
 }
index 25b1308fd4e59f69de27508e788ad3dfa5e0841f..cf6377bca8844e29b413fd1dc8de073c71d3f5fd 100644 (file)
@@ -36,6 +36,10 @@ import org.sonar.server.es.EsClient;
 import static com.google.common.collect.Lists.newArrayList;
 import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
 
+/**
+ * The View Index indexes all views, root and not root (APP, VW, SVW), and all projects that are computed under each view.
+ * It's based on the computation results, coming from the components table, not on the definition of those views.
+ */
 @ServerSide
 @ComputeEngineSide
 public class ViewIndex {
index 381eee197288e04bbefc1fd75566119ae4e9b10f..56cb492fabaf471f60d87af41f654748d0068289 100644 (file)
@@ -70,16 +70,16 @@ public class ViewIndexer implements ResilientIndexer {
 
   private void indexAll(Size bulkSize) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      Map<String, String> viewAndProjectViewUuidMap = new HashMap<>();
+      Map<String, String> rootViewUuidByViewUuid = new HashMap<>();
       for (UuidWithBranchUuidDto uuidWithBranchUuidDto : dbClient.componentDao().selectAllViewsAndSubViews(dbSession)) {
-        viewAndProjectViewUuidMap.put(uuidWithBranchUuidDto.getUuid(), uuidWithBranchUuidDto.getBranchUuid());
+        rootViewUuidByViewUuid.put(uuidWithBranchUuidDto.getUuid(), uuidWithBranchUuidDto.getBranchUuid());
       }
-      index(dbSession, viewAndProjectViewUuidMap, false, bulkSize);
+      index(dbSession, rootViewUuidByViewUuid, false, bulkSize);
     }
   }
 
   /**
-   * Index a root view : it will a view and its subviews and index them.
+   * Index a root view : it will fetch a view and its subviews from the DB and index them.
    * Used by the compute engine to reindex a root view.
    * <p/>
    * The views lookup cache will be cleared
@@ -106,15 +106,16 @@ public class ViewIndexer implements ResilientIndexer {
     bulk.stop();
   }
 
-  private void index(DbSession dbSession, Map<String, String> viewAndRootViewUuidMap, boolean needClearCache, Size bulkSize) {
+  private void index(DbSession dbSession, Map<String, String> rootViewUuidByViewUuid, boolean needClearCache, Size bulkSize) {
     BulkIndexer bulk = new BulkIndexer(esClient, TYPE_VIEW, bulkSize);
     bulk.start();
-    for (Map.Entry<String, String> entry : viewAndRootViewUuidMap.entrySet()) {
+    for (Map.Entry<String, String> entry : rootViewUuidByViewUuid.entrySet()) {
       String viewUuid = entry.getKey();
-      List<String> projects = dbClient.componentDao().selectProjectsFromView(dbSession, viewUuid, entry.getValue());
+      String rootViewUuid = entry.getValue();
+      List<String> projectBranchUuids = dbClient.componentDao().selectProjectBranchUuidsFromView(dbSession, viewUuid, rootViewUuid);
       doIndex(bulk, new ViewDoc()
         .setUuid(viewUuid)
-        .setProjects(projects), needClearCache);
+        .setProjectBranchUuids(projectBranchUuids), needClearCache);
     }
     bulk.stop();
   }
@@ -145,7 +146,6 @@ public class ViewIndexer implements ResilientIndexer {
    * This is based on the fact that a WebService is only calling {@link ViewIndexer#delete(DbSession, Collection)}
    * So the resiliency is only taking in account a deletion of view component
    * A safety check is done by not deleting any component that still exist in database.
-   *
    * This should not occur but prevent any misuse on this resiliency
    */
   @Override
@@ -154,7 +154,7 @@ public class ViewIndexer implements ResilientIndexer {
       return new IndexingResult();
     }
 
-    Set<String> views = items
+    Set<String> viewUuids = items
       .stream()
       .map(EsQueueDto::getDocId)
       .collect(toHashSet(items.size()));
@@ -163,8 +163,8 @@ public class ViewIndexer implements ResilientIndexer {
     bulkIndexer.start();
 
     // Safety check to remove all views that may not have been deleted
-    views.removeAll(dbClient.componentDao().selectExistingUuids(dbSession, views));
-    views.forEach(v -> bulkIndexer.addDeletion(TYPE_VIEW, v));
+    viewUuids.removeAll(dbClient.componentDao().selectExistingUuids(dbSession, viewUuids));
+    viewUuids.forEach(v -> bulkIndexer.addDeletion(TYPE_VIEW, v));
     return bulkIndexer.stop();
   }
 
index 04ef1b6348846a5d2614513cf93b3a677d398310..f5f7f0620c1891e4649f8e2a4895ad55077beab7 100644 (file)
@@ -35,7 +35,7 @@ public class SearchRequestTest {
       .setStatuses(singletonList("CLOSED"))
       .setResolutions(singletonList("FALSE-POSITIVE"))
       .setResolved(true)
-      .setProjects(singletonList("project-a"))
+      .setProjectKeys(singletonList("project-a"))
       .setDirectories(singletonList("aDirPath"))
       .setFiles(asList("file-a", "file-b"))
       .setAssigneesUuid(asList("user-a", "user-b"))
@@ -61,7 +61,7 @@ public class SearchRequestTest {
     assertThat(underTest.getStatuses()).containsExactly("CLOSED");
     assertThat(underTest.getResolutions()).containsExactly("FALSE-POSITIVE");
     assertThat(underTest.getResolved()).isTrue();
-    assertThat(underTest.getProjects()).containsExactly("project-a");
+    assertThat(underTest.getProjectKeys()).containsExactly("project-a");
     assertThat(underTest.getDirectories()).containsExactly("aDirPath");
     assertThat(underTest.getFiles()).containsExactly("file-a", "file-b");
     assertThat(underTest.getAssigneeUuids()).containsExactly("user-a", "user-b");
index 75250d664129e4ff300fb08beb1f8479731e19ee..9eedb55c79b1e92b9890a7355515af8da440d7af 100644 (file)
@@ -54,23 +54,23 @@ public class AuthorizationDocTest {
 
   @Test
   public void projectUuidOf_fails_with_NPE_if_argument_is_null() {
-    assertThatThrownBy(() ->  AuthorizationDoc.projectUuidOf(null))
+    assertThatThrownBy(() ->  AuthorizationDoc.entityUuidOf(null))
       .isInstanceOf(NullPointerException.class);
   }
 
   @Test
   public void projectUuidOf_returns_substring_if_starts_with_id_prefix() {
-    assertThat(AuthorizationDoc.projectUuidOf("auth_")).isEmpty();
+    assertThat(AuthorizationDoc.entityUuidOf("auth_")).isEmpty();
 
     String id = randomAlphabetic(1 + new Random().nextInt(10));
-    assertThat(AuthorizationDoc.projectUuidOf("auth_" + id)).isEqualTo(id);
+    assertThat(AuthorizationDoc.entityUuidOf("auth_" + id)).isEqualTo(id);
   }
 
   @Test
   public void projectUuidOf_returns_argument_if_does_not_starts_with_id_prefix() {
     String id = randomAlphabetic(1 + new Random().nextInt(10));
-    assertThat(AuthorizationDoc.projectUuidOf(id)).isEqualTo(id);
-    assertThat(AuthorizationDoc.projectUuidOf("")).isEmpty();
+    assertThat(AuthorizationDoc.entityUuidOf(id)).isEqualTo(id);
+    assertThat(AuthorizationDoc.entityUuidOf("")).isEmpty();
   }
 
   @Test
@@ -89,7 +89,7 @@ public class AuthorizationDocTest {
   public void getId_returns_projectUuid_with_a_prefix(IndexPermissions dto) {
     AuthorizationDoc underTest = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), dto);
 
-    assertThat(underTest.getId()).isEqualTo("auth_" + dto.getProjectUuid());
+    assertThat(underTest.getId()).isEqualTo("auth_" + dto.getEntityUuid());
   }
 
   @Test
@@ -97,7 +97,7 @@ public class AuthorizationDocTest {
   public void getRouting_returns_projectUuid(IndexPermissions dto) {
     AuthorizationDoc underTest = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), dto);
 
-    assertThat(underTest.getRouting()).contains(dto.getProjectUuid());
+    assertThat(underTest.getRouting()).contains(dto.getEntityUuid());
   }
 
   @Test
index d4903dd711f5527758ec2d94e7691b22b26817bb..f5a62707ef3f8c42aa423dcc94c152ddb6092896 100644 (file)
@@ -35,7 +35,6 @@ import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDbTester;
-import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ProjectData;
 import org.sonar.db.permission.GroupPermissionDto;
 import org.sonar.db.portfolio.PortfolioDto;
@@ -43,7 +42,6 @@ import org.sonar.db.project.ProjectDto;
 import org.sonar.db.user.GroupDto;
 import org.sonar.db.user.UserDbTester;
 import org.sonar.db.user.UserDto;
-import org.sonar.server.project.Project;
 
 import static java.util.Arrays.asList;
 import static java.util.Collections.singletonList;
@@ -128,7 +126,7 @@ public class PermissionIndexerDaoIT {
       .selectByUuids(dbClient, dbSession,
         asList(publicProject.getUuid(), privateProject1.getUuid(), privateProject2.getUuid(), view1.getUuid(), view2.getUuid(), application.getUuid()))
       .stream()
-      .collect(MoreCollectors.uniqueIndex(IndexPermissions::getProjectUuid, Function.identity()));
+      .collect(MoreCollectors.uniqueIndex(IndexPermissions::getEntityUuid, Function.identity()));
     Assertions.assertThat(dtos).hasSize(6);
 
     IndexPermissions publicProjectAuthorization = dtos.get(publicProject.getUuid());
@@ -183,7 +181,7 @@ public class PermissionIndexerDaoIT {
 
     assertThat(underTest.selectByUuids(dbClient, dbSession, projectUuids))
       .hasSize(3500)
-      .extracting(IndexPermissions::getProjectUuid)
+      .extracting(IndexPermissions::getEntityUuid)
       .containsAll(projectUuids);
   }
 
@@ -197,7 +195,7 @@ public class PermissionIndexerDaoIT {
     assertThat(dto.getGroupUuids()).isEmpty();
     assertThat(dto.getUserUuids()).isEmpty();
     assertThat(dto.isAllowAnyone()).isFalse();
-    assertThat(dto.getProjectUuid()).isEqualTo(privateProject1.getUuid());
+    assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
     assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
   }
 
@@ -210,7 +208,7 @@ public class PermissionIndexerDaoIT {
     assertThat(dto.getGroupUuids()).isEmpty();
     assertThat(dto.getUserUuids()).isEmpty();
     assertThat(dto.isAllowAnyone()).isTrue();
-    assertThat(dto.getProjectUuid()).isEqualTo(publicProject.getUuid());
+    assertThat(dto.getEntityUuid()).isEqualTo(publicProject.getUuid());
     assertThat(dto.getQualifier()).isEqualTo(publicProject.getQualifier());
   }
 
@@ -224,7 +222,7 @@ public class PermissionIndexerDaoIT {
     assertThat(dto.getGroupUuids()).isEmpty();
     assertThat(dto.getUserUuids()).containsOnly(user1.getUuid());
     assertThat(dto.isAllowAnyone()).isFalse();
-    assertThat(dto.getProjectUuid()).isEqualTo(privateProject1.getUuid());
+    assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
     assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
   }
 
@@ -239,7 +237,7 @@ public class PermissionIndexerDaoIT {
     assertThat(dto.getGroupUuids()).containsOnly(group.getUuid());
     assertThat(dto.getUserUuids()).isEmpty();
     assertThat(dto.isAllowAnyone()).isFalse();
-    assertThat(dto.getProjectUuid()).isEqualTo(privateProject1.getUuid());
+    assertThat(dto.getEntityUuid()).isEqualTo(privateProject1.getUuid());
     assertThat(dto.getQualifier()).isEqualTo(privateProject1.getQualifier());
   }
 
@@ -251,7 +249,7 @@ public class PermissionIndexerDaoIT {
   }
 
   private static IndexPermissions getByProjectUuid(String projectUuid, Collection<IndexPermissions> dtos) {
-    return dtos.stream().filter(dto -> dto.getProjectUuid().equals(projectUuid)).findFirst().orElseThrow(IllegalArgumentException::new);
+    return dtos.stream().filter(dto -> dto.getEntityUuid().equals(projectUuid)).findFirst().orElseThrow(IllegalArgumentException::new);
   }
 
   private void insertTestDataForProjectsAndViews() {
index 58174b3b5f2791369f08e62cc24799f7c8252d89..a6c367cc8c48ed25874f88d8c2de8b4095d7c36c 100644 (file)
@@ -178,6 +178,10 @@ public class IssueQuery {
     return files;
   }
 
+  /**
+   * Restrict issues belonging to projects that were analyzed under a view.
+   * The view UUIDs should be portfolios, sub portfolios or application branches.
+   */
   public Collection<String> viewUuids() {
     return views;
   }
@@ -422,6 +426,10 @@ public class IssueQuery {
       return this;
     }
 
+    /**
+     * Restrict issues belonging to projects that were analyzed under a view.
+     * The view UUIDs should be portfolios, sub portfolios or application branches.
+     */
     public Builder viewUuids(@Nullable Collection<String> l) {
       this.views = l;
       return this;
index 3ae9b3992108b1fb28ab2d4e1cbab7197a065164..63d5679c91ca800f5dedf52dd8b50612094e3b48 100644 (file)
@@ -42,12 +42,12 @@ import java.util.stream.Collectors;
 import javax.annotation.Nullable;
 import org.apache.commons.lang.BooleanUtils;
 import org.jetbrains.annotations.NotNull;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.api.rules.RuleType;
 import org.sonar.api.server.ServerSide;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
@@ -248,18 +248,18 @@ public class IssueQueryFactory {
 
   private boolean mergeDeprecatedComponentParameters(DbSession session, SearchRequest request, List<ComponentDto> allComponents) {
     Boolean onComponentOnly = request.getOnComponentOnly();
-    Collection<String> components = request.getComponents();
+    Collection<String> componentKeys = request.getComponentKeys();
     Collection<String> componentUuids = request.getComponentUuids();
     String branch = request.getBranch();
     String pullRequest = request.getPullRequest();
 
     boolean effectiveOnComponentOnly = false;
 
-    checkArgument(atMostOneNonNullElement(components, componentUuids),
+    checkArgument(atMostOneNonNullElement(componentKeys, componentUuids),
       "At most one of the following parameters can be provided: %s and %s", PARAM_COMPONENT_KEYS, PARAM_COMPONENT_UUIDS);
 
-    if (components != null) {
-      allComponents.addAll(getComponentsFromKeys(session, components, branch, pullRequest));
+    if (componentKeys != null) {
+      allComponents.addAll(getComponentsFromKeys(session, componentKeys, branch, pullRequest));
       effectiveOnComponentOnly = BooleanUtils.isTrue(onComponentOnly);
     } else if (componentUuids != null) {
       allComponents.addAll(getComponentsFromUuids(session, componentUuids));
@@ -284,7 +284,7 @@ public class IssueQueryFactory {
       return;
     }
 
-    List<String> projectKeys = request.getProjects();
+    List<String> projectKeys = request.getProjectKeys();
     if (projectKeys != null) {
       List<ComponentDto> branchComponents = getComponentsFromKeys(session, projectKeys, request.getBranch(), request.getPullRequest());
       Set<String> projectUuids = retrieveProjectUuidsFromComponents(session, branchComponents);
@@ -348,11 +348,12 @@ public class IssueQueryFactory {
   }
 
   private void addProjectUuidsForApplication(IssueQuery.Builder builder, DbSession session, SearchRequest request) {
-    List<String> projectKeys = request.getProjects();
+    List<String> projectKeys = request.getProjectKeys();
     if (projectKeys != null) {
       // On application, branch should only be applied on the application, not on projects
-      List<ComponentDto> projects = getComponentsFromKeys(session, projectKeys, null, null);
-      builder.projectUuids(projects.stream().map(ComponentDto::uuid).collect(toList()));
+      List<ComponentDto> appBranchComponents = getComponentsFromKeys(session, projectKeys, null, null);
+      Set<String> appUuids = retrieveProjectUuidsFromComponents(session, appBranchComponents);
+      builder.projectUuids(appUuids);
     }
   }
 
@@ -367,26 +368,26 @@ public class IssueQueryFactory {
     builder.viewUuids(filteredViewUuids);
   }
 
-  private void addApplications(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> applications, SearchRequest request) {
-    Set<String> authorizedApplicationUuids = applications.stream()
+  private void addApplications(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> appBranchComponents, SearchRequest request) {
+    Set<String> authorizedAppBranchUuids = appBranchComponents.stream()
       .filter(app -> userSession.hasComponentPermission(USER, app) && userSession.hasChildProjectsPermission(USER, app))
       .map(ComponentDto::uuid)
       .collect(toSet());
 
-    builder.viewUuids(authorizedApplicationUuids.isEmpty() ? singleton(UNKNOWN) : authorizedApplicationUuids);
-    addCreatedAfterByProjects(builder, dbSession, request, authorizedApplicationUuids);
+    builder.viewUuids(authorizedAppBranchUuids.isEmpty() ? singleton(UNKNOWN) : authorizedAppBranchUuids);
+    addCreatedAfterByProjects(builder, dbSession, request, authorizedAppBranchUuids);
   }
 
-  private void addCreatedAfterByProjects(IssueQuery.Builder builder, DbSession dbSession, SearchRequest request, Set<String> applicationUuids) {
+  private void addCreatedAfterByProjects(IssueQuery.Builder builder, DbSession dbSession, SearchRequest request, Set<String> appBranchUuids) {
     if (notInNewCodePeriod(request) || request.getPullRequest() != null) {
       return;
     }
 
-    Set<String> projectUuids = applicationUuids.stream()
-      .flatMap(app -> dbClient.componentDao().selectProjectsFromView(dbSession, app, app).stream())
+    Set<String> projectBranchUuids = appBranchUuids.stream()
+      .flatMap(app -> dbClient.componentDao().selectProjectBranchUuidsFromView(dbSession, app, app).stream())
       .collect(toSet());
 
-    List<SnapshotDto> snapshots = getLastAnalysis(dbSession, projectUuids);
+    List<SnapshotDto> snapshots = getLastAnalysis(dbSession, projectBranchUuids);
 
     Set<String> newCodeReferenceByProjects = snapshots
       .stream()
index 32eab8af7f24a7d8be2ed4d959e948fabdf09cef..3fc534a420a00c8464313eadd99f68a2adb9e196 100644 (file)
@@ -170,18 +170,18 @@ public class PermissionIndexer implements ProjectIndexer {
     bulkIndexers.forEach(BulkIndexer::start);
 
     PermissionIndexerDao permissionIndexerDao = new PermissionIndexerDao();
-    Set<String> remainingProjectUuids = items.stream().map(EsQueueDto::getDocId)
-      .map(AuthorizationDoc::projectUuidOf)
+    Set<String> remainingEntityUuids = items.stream().map(EsQueueDto::getDocId)
+      .map(AuthorizationDoc::entityUuidOf)
       .collect(MoreCollectors.toHashSet());
-    permissionIndexerDao.selectByUuids(dbClient, dbSession, remainingProjectUuids).forEach(p -> {
-      remainingProjectUuids.remove(p.getProjectUuid());
+    permissionIndexerDao.selectByUuids(dbClient, dbSession, remainingEntityUuids).forEach(p -> {
+      remainingEntityUuids.remove(p.getEntityUuid());
       bulkIndexers.forEach(bi -> bi.add(AuthorizationDoc.fromDto(bi.getIndexType(), p).toIndexRequest()));
     });
 
-    // the remaining references on projects that don't exist in db. They must
+    // the remaining references on entities that don't exist in db. They must
     // be deleted from index.
-    remainingProjectUuids.forEach(projectUuid -> bulkIndexers.forEach(bi -> {
-      String authorizationDocId = AuthorizationDoc.idOf(projectUuid);
+    remainingEntityUuids.forEach(entityUuid -> bulkIndexers.forEach(bi -> {
+      String authorizationDocId = AuthorizationDoc.idOf(entityUuid);
       bi.addDeletion(bi.getIndexType(), authorizationDocId, authorizationDocId);
     }));
 
index 9c6f173365f698c4fef0a34c9b78c9afd8945583..6ad3277147838e74a251bcea07350a9300c6bd74 100644 (file)
@@ -852,7 +852,7 @@ public class IssueIndexFiltersTest extends IssueIndexTestCommon {
     assertThatSearchReturnsOnly(IssueQuery.builder().codeVariants(singletonList("variant2")), "I1", "I2");
   }
 
-  private void indexView(String viewUuid, List<String> projects) {
-    viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjects(projects));
+  private void indexView(String viewUuid, List<String> projectBranchUuids) {
+    viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjectBranchUuids(projectBranchUuids));
   }
 }
index 657622b5d9e6d5e036474334a54d3092b59088ba..c150e3126a33812824851a88f3ec19bde5d1384f 100644 (file)
@@ -735,8 +735,8 @@ public class IssueIndexSecurityReportsTest extends IssueIndexTestCommon {
     return statistics.getChildren().stream().filter(stat -> stat.getCategory().equals(cweId)).findAny().orElse(null);
   }
 
-  private void indexView(String viewUuid, List<String> projects) {
-    viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjects(projects));
+  private void indexView(String viewUuid, List<String> projectBranchUuids) {
+    viewIndexer.index(new ViewDoc().setUuid(viewUuid).setProjectBranchUuids(projectBranchUuids));
   }
 
 }
index d74539ba182b60db53cb2b491e8d05d84041fed6..fbd161d712e9ddf96cac7298afc3045b2eb02148 100644 (file)
@@ -36,7 +36,6 @@ import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ProjectData;
 import org.sonar.db.component.SnapshotDto;
 import org.sonar.db.metric.MetricDto;
-import org.sonar.db.project.ProjectDto;
 import org.sonar.db.rule.RuleDbTester;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
@@ -94,7 +93,7 @@ public class IssueQueryFactoryTest {
       .setStatuses(asList("CLOSED"))
       .setResolutions(asList("FALSE-POSITIVE"))
       .setResolved(true)
-      .setProjects(asList(project.getKey()))
+      .setProjectKeys(asList(project.getKey()))
       .setDirectories(asList("aDirPath"))
       .setFiles(asList(file.uuid()))
       .setAssigneesUuid(asList(user.getUuid()))
@@ -255,7 +254,7 @@ public class IssueQueryFactoryTest {
   @Test
   public void add_unknown_when_no_component_found() {
     SearchRequest request = new SearchRequest()
-      .setComponents(asList("does_not_exist"));
+      .setComponentKeys(asList("does_not_exist"));
 
     IssueQuery query = underTest.create(request);
 
@@ -279,7 +278,7 @@ public class IssueQueryFactoryTest {
   @Test
   public void fail_if_components_and_components_uuid_params_are_set_at_the_same_time() {
     SearchRequest request = new SearchRequest()
-      .setComponents(singletonList("foo"))
+      .setComponentKeys(singletonList("foo"))
       .setComponentUuids(singletonList("bar"));
 
     assertThatThrownBy(() -> underTest.create(request))
@@ -407,7 +406,7 @@ public class IssueQueryFactoryTest {
   public void onComponentOnly_restricts_search_to_specified_componentKeys() {
     ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
     SearchRequest request = new SearchRequest()
-      .setComponents(asList(project.getKey()))
+      .setComponentKeys(asList(project.getKey()))
       .setOnComponentOnly(true);
 
     IssueQuery query = underTest.create(request);
@@ -461,13 +460,13 @@ public class IssueQueryFactoryTest {
     ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
 
     assertThat(underTest.create(new SearchRequest()
-      .setProjects(singletonList(branch.getKey()))
+      .setProjectKeys(singletonList(branch.getKey()))
       .setBranch(branchName)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(branch.uuid(), singletonList(project.uuid()), false);
 
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(branch.getKey()))
+      .setComponentKeys(singletonList(branch.getKey()))
       .setBranch(branchName)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(branch.uuid(), singletonList(project.uuid()), false);
@@ -481,20 +480,20 @@ public class IssueQueryFactoryTest {
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
 
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(file.getKey()))
+      .setComponentKeys(singletonList(file.getKey()))
       .setBranch(branchName)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch)
       .containsOnly(branch.uuid(), singletonList(file.uuid()), false);
 
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(branch.getKey()))
+      .setComponentKeys(singletonList(branch.getKey()))
       .setFiles(singletonList(file.path()))
       .setBranch(branchName)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch)
       .containsOnly(branch.uuid(), singletonList(file.path()), false);
 
     assertThat(underTest.create(new SearchRequest()
-      .setProjects(singletonList(branch.getKey()))
+      .setProjectKeys(singletonList(branch.getKey()))
       .setFiles(singletonList(file.path()))
       .setBranch(branchName)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch)
@@ -509,7 +508,7 @@ public class IssueQueryFactoryTest {
     ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
 
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(file.getKey()))
+      .setComponentKeys(singletonList(file.getKey()))
       .setBranch(branchName)
       .setOnComponentOnly(true)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch)
@@ -522,12 +521,12 @@ public class IssueQueryFactoryTest {
     db.components().insertProjectBranch(project);
 
     assertThat(underTest.create(new SearchRequest()
-      .setProjects(singletonList(project.getKey()))
+      .setProjectKeys(singletonList(project.getKey()))
       .setBranch(DEFAULT_MAIN_BRANCH_NAME)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(project.uuid(), singletonList(project.uuid()), true);
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(project.getKey()))
+      .setComponentKeys(singletonList(project.getKey()))
       .setBranch(DEFAULT_MAIN_BRANCH_NAME)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(project.uuid(), singletonList(project.uuid()), true);
@@ -550,7 +549,7 @@ public class IssueQueryFactoryTest {
       .addProjectPermission(USER, projectData2.getProjectDto());
 
     assertThat(underTest.create(new SearchRequest()
-        .setComponents(singletonList(application.getKey())))
+        .setComponentKeys(singletonList(application.getKey())))
       .viewUuids()).containsExactly(application.uuid());
   }
 
@@ -572,15 +571,15 @@ public class IssueQueryFactoryTest {
 
     // Search on applicationBranch1
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(applicationBranch1.getKey()))
+      .setComponentKeys(singletonList(applicationBranch1.getKey()))
       .setBranch(branchName1)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(applicationBranch1.uuid(), Collections.emptyList(), false);
 
     // Search on project1Branch1
     assertThat(underTest.create(new SearchRequest()
-      .setComponents(singletonList(applicationBranch1.getKey()))
-      .setProjects(singletonList(project1.getKey()))
+      .setComponentKeys(singletonList(applicationBranch1.getKey()))
+      .setProjectKeys(singletonList(project1.getKey()))
       .setBranch(branchName1)))
       .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch)
       .containsOnly(applicationBranch1.uuid(), singletonList(project1.uuid()), false);
@@ -657,7 +656,7 @@ public class IssueQueryFactoryTest {
 
     SearchRequest searchRequest = new SearchRequest()
       .setInNewCodePeriod(true)
-      .setComponents(asList(project1.getKey(), project2.getKey()));
+      .setComponentKeys(asList(project1.getKey(), project2.getKey()));
 
     assertThatThrownBy(() -> underTest.create(searchRequest))
       .isInstanceOf(IllegalArgumentException.class)
index abc0453fa77ccb25b9d3219a856116cf551cc250..ba24933e1f09cc4fbcdedfa81f853b63322fcdaf 100644 (file)
@@ -43,8 +43,8 @@ public class PermissionIndexerTester {
     return allow(stream(projects).map(project -> new IndexPermissions(project.uuid(), project.qualifier()).allowAnyone()).toList());
   }
 
-  public PermissionIndexerTester allowOnlyAnyone(ProjectDto... projects) {
-    return allow(stream(projects).map(project -> new IndexPermissions(project.getUuid(), project.getQualifier()).allowAnyone()).toList());
+  public PermissionIndexerTester allowOnlyAnyone(EntityDto... entities) {
+    return allow(stream(entities).map(entity -> new IndexPermissions(entity.getUuid(), entity.getQualifier()).allowAnyone()).toList());
   }
 
   public PermissionIndexerTester allowOnlyUser(ComponentDto project, UserDto user) {
index 9f01bc411cdb375d06a9fa9c7c57b8e35883937e..05b3efeb77912eaf2bdc104174e5a8597c79ce6a 100644 (file)
@@ -35,6 +35,7 @@ import org.sonar.db.DbTester;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
 import org.sonar.db.issue.IssueDto;
 import org.sonar.db.project.ProjectDto;
 import org.sonar.db.pushevent.PushEventDto;
@@ -58,90 +59,86 @@ import static org.sonarqube.ws.Common.Severity.MAJOR;
 public class IssueChangeEventServiceImplTest {
 
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
 
   public final IssueChangeEventServiceImpl underTest = new IssueChangeEventServiceImpl(db.getDbClient());
 
   @Test
   public void distributeIssueChangeEvent_whenSingleIssueChange_shouldChangeSeverity() {
-    ComponentDto componentDto = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto.uuid()).get();
-    BranchDto branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.getUuid()).get();
+    ProjectData projectData = db.components().insertPublicProject();
     RuleDto rule = db.rules().insert();
-    IssueDto issue = db.issues().insert(rule, project, componentDto, i -> i.setSeverity(MAJOR.name()));
+    IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name()));
 
-    assertPushEventIsPersisted(project, branch, issue, BLOCKER.name(), null, null, null, 1);
+    assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, BLOCKER.name(), null, null, null, 1);
   }
 
   @Test
   public void distributeIssueChangeEvent_whenSingleIssueChange_shouldChangeType() {
-    ComponentDto componentDto = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto.uuid()).get();
-    BranchDto branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.getUuid()).get();
+    ProjectData projectData = db.components().insertPublicProject();
     RuleDto rule = db.rules().insert();
-    IssueDto issue = db.issues().insert(rule, project, componentDto, i -> i.setSeverity(MAJOR.name()));
+    IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name()));
 
-    assertPushEventIsPersisted(project, branch, issue, null, Common.RuleType.BUG.name(), null, null, 1);
+    assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, null, Common.RuleType.BUG.name(), null, null, 1);
   }
 
   @Test
   public void distributeIssueChangeEvent_whenSingleIssueChange_shouldExecuteTransitionChanges() {
-    ComponentDto componentDto = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto.uuid()).get();
-    BranchDto branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.getUuid()).get();
+    ProjectData projectData = db.components().insertPublicProject();
+    ProjectDto project = projectData.getProjectDto();
+    BranchDto mainBranch = projectData.getMainBranchDto();
     RuleDto rule = db.rules().insert();
-    IssueDto issue = db.issues().insert(rule, project, componentDto, i -> i.setSeverity(MAJOR.name()));
-
-    assertPushEventIsPersisted(project, branch, issue, null, null, WONT_FIX, true, 1);
-    assertPushEventIsPersisted(project, branch, issue, null, null, REOPEN, false, 2);
-    assertPushEventIsPersisted(project, branch, issue, null, null, FALSE_POSITIVE, true, 3);
-    assertPushEventIsPersisted(project, branch, issue, null, null, REOPEN, false, 4);
-    assertPushEventIsPersisted(project, branch, issue, null, null, RESOLVE, false, 5);
-    assertPushEventIsPersisted(project, branch, issue, null, null, REOPEN, false, 6);
-    assertNoIssueDistribution(project, branch, issue, null, null, CONFIRM, 7);
-    assertNoIssueDistribution(project, branch, issue, null, null, UNCONFIRM, 8);
+    IssueDto issue = db.issues().insert(rule, mainBranch, projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name()));
+
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, WONT_FIX, true, 1);
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 2);
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, FALSE_POSITIVE, true, 3);
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 4);
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, RESOLVE, false, 5);
+    assertPushEventIsPersisted(project, mainBranch, issue, null, null, REOPEN, false, 6);
+    assertNoIssueDistribution(project, mainBranch, issue, null, null, CONFIRM, 7);
+    assertNoIssueDistribution(project, mainBranch, issue, null, null, UNCONFIRM, 8);
   }
 
   @Test
   public void distributeIssueChangeEvent_whenSingleIssueChangeOnABranch_shouldChangeSeverity() {
-    ComponentDto componentDto = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto.uuid()).get();
-    BranchDto featureBranch = db.components().insertProjectBranch(project, b -> b.setKey("feature1"));
+    ProjectData projectData = db.components().insertPublicProject();
+    BranchDto featureBranch = db.components().insertProjectBranch(projectData.getProjectDto(), b -> b.setKey("feature1"));
     ComponentDto branchComponent = db.components().insertFile(featureBranch);
     RuleDto rule = db.rules().insert();
-    IssueDto issue = db.issues().insert(rule, project, branchComponent, i -> i.setSeverity(MAJOR.name()));
-    assertPushEventIsPersisted(project, featureBranch, issue, BLOCKER.name(), null, null, null, 1);
+    IssueDto issue = db.issues().insert(rule, featureBranch, branchComponent, i -> i.setSeverity(MAJOR.name()));
+    assertPushEventIsPersisted(projectData.getProjectDto(), featureBranch, issue, BLOCKER.name(), null, null, null, 1);
   }
 
   @Test
   public void distributeIssueChangeEvent_whenSingleIssueChange_shouldExecuteSeveralChanges() {
-    ComponentDto componentDto = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto.uuid()).get();
-    BranchDto branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.getUuid()).get();
+    ProjectData projectData = db.components().insertPublicProject();
     RuleDto rule = db.rules().insert();
-    IssueDto issue = db.issues().insert(rule, project, componentDto, i -> i.setSeverity(MAJOR.name()));
+    IssueDto issue = db.issues().insert(rule, projectData.getMainBranchDto(), projectData.getMainBranchComponent(), i -> i.setSeverity(MAJOR.name()));
 
-    assertPushEventIsPersisted(project, branch, issue, BLOCKER.name(), Common.RuleType.BUG.name(), WONT_FIX, true, 1);
+    assertPushEventIsPersisted(projectData.getProjectDto(), projectData.getMainBranchDto(), issue, BLOCKER.name(), Common.RuleType.BUG.name(), WONT_FIX, true, 1);
   }
 
   @Test
   public void distributeIssueChangeEvent_whenBulkIssueChange_shouldDistributesEvents() {
     RuleDto rule = db.rules().insert();
 
-    ComponentDto componentDto1 = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project1 = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto1.uuid()).get();
-    BranchDto branch1 = db.getDbClient().branchDao().selectByUuid(db.getSession(), project1.getUuid()).get();
-    IssueDto issue1 = db.issues().insert(rule, project1, componentDto1, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
+    ProjectData projectData1 = db.components().insertPublicProject();
+    ProjectDto project1 = projectData1.getProjectDto();
+    BranchDto branch1 = projectData1.getMainBranchDto();
+    ComponentDto componentDto1 = projectData1.getMainBranchComponent();
+    IssueDto issue1 = db.issues().insert(rule, branch1, componentDto1, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
 
-    ComponentDto componentDto2 = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project2 = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto2.uuid()).get();
-    BranchDto branch2 = db.getDbClient().branchDao().selectByUuid(db.getSession(), project2.getUuid()).get();
-    IssueDto issue2 = db.issues().insert(rule, project2, componentDto2, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
+    ProjectData projectData2 = db.components().insertPublicProject();
+    ProjectDto project2 = projectData2.getProjectDto();
+    BranchDto branch2 = projectData2.getMainBranchDto();
+    ComponentDto componentDto2 = projectData2.getMainBranchComponent();
+    IssueDto issue2 = db.issues().insert(rule, branch2, componentDto2, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
 
-    ComponentDto componentDto3 = db.components().insertPublicProject().getMainBranchComponent();
-    ProjectDto project3 = db.getDbClient().projectDao().selectByUuid(db.getSession(), componentDto3.uuid()).get();
-    BranchDto branch3 = db.getDbClient().branchDao().selectByUuid(db.getSession(), project3.getUuid()).get();
-    IssueDto issue3 = db.issues().insert(rule, project3, componentDto3, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
+    ProjectData projectData3 = db.components().insertPublicProject();
+    ProjectDto project3 = projectData3.getProjectDto();
+    BranchDto branch3 = projectData3.getMainBranchDto();
+    ComponentDto componentDto3 = projectData3.getMainBranchComponent();
+    IssueDto issue3 = db.issues().insert(rule, branch3, componentDto3, i -> i.setSeverity(MAJOR.name()).setType(RuleType.BUG));
 
     DefaultIssue defaultIssue1 = issue1.toDefaultIssue().setCurrentChangeWithoutAddChange(new FieldDiffs()
       .setDiff("resolution", null, null)
@@ -256,7 +253,6 @@ public class IssueChangeEventServiceImplTest {
     if (resolved != null) {
       assertThat(payload).contains("\"resolved\":" + resolved);
     }
-
   }
 
 }
index e9f7ce8169dc12d76cb971bb55748d2d761c43d6..dd9675acce917a59c6f3aca07d5b50525b6257a9 100644 (file)
@@ -58,7 +58,7 @@ public class LoginActionIT {
   private static final String PASSWORD = "PASSWORD";
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
 
   private final DbClient dbClient = dbTester.getDbClient();
 
index cb83c6620c2f3a0e8d8ecee0d1182cd139799fdd..fe7e36f333fb0f820bdb4d10e0702c1c5e681e80 100644 (file)
@@ -113,7 +113,7 @@ public class ListActionIT {
     db.measures().insertLiveMeasure(branch, qualityGateStatus, m -> m.setData("OK"));
 
     RuleDto rule = db.rules().insert();
-    db.issues().insert(rule, project, db.components().getComponentDto(branch), i -> i.setType(BUG).setResolution(null));
+    db.issues().insert(rule, branch, db.components().getComponentDto(branch), i -> i.setType(BUG).setResolution(null));
 
     indexIssues();
 
@@ -143,7 +143,7 @@ public class ListActionIT {
     db.measures().insertLiveMeasure(branch, qualityGateStatus, m -> m.setData("OK"));
 
     RuleDto rule = db.rules().insert();
-    db.issues().insert(rule, project, db.components().getComponentDto(branch), i -> i.setType(BUG).setResolution(null));
+    db.issues().insert(rule, branch, db.components().getComponentDto(branch), i -> i.setType(BUG).setResolution(null));
     indexIssues();
 
     userSession.logIn().addProjectPermission(SCAN.getKey(), project);
index 29c17d9eea5acec786546ebf40e2f32248388dba..4590889a6788bf6bc4b367c7a2b781e603dbc5e6 100644 (file)
@@ -111,7 +111,6 @@ public class ComponentCleanerServiceIT {
       .isInstanceOf(IllegalArgumentException.class);
   }
 
-
   @Test
   public void delete_application_from_db_and_index() {
     DbData data1 = insertProjectData();
@@ -182,7 +181,6 @@ public class ComponentCleanerServiceIT {
     assertExists(data3);
   }
 
-
   @Test
   public void delete_webhooks_from_projects() {
     ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
@@ -247,8 +245,7 @@ public class ComponentCleanerServiceIT {
 
   private void assertProjectOrAppExists(ProjectDto appOrProject, BranchDto branch, boolean exists) {
     assertThat(dbClient.projectDao().selectByUuid(dbSession, appOrProject.getUuid()).isPresent()).isEqualTo(exists);
-    assertThat(dbClient.componentDao().selectByUuid(dbSession, branch.getUuid()).isPresent()).isEqualTo(exists);
-    assertThat(dbClient.branchDao().selectByUuid(dbSession, branch.getUuid()).isPresent()).isEqualTo(exists);
+    assertThat(dbClient.branchDao().selectByProject(dbSession, appOrProject).isEmpty()).isEqualTo(!exists);
   }
 
   private void assertNotExists(ComponentDto componentDto) {
index 3b3af2c90dd58b6f36db85a5da50a015b41d9e47..e9d88885b27dcf471b9e84e6212b966275593ca9 100644 (file)
@@ -52,7 +52,8 @@ public class ComponentServiceUpdateKeyIT {
   @Rule
   public final UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public final DbTester db = DbTester.create(system2);
+  public final DbTester db = DbTester.create(system2, true);
+
   private DbClient dbClient = db.getDbClient();
   private DbSession dbSession = db.getSession();
   private TestProjectIndexers projectIndexers = new TestProjectIndexers();
@@ -61,14 +62,15 @@ public class ComponentServiceUpdateKeyIT {
 
   @Test
   public void update_project_key() {
-    ComponentDto project = insertSampleProject();
-    ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project).setKey("sample:root:src/File.xoo"));
-    ComponentDto inactiveFile = db.components().insertComponent(ComponentTesting.newFileDto(project).setKey("sample:root:src/InactiveFile.xoo").setEnabled(false));
+    ProjectDto project = insertSampleProject();
+    ComponentDto mainBranchComponent = db.components().getComponentDto(project);
+    ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(mainBranchComponent).setKey("sample:root:src/File.xoo"));
+    ComponentDto inactiveFile = db.components().insertComponent(ComponentTesting.newFileDto(mainBranchComponent).setKey("sample:root:src/InactiveFile.xoo").setEnabled(false));
 
     dbSession.commit();
 
     logInAsProjectAdministrator(project);
-    underTest.updateKey(dbSession, db.components().getProjectDtoByMainBranch(project), "sample2:root");
+    underTest.updateKey(dbSession, project, "sample2:root");
     dbSession.commit();
 
     // Check project key has been updated
@@ -82,13 +84,13 @@ public class ComponentServiceUpdateKeyIT {
 
     assertThat(dbClient.componentDao().selectByKey(dbSession, inactiveFile.getKey())).isEmpty();
 
-    assertThat(projectIndexers.hasBeenCalled(project.uuid(), ProjectIndexer.Cause.PROJECT_KEY_UPDATE)).isTrue();
+    assertThat(projectIndexers.hasBeenCalled(project.getUuid(), ProjectIndexer.Cause.PROJECT_KEY_UPDATE)).isTrue();
 
-    Deque<PushEventDto> pushEvents = db.getDbClient().pushEventDao().selectChunkByProjectUuids(dbSession, Set.of(project.uuid()), 0L, "id", 20);
+    Deque<PushEventDto> pushEvents = db.getDbClient().pushEventDao().selectChunkByProjectUuids(dbSession, Set.of(project.getUuid()), 0L, "id", 20);
 
     assertThat(pushEvents).isNotEmpty();
 
-    Optional<PushEventDto> event = pushEvents.stream().filter(e -> e.getProjectUuid().equals(project.uuid()) && e.getName().equals("ProjectKeyChanged")).findFirst();
+    Optional<PushEventDto> event = pushEvents.stream().filter(e -> e.getProjectUuid().equals(project.getUuid()) && e.getName().equals("ProjectKeyChanged")).findFirst();
     assertThat(event).isNotEmpty();
 
     String payload = new String(event.get().getPayload(), StandardCharsets.UTF_8);
@@ -98,37 +100,35 @@ public class ComponentServiceUpdateKeyIT {
 
   @Test
   public void update_provisioned_project_key() {
-    ComponentDto provisionedProject = insertProject("provisionedProject");
+    ProjectDto provisionedProject = insertProject("provisionedProject");
 
     dbSession.commit();
 
     logInAsProjectAdministrator(provisionedProject);
-    underTest.updateKey(dbSession, db.components().getProjectDtoByMainBranch(provisionedProject), "provisionedProject2");
+    underTest.updateKey(dbSession, provisionedProject, "provisionedProject2");
     dbSession.commit();
 
     assertComponentKeyHasBeenUpdated(provisionedProject.getKey(), "provisionedProject2");
-    assertThat(projectIndexers.hasBeenCalled(provisionedProject.uuid(), ProjectIndexer.Cause.PROJECT_KEY_UPDATE)).isTrue();
+    assertThat(projectIndexers.hasBeenCalled(provisionedProject.getUuid(), ProjectIndexer.Cause.PROJECT_KEY_UPDATE)).isTrue();
   }
 
   @Test
   public void fail_to_update_project_key_without_admin_permission() {
-    ComponentDto project = insertSampleProject();
+    ProjectDto project = insertSampleProject();
     userSession.logIn("john").addProjectPermission(UserRole.USER, project);
 
-    ProjectDto projectDto = db.components().getProjectDtoByMainBranch(project);
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, projectDto, "sample2:root"))
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, project, "sample2:root"))
       .isInstanceOf(ForbiddenException.class);
   }
 
   @Test
   public void fail_if_old_key_and_new_key_are_the_same() {
-    ComponentDto project = insertSampleProject();
+    ProjectDto project = insertSampleProject();
     ComponentDto anotherProject = db.components().insertPrivateProject().getMainBranchComponent();
     logInAsProjectAdministrator(project);
 
-    ProjectDto projectDto = db.components().getProjectDtoByMainBranch(project);
     String anotherProjectDbKey = anotherProject.getKey();
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, projectDto,
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, project,
       anotherProjectDbKey))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("Impossible to update key: a component with key \"" + anotherProjectDbKey + "\" already exists.");
@@ -136,32 +136,30 @@ public class ComponentServiceUpdateKeyIT {
 
   @Test
   public void fail_if_new_key_is_empty() {
-    ComponentDto project = insertSampleProject();
+    ProjectDto project = insertSampleProject();
     logInAsProjectAdministrator(project);
 
-    ProjectDto projectDto = db.components().getProjectDtoByMainBranch(project);
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, projectDto, ""))
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, project, ""))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("Malformed key for ''. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
   }
 
   @Test
   public void fail_if_new_key_is_not_formatted_correctly() {
-    ComponentDto project = insertSampleProject();
+    ProjectDto project = insertSampleProject();
     logInAsProjectAdministrator(project);
 
-    ProjectDto projectDto = db.components().getProjectDtoByMainBranch(project);
-    assertThatThrownBy(() -> underTest.updateKey(dbSession, projectDto, "sample?root"))
+    assertThatThrownBy(() -> underTest.updateKey(dbSession, project, "sample?root"))
       .isInstanceOf(IllegalArgumentException.class)
       .hasMessage("Malformed key for 'sample?root'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
   }
 
-  private ComponentDto insertSampleProject() {
+  private ProjectDto insertSampleProject() {
     return insertProject("sample:root");
   }
 
-  private ComponentDto insertProject(String key) {
-    return db.components().insertPrivateProject(c -> c.setKey(key)).getMainBranchComponent();
+  private ProjectDto insertProject(String key) {
+    return db.components().insertPrivateProject(c -> c.setKey(key)).getProjectDto();
   }
 
   private void assertComponentKeyHasBeenUpdated(String oldKey, String newKey) {
@@ -169,7 +167,7 @@ public class ComponentServiceUpdateKeyIT {
     assertThat(dbClient.componentDao().selectByKey(dbSession, newKey)).isPresent();
   }
 
-  private void logInAsProjectAdministrator(ComponentDto provisionedProject) {
+  private void logInAsProjectAdministrator(ProjectDto provisionedProject) {
     userSession.logIn("john").addProjectPermission(UserRole.ADMIN, provisionedProject);
   }
 }
index 7f5f410e4616fd349a59eb819f28ac345f319847..854e097b1141dac382b68d2dc0b1c700d8165469 100644 (file)
@@ -67,7 +67,7 @@ public class ComponentUpdaterIT {
   private final System2 system2 = System2.INSTANCE;
 
   @Rule
-  public final DbTester db = DbTester.create(system2);
+  public final DbTester db = DbTester.create(system2, true);
   @Rule
   public final I18nRule i18n = new I18nRule().put("qualifier.TRK", "Project");
 
index e112df8b1b8c2fef3cb34eb5c6b76e288c40fa89..1800a26da9d03df5261f15b1c3da7282a1a3f5af 100644 (file)
 package org.sonar.server.component.ws;
 
 import org.apache.commons.lang.RandomStringUtils;
+import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.db.DbTester;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
 import org.sonar.db.metric.MetricDto;
 import org.sonar.db.project.ProjectDto;
 import org.sonar.server.component.TestComponentFinder;
@@ -54,19 +57,24 @@ public class AppActionIT {
   @Rule
   public final UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public final DbTester db = DbTester.create();
+  public final DbTester db = DbTester.create(true);
 
   private final ComponentViewerJsonWriter componentViewerJsonWriter = new ComponentViewerJsonWriter(db.getDbClient());
-
   private final WsActionTester ws = new WsActionTester(new AppAction(db.getDbClient(), userSession,
     TestComponentFinder.from(db), componentViewerJsonWriter));
+  private ProjectData projectData;
+  private ComponentDto mainBranchComponent;
 
+  @Before
+  public void setup() {
+    projectData = db.components().insertPrivateProject();
+    mainBranchComponent = projectData.getMainBranchComponent();
+  }
   @Test
   public void file_info() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
-    ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
-    userSession.logIn("john").addProjectPermission(USER, project);
+    ComponentDto directory = db.components().insertComponent(newDirectory(mainBranchComponent, "src"));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent, directory));
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -80,8 +88,8 @@ public class AppActionIT {
       "  \"name\": \"" + file.name() + "\",\n" +
       "  \"longName\": \"" + file.longName() + "\",\n" +
       "  \"q\": \"" + file.qualifier() + "\",\n" +
-      "  \"project\": \"" + project.getKey() + "\",\n" +
-      "  \"projectName\": \"" + project.longName() + "\",\n" +
+      "  \"project\": \"" + projectData.getProjectDto().getKey() + "\",\n" +
+      "  \"projectName\": \"" + projectData.getProjectDto().getName() + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
       "  \"measures\": {}\n" +
@@ -90,10 +98,9 @@ public class AppActionIT {
 
   @Test
   public void file_on_module() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
-    ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
-    userSession.logIn("john").addProjectPermission(USER, project);
+    ComponentDto directory = db.components().insertComponent(newDirectory(mainBranchComponent, "src"));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent, directory));
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -107,8 +114,8 @@ public class AppActionIT {
       "  \"name\": \"" + file.name() + "\",\n" +
       "  \"longName\": \"" + file.longName() + "\",\n" +
       "  \"q\": \"" + file.qualifier() + "\",\n" +
-      "  \"project\": \"" + project.getKey() + "\",\n" +
-      "  \"projectName\": \"" + project.longName() + "\",\n" +
+      "  \"project\": \"" + projectData.getProjectDto().getKey() + "\",\n" +
+      "  \"projectName\": \"" + projectData.getProjectDto().getName() + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
       "  \"measures\": {}\n" +
@@ -117,9 +124,8 @@ public class AppActionIT {
 
   @Test
   public void file_without_measures() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = db.components().insertComponent(newFileDto(project));
-    userSession.logIn("john").addProjectPermission(USER, project);
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent));
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -133,9 +139,8 @@ public class AppActionIT {
 
   @Test
   public void file_with_measures() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
-    ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
+    ComponentDto directory = db.components().insertComponent(newDirectory(mainBranchComponent, "src"));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent, directory));
     MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
     db.measures().insertLiveMeasure(file, lines, m -> m.setValue(200d));
     MetricDto duplicatedLines = db.measures().insertMetric(m -> m.setKey(DUPLICATED_LINES_DENSITY_KEY));
@@ -148,7 +153,7 @@ public class AppActionIT {
     db.measures().insertLiveMeasure(file, issues, m -> m.setValue(231d));
     MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
     db.measures().insertLiveMeasure(file, coverage, m -> m.setValue(95.4d));
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -168,11 +173,10 @@ public class AppActionIT {
 
   @Test
   public void get_by_component() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = db.components().insertComponent(newFileDto(project, project));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent, mainBranchComponent));
     MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
     db.measures().insertLiveMeasure(file, coverage, m -> m.setValue(95.4d));
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -190,11 +194,10 @@ public class AppActionIT {
 
   @Test
   public void canMarkAsFavorite_is_true_when_logged() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
-      .setParam("component", project.getKey())
+      .setParam("component", mainBranchComponent.getKey())
       .execute()
       .getInput();
 
@@ -205,11 +208,10 @@ public class AppActionIT {
 
   @Test
   public void canMarkAsFavorite_is_false_when_not_logged() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.addProjectPermission(USER, project);
+    userSession.addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
-      .setParam("component", project.getKey())
+      .setParam("component", mainBranchComponent.getKey())
       .execute()
       .getInput();
 
@@ -220,8 +222,11 @@ public class AppActionIT {
 
   @Test
   public void component_is_favorite() {
-    ProjectDto project = db.components().insertPrivateProject().getProjectDto();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    BranchDto mainBranch = projectData.getMainBranchDto();
+    ProjectDto project = projectData.getProjectDto();
+    userSession.logIn("john")
+      .addProjectPermission(USER, project)
+      .registerBranches(mainBranch);
     db.favorites().add(project, userSession.getUuid(), userSession.getLogin());
 
     String result = ws.newRequest()
@@ -236,11 +241,10 @@ public class AppActionIT {
 
   @Test
   public void component_is_not_favorite() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
 
     String result = ws.newRequest()
-      .setParam("component", project.getKey())
+      .setParam("component", mainBranchComponent.getKey())
       .execute()
       .getInput();
 
@@ -251,13 +255,12 @@ public class AppActionIT {
 
   @Test
   public void branch() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
     String branchName = randomAlphanumeric(248);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
-    userSession.addProjectBranchMapping(project.uuid(), branch);
+    ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(mainBranchComponent.uuid(), branch);
     ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src"));
-    ComponentDto file = db.components().insertComponent(newFileDto(project.uuid(), branch, directory));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent.uuid(), branch, directory));
     MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
     db.measures().insertLiveMeasure(file, coverage, m -> m.setValue(95.4d));
 
@@ -275,8 +278,8 @@ public class AppActionIT {
       "  \"name\": \"" + file.name() + "\",\n" +
       "  \"longName\": \"" + file.longName() + "\",\n" +
       "  \"q\": \"" + file.qualifier() + "\",\n" +
-      "  \"project\": \"" + project.getKey() + "\",\n" +
-      "  \"projectName\": \"" + project.longName() + "\",\n" +
+      "  \"project\": \"" + projectData.getProjectDto().getKey() + "\",\n" +
+      "  \"projectName\": \"" + projectData.getProjectDto().getName() + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
       "  \"measures\": {\n" +
@@ -295,12 +298,11 @@ public class AppActionIT {
 
   @Test
   public void component_and_branch_parameters_provided() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
     String branchName = randomAlphanumeric(248);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
-    userSession.addProjectBranchMapping(project.uuid(), branch);
-    ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
+    ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
+    userSession.addProjectBranchMapping(mainBranchComponent.uuid(), branch);
+    ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -316,8 +318,8 @@ public class AppActionIT {
       "  \"name\": \"" + file.name() + "\",\n" +
       "  \"longName\": \"" + file.longName() + "\",\n" +
       "  \"q\": \"" + file.qualifier() + "\",\n" +
-      "  \"project\": \"" + project.getKey() + "\",\n" +
-      "  \"projectName\": \"" + project.longName() + "\",\n" +
+      "  \"project\": \"" + projectData.getProjectDto().getKey() + "\",\n" +
+      "  \"projectName\": \"" + projectData.getProjectDto().getName() + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
       "  \"measures\": {}\n" +
@@ -326,12 +328,11 @@ public class AppActionIT {
 
   @Test
   public void component_and_pull_request_parameters_provided() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
     String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
-    userSession.addProjectBranchMapping(project.uuid(), branch);
-    ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
+    ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
+    userSession.addProjectBranchMapping(mainBranchComponent.uuid(), branch);
+    ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
 
     String result = ws.newRequest()
       .setParam("component", file.getKey())
@@ -346,8 +347,8 @@ public class AppActionIT {
       "  \"name\": \"" + file.name() + "\",\n" +
       "  \"longName\": \"" + file.longName() + "\",\n" +
       "  \"q\": \"" + file.qualifier() + "\",\n" +
-      "  \"project\": \"" + project.getKey() + "\",\n" +
-      "  \"projectName\": \"" + project.longName() + "\",\n" +
+      "  \"project\": \"" + projectData.getProjectDto().getKey() + "\",\n" +
+      "  \"projectName\": \"" + projectData.getProjectDto().getName() + "\",\n" +
       "  \"pullRequest\": \"" + pullRequestKey + "\",\n" +
       "  \"fav\": false,\n" +
       "  \"canMarkAsFavorite\": true,\n" +
@@ -357,10 +358,9 @@ public class AppActionIT {
 
   @Test
   public void fail_if_component_and_pull_request_and_branch_parameters_provided() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    userSession.logIn("john").addProjectPermission(USER, project);
-    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST));
-    ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
+    userSession.logIn("john").addProjectPermission(USER, mainBranchComponent);
+    ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setBranchType(PULL_REQUEST));
+    ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
 
     TestRequest request = ws.newRequest()
       .setParam("component", file.getKey())
@@ -373,8 +373,7 @@ public class AppActionIT {
 
   @Test
   public void fail_when_component_not_found() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = db.components().insertComponent(newFileDto(project));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent));
 
     TestRequest request = ws.newRequest()
       .setParam("component", "unknown");
@@ -384,9 +383,8 @@ public class AppActionIT {
 
   @Test
   public void fail_when_branch_not_found() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto branch = db.components().insertProjectBranch(project);
-    ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
+    ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent);
+    ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
 
     TestRequest request = ws.newRequest()
       .setParam("component", file.getKey())
@@ -398,8 +396,7 @@ public class AppActionIT {
 
   @Test
   public void fail_when_missing_permission() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = db.components().insertComponent(newFileDto(project));
+    ComponentDto file = db.components().insertComponent(newFileDto(mainBranchComponent));
 
     TestRequest request = ws.newRequest()
       .setParam("component", file.getKey());
index d7c4fbf3585944775467a2f55972169590d53d70..de0af82b8de78d0e674fc961ce9bce38a5e510b4 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.component.ws;
 import com.google.common.base.Joiner;
 import java.util.ArrayList;
 import java.util.List;
+import org.eclipse.jface.text.projection.ProjectionDocument;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -30,7 +31,9 @@ import org.sonar.api.server.ws.WebService;
 import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
 import org.sonar.db.component.ResourceTypesRule;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.component.index.ComponentIndex;
 import org.sonar.server.component.index.ComponentIndexer;
@@ -68,7 +71,7 @@ public class SearchActionIT {
   @Rule
   public final UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public final DbTester db = DbTester.create(System2.INSTANCE);
+  public final DbTester db = DbTester.create(System2.INSTANCE, true);
   @Rule
   public final EsTester es = EsTester.create();
 
@@ -120,8 +123,8 @@ public class SearchActionIT {
 
   @Test
   public void search_by_key_query() {
-    ComponentDto p1 = db.components().insertPrivateProject(p -> p.setKey("project-_%-key")).getMainBranchComponent();
-    ComponentDto p2 = db.components().insertPrivateProject(p -> p.setKey("project-key-without-escaped-characters")).getMainBranchComponent();
+    ProjectDto p1 = db.components().insertPrivateProject(p -> p.setKey("project-_%-key")).getProjectDto();
+    ProjectDto p2 = db.components().insertPrivateProject(p -> p.setKey("project-key-without-escaped-characters")).getProjectDto();
 
     insertProjectsAuthorizedForUser(List.of(p1, p2));
     SearchWsResponse response = call(new SearchRequest().setQuery("project-_%-key").setQualifiers(singletonList(PROJECT)));
@@ -131,12 +134,12 @@ public class SearchActionIT {
 
   @Test
   public void search_with_pagination() {
-    List<ComponentDto> componentDtoList = new ArrayList<>();
+    List<ProjectDto> projectList = new ArrayList<>();
     for (int i = 1; i <= 9; i++) {
       int j = i;
-      componentDtoList.add(db.components().insertPrivateProject("project-uuid-" + j, p -> p.setKey("project-key-" + j).setName("Project Name " + j)).getMainBranchComponent());
+      projectList.add(db.components().insertPrivateProject("project-uuid-" + j, p -> p.setKey("project-key-" + j).setName("Project Name " + j)).getProjectDto());
     }
-    insertProjectsAuthorizedForUser(componentDtoList);
+    insertProjectsAuthorizedForUser(projectList);
 
     SearchWsResponse response = call(new SearchRequest().setPage(2).setPageSize(3).setQualifiers(singletonList(PROJECT)));
 
@@ -145,8 +148,8 @@ public class SearchActionIT {
 
   @Test
   public void return_only_projects_on_which_user_has_browse_permission() {
-    ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
+    ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
+    ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
     ComponentDto portfolio = db.components().insertPrivatePortfolio();
 
     setBrowsePermissionOnUserAndIndex(List.of(project1));
@@ -160,29 +163,29 @@ public class SearchActionIT {
 
   @Test
   public void return_project_key() {
-    ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
-    ComponentDto dir1 = newDirectory(project, "dir1").setKey("dir1");
-    ComponentDto dir2 = newDirectory(project, "dir2").setKey("dir2");
-    ComponentDto dir3 = newDirectory(project, "dir3").setKey("dir3");
+    ProjectData project = db.components().insertPublicProject();
+    ComponentDto dir1 = newDirectory(project.getMainBranchComponent(), "dir1").setKey("dir1");
+    ComponentDto dir2 = newDirectory(project.getMainBranchComponent(), "dir2").setKey("dir2");
+    ComponentDto dir3 = newDirectory(project.getMainBranchComponent(), "dir3").setKey("dir3");
     db.components().insertComponents(dir1, dir2, dir3);
-    setBrowsePermissionOnUserAndIndex(List.of(project));
+    setBrowsePermissionOnUserAndIndex(List.of(project.getProjectDto()));
 
     SearchWsResponse response = call(new SearchRequest().setQualifiers(asList(PROJECT, APP)));
 
     assertThat(response.getComponentsList()).extracting(Component::getKey, Component::getProject)
-      .containsOnly(tuple(project.getKey(), project.getKey()));
+      .containsOnly(tuple(project.getProjectDto().getKey(), project.getProjectDto().getKey()));
   }
 
   @Test
   public void does_not_return_branches() {
-    ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
-    ComponentDto branch = db.components().insertProjectBranch(project);
-    setBrowsePermissionOnUserAndIndex(List.of(project, branch));
+    ProjectData project = db.components().insertPublicProject();
+    ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent());
+    setBrowsePermissionOnUserAndIndex(List.of(project.getProjectDto()));
 
     SearchWsResponse response = call(new SearchRequest().setQualifiers(asList(PROJECT)));
 
     assertThat(response.getComponentsList()).extracting(Component::getKey)
-      .containsOnly(project.getKey());
+      .containsOnly(project.getProjectDto().getKey());
   }
 
   @Test
@@ -204,11 +207,11 @@ public class SearchActionIT {
   @Test
   public void test_json_example() {
     db.components().insertComponent(newPortfolio());
-    ComponentDto project = db.components().insertPrivateProject("project-uuid", p -> p.setName("Project Name").setKey("project-key")).getMainBranchComponent();
-    ComponentDto directory = newDirectory(project, "path/to/directoy").setUuid("directory-uuid").setKey("directory-key").setName("Directory Name");
+    ProjectData project = db.components().insertPrivateProject("project-uuid", p -> p.setName("Project Name").setKey("project-key"));
+    ComponentDto directory = newDirectory(project.getMainBranchComponent(), "path/to/directoy").setUuid("directory-uuid").setKey("directory-key").setName("Directory Name");
     ComponentDto view = newPortfolio();
     db.components().insertComponents(directory, view);
-    setBrowsePermissionOnUserAndIndex(List.of(project));
+    setBrowsePermissionOnUserAndIndex(List.of(project.getProjectDto()));
 
     String response = underTest.newRequest()
       .setMediaType(MediaTypes.JSON)
@@ -217,12 +220,12 @@ public class SearchActionIT {
     assertJson(response).isSimilarTo(underTest.getDef().responseExampleAsString());
   }
 
-  private void insertProjectsAuthorizedForUser(List<ComponentDto> projects) {
+  private void insertProjectsAuthorizedForUser(List<ProjectDto> projects) {
     setBrowsePermissionOnUserAndIndex(projects);
     db.commit();
   }
 
-  private void setBrowsePermissionOnUserAndIndex(List<ComponentDto> projects) {
+  private void setBrowsePermissionOnUserAndIndex(List<ProjectDto> projects) {
     index();
     projects.forEach(project -> authorizationIndexerTester.allowOnlyUser(project, user));
   }
index 2396c0a9786034b7b17c9975cc3e6f8caf477a0e..75db28e67ba2bfb0ba521acab800c3cc5f9785a7 100644 (file)
@@ -25,14 +25,13 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner;
 import com.tngtech.java.junit.dataprovider.UseDataProvider;
 import java.util.Arrays;
 import java.util.Date;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
-import java.util.Set;
 import java.util.function.Consumer;
 import java.util.stream.IntStream;
 import java.util.stream.Stream;
 import javax.annotation.Nullable;
+import org.apache.ibatis.session.ResultHandler;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -48,6 +47,8 @@ import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
+import org.sonar.db.entity.EntityDto;
 import org.sonar.db.measure.LiveMeasureDto;
 import org.sonar.db.metric.MetricDto;
 import org.sonar.db.project.ProjectDto;
@@ -122,31 +123,31 @@ public class SearchProjectsActionIT {
   @Rule
   public final EsTester es = EsTester.create();
   @Rule
-  public final DbTester db = DbTester.create(System2.INSTANCE);
+  public final DbTester db = DbTester.create(System2.INSTANCE, true);
 
   @DataProvider
   public static Object[][] rating_metric_keys() {
-    return new Object[][]{{SQALE_RATING_KEY}, {RELIABILITY_RATING_KEY}, {SECURITY_RATING_KEY}};
+    return new Object[][] {{SQALE_RATING_KEY}, {RELIABILITY_RATING_KEY}, {SECURITY_RATING_KEY}};
   }
 
   @DataProvider
   public static Object[][] new_rating_metric_keys() {
-    return new Object[][]{{NEW_MAINTAINABILITY_RATING_KEY}, {NEW_RELIABILITY_RATING_KEY}, {NEW_SECURITY_RATING_KEY}};
+    return new Object[][] {{NEW_MAINTAINABILITY_RATING_KEY}, {NEW_RELIABILITY_RATING_KEY}, {NEW_SECURITY_RATING_KEY}};
   }
 
   @DataProvider
   public static Object[][] component_qualifiers_for_valid_editions() {
-    return new Object[][]{
-      {new String[]{Qualifiers.PROJECT}, Edition.COMMUNITY},
-      {new String[]{Qualifiers.APP, Qualifiers.PROJECT}, Edition.DEVELOPER},
-      {new String[]{Qualifiers.APP, Qualifiers.PROJECT}, Edition.ENTERPRISE},
-      {new String[]{Qualifiers.APP, Qualifiers.PROJECT}, Edition.DATACENTER},
+    return new Object[][] {
+      {new String[] {Qualifiers.PROJECT}, Edition.COMMUNITY},
+      {new String[] {Qualifiers.APP, Qualifiers.PROJECT}, Edition.DEVELOPER},
+      {new String[] {Qualifiers.APP, Qualifiers.PROJECT}, Edition.ENTERPRISE},
+      {new String[] {Qualifiers.APP, Qualifiers.PROJECT}, Edition.DATACENTER},
     };
   }
 
   @DataProvider
   public static Object[][] community_or_developer_edition() {
-    return new Object[][]{
+    return new Object[][] {
       {Edition.COMMUNITY},
       {Edition.DEVELOPER},
     };
@@ -154,7 +155,7 @@ public class SearchProjectsActionIT {
 
   @DataProvider
   public static Object[][] enterprise_or_datacenter_edition() {
-    return new Object[][]{
+    return new Object[][] {
       {Edition.ENTERPRISE},
       {Edition.DATACENTER},
     };
@@ -249,7 +250,7 @@ public class SearchProjectsActionIT {
       c -> c.setKey(KEY_PROJECT_EXAMPLE_003).setName("My Project 3"),
       p -> p.setTagsString("sales, offshore, java"),
       new Measure(coverage, c -> c.setValue(20d)));
-    addFavourite(project1);
+    addFavourite(db.components().getProjectDtoByMainBranch(project1));
     index();
 
     String jsonResult = ws.newRequest()
@@ -545,7 +546,7 @@ public class SearchProjectsActionIT {
     ComponentDto javaProject = insertProject();
     ComponentDto markDownProject = insertProject();
     ComponentDto sonarQubeProject = insertProject();
-    Stream.of(javaProject, markDownProject).forEach(this::addFavourite);
+    Stream.of(javaProject, markDownProject).forEach(c -> addFavourite(db.components().getProjectDtoByMainBranch(c)));
     index();
 
     SearchProjectsWsResponse result = call(request.setFilter("isFavorite"));
@@ -560,7 +561,7 @@ public class SearchProjectsActionIT {
     ComponentDto javaProject = insertProject();
     ComponentDto markDownProject = insertProject();
     ComponentDto sonarQubeProject = insertProject();
-    Stream.of(javaProject, markDownProject).forEach(this::addFavourite);
+    Stream.of(javaProject, markDownProject).forEach(c -> addFavourite(db.components().getProjectDtoByMainBranch(c)));
     index();
 
     addFavourite(null, null, null, null);
@@ -577,7 +578,7 @@ public class SearchProjectsActionIT {
     ComponentDto javaProject = insertProject();
     ComponentDto markDownProject = insertProject();
     ComponentDto sonarQubeProject = insertProject();
-    Stream.of(javaProject, markDownProject).forEach(this::addFavourite);
+    Stream.of(javaProject, markDownProject).forEach(c -> addFavourite(db.components().getProjectDtoByMainBranch(c)));
     index();
 
     SearchProjectsWsResponse result = call(request.setFilter("isFavorite"));
@@ -1184,25 +1185,26 @@ public class SearchProjectsActionIT {
   @Test
   public void sort_by_last_analysis_date() {
     userSession.logIn();
-    ComponentDto project1 = db.components().insertPublicProject(p -> p.setKey("project1")).getMainBranchComponent();
-    authorizationIndexerTester.allowOnlyAnyone(project1);
-    ComponentDto project2 = db.components().insertPublicProject(p -> p.setKey("project2")).getMainBranchComponent();
+    ProjectData project1 = db.components().insertPublicProject(p -> p.setKey("project1"));
+    authorizationIndexerTester.allowOnlyAnyone(project1.getProjectDto());
+    ProjectDto project2 = db.components().insertPublicProject(p -> p.setKey("project2")).getProjectDto();
     db.components().insertSnapshot(project2, snapshot -> snapshot.setCreatedAt(40_000_000_000L).setLast(true));
     authorizationIndexerTester.allowOnlyAnyone(project2);
-    ComponentDto project3 = db.components().insertPublicProject(p -> p.setKey("project3")).getMainBranchComponent();
+    ProjectDto project3 = db.components().insertPublicProject(p -> p.setKey("project3")).getProjectDto();
     db.components().insertSnapshot(project3, snapshot -> snapshot.setCreatedAt(20_000_000_000L).setLast(true));
     authorizationIndexerTester.allowOnlyAnyone(project3);
-    ComponentDto project4 = db.components().insertPublicProject(p -> p.setKey("project4")).getMainBranchComponent();
+    ProjectDto project4 = db.components().insertPublicProject(p -> p.setKey("project4")).getProjectDto();
     db.components().insertSnapshot(project4, snapshot -> snapshot.setCreatedAt(10_000_000_000L).setLast(false));
     db.components().insertSnapshot(project4, snapshot -> snapshot.setCreatedAt(30_000_000_000L).setLast(true));
     authorizationIndexerTester.allowOnlyAnyone(project4);
     index();
 
-    assertThat(call(request.setSort(ANALYSIS_DATE).setAsc(true)).getComponentsList()).extracting(Component::getKey)
-      .containsExactly(project3.getKey(), project4.getKey(), project2.getKey(), project1.getKey());
+    List<Component> response = call(request.setSort(ANALYSIS_DATE).setAsc(true)).getComponentsList();
+    assertThat(response).extracting(Component::getKey)
+      .containsExactly(project3.getKey(), project4.getKey(), project2.getKey(), project1.getProjectDto().getKey());
 
     assertThat(call(request.setSort(ANALYSIS_DATE).setAsc(false)).getComponentsList()).extracting(Component::getKey)
-      .containsExactly(project2.getKey(), project4.getKey(), project3.getKey(), project1.getKey());
+      .containsExactly(project2.getKey(), project4.getKey(), project3.getKey(), project1.getProjectDto().getKey());
   }
 
   @Test
@@ -1235,21 +1237,21 @@ public class SearchProjectsActionIT {
     userSession.logIn();
     ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
     db.components().insertSnapshot(project1, snapshot -> snapshot.setPeriodDate(10_000_000_000L));
-    authorizationIndexerTester.allowOnlyAnyone(project1);
+    authorizationIndexerTester.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(project1));
     // No leak period
     ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
     db.components().insertSnapshot(project2, snapshot -> snapshot.setPeriodDate(null));
-    authorizationIndexerTester.allowOnlyAnyone(project2);
+    authorizationIndexerTester.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(project2));
     // No snapshot on project 3
     ComponentDto project3 = db.components().insertPublicProject().getMainBranchComponent();
-    authorizationIndexerTester.allowOnlyAnyone(project3);
+    authorizationIndexerTester.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(project3));
 
     MetricDto leakProjects = db.measures().insertMetric(c -> c.setKey(LEAK_PROJECTS_KEY).setValueType(DATA.name()));
     ComponentDto application1 = insertApplication(
       new Measure(leakProjects, c -> c.setData("{\"leakProjects\":[{\"id\": 1, \"leak\":20000000000}, {\"id\": 2, \"leak\":10000000000}]}")));
     db.components().insertSnapshot(application1);
 
-    authorizationIndexerTester.allowOnlyAnyone(application1);
+    authorizationIndexerTester.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(application1));
     index();
 
     SearchProjectsWsResponse result = call(request.setAdditionalFields(singletonList("leakPeriodDate")));
@@ -1354,16 +1356,13 @@ public class SearchProjectsActionIT {
     return httpRequest.executeProtobuf(SearchProjectsWsResponse.class);
   }
 
-  private void addFavourite(ComponentDto project) {
-    addFavourite(project.uuid(), project.getKey(),
-      project.name(), project.qualifier());
+  private void addFavourite(ProjectDto project) {
+    addFavourite(project.getUuid(), project.getKey(), project.getName(), project.getQualifier());
   }
 
-  private void addFavourite(@Nullable String componentUuid, @Nullable String componentKey,
-    @Nullable String componentName, @Nullable String qualifier) {
+  private void addFavourite(@Nullable String entityUuid, @Nullable String entityKey, @Nullable String entityName, @Nullable String qualifier) {
     dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey("favourite")
-        .setEntityUuid(componentUuid).setUserUuid(userSession.getUuid()), userSession.getLogin(), componentKey,
-      componentName, qualifier);
+        .setEntityUuid(entityUuid).setUserUuid(userSession.getUuid()), userSession.getLogin(), entityKey, entityName, qualifier);
     dbSession.commit();
   }
 
@@ -1375,8 +1374,7 @@ public class SearchProjectsActionIT {
     return insertProject(componentConsumer, defaults(), measures);
   }
 
-  private ComponentDto insertProject(Consumer<ComponentDto> componentConsumer, Consumer<ProjectDto> projectConsumer,
-    Measure... measures) {
+  private ComponentDto insertProject(Consumer<ComponentDto> componentConsumer, Consumer<ProjectDto> projectConsumer, Measure... measures) {
     ComponentDto project = db.components().insertPublicProject(componentConsumer, projectConsumer).getMainBranchComponent();
     Arrays.stream(measures).forEach(m -> db.measures().insertLiveMeasure(project, m.metric, m.consumer));
     return project;
@@ -1394,9 +1392,12 @@ public class SearchProjectsActionIT {
 
   private void index() {
     projectMeasuresIndexer.indexAll();
-    Set<ComponentDto> roots = dbClient.componentDao().selectComponentsByQualifiers(db.getSession(),
-      new HashSet<>(asList(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP)));
-    authorizationIndexerTester.allowOnlyAnyone(roots.toArray(new ComponentDto[0]));
+    ResultHandler<EntityDto> rh = r -> {
+      if (!r.getResultObject().getQualifier().equals(Qualifiers.SUBVIEW)) {
+        authorizationIndexerTester.allowOnlyAnyone(r.getResultObject());
+      }
+    };
+    db.getDbClient().entityDao().scrollForIndexing(dbSession, null, rh);
   }
 
   private ComponentDto insertPortfolio() {
index 063ec52e6b3701b08b4aea2fd257d9ab77828cee..5b93b1cf72aa8d7a3f7c21454635e904ce917512 100644 (file)
@@ -217,8 +217,8 @@ public class ShowActionIT {
     ProjectData projectData = db.components().insertPublicProject();
     ComponentDto publicProject = projectData.getMainBranchComponent();
 
-    userSession.registerProjects(projectData.getProjectDto())
-      .registerBranches(projectData.getMainBranchDto());
+    userSession.addProjectBranchMapping(projectData.projectUuid(), projectData.getMainBranchComponent());
+    userSession.registerProjects(projectData.getProjectDto());
 
     ShowWsResponse result = newRequest(publicProject.getKey());
     assertThat(result.getComponent().hasVisibility()).isTrue();
@@ -328,6 +328,7 @@ public class ShowActionIT {
       .setNeedIssueSync(true));
     ComponentDto directory = db.components().insertComponent(newDirectoryOnBranch(branch1, "dir", project1.uuid()));
     ComponentDto file = db.components().insertComponent(newFileDto(project1.uuid(), branch1, directory));
+    userSession.addProjectBranchMapping(projectData1.projectUuid(), projectData1.getMainBranchComponent());
     userSession.addProjectBranchMapping(projectData1.projectUuid(), branch1);
 
     ProjectData projectData2 = db.components().insertPrivateProject();
@@ -336,6 +337,7 @@ public class ShowActionIT {
     ComponentDto branch2 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(true).setKey(branchName2));
     String branchName3 = randomAlphanumeric(248);
     ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName3));
+    userSession.addProjectBranchMapping(projectData2.projectUuid(), projectData2.getMainBranchComponent());
     userSession.addProjectBranchMapping(projectData2.projectUuid(), branch2);
     userSession.addProjectBranchMapping(projectData2.projectUuid(), branch3);
 
@@ -347,6 +349,7 @@ public class ShowActionIT {
     ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(project3.uuid(), branch4, directoryOfBranch4));
     String branchName5 = randomAlphanumeric(248);
     ComponentDto branch5 = db.components().insertProjectBranch(project3, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName5));
+    userSession.addProjectBranchMapping(projectData3.projectUuid(), projectData3.getMainBranchComponent());
     userSession.addProjectBranchMapping(projectData3.projectUuid(), branch4);
     userSession.addProjectBranchMapping(projectData3.projectUuid(), branch5);
 
index a14f41ee154c0c644f1ac079c5ee2572b3bf677a..2408c613180a171f81bef6f19fe346b95b6790d8 100644 (file)
@@ -82,7 +82,7 @@ public class SuggestionsActionIT {
     .collect(MoreCollectors.toList()).toArray(new String[0]);
 
   @Rule
-  public final DbTester db = DbTester.create(System2.INSTANCE);
+  public final DbTester db = DbTester.create(System2.INSTANCE, true);
   @Rule
   public final EsTester es = EsTester.create();
   @Rule
@@ -472,11 +472,12 @@ public class SuggestionsActionIT {
 
   @Test
   public void should_mark_recently_browsed_items() {
-    ComponentDto project = db.components().insertPrivateProject(p -> p.setName("ProjectTest")).getMainBranchComponent();
+    ProjectData projectData = db.components().insertPrivateProject(p -> p.setName("ProjectTest"));
+    ComponentDto project = projectData.getMainBranchComponent();
     ComponentDto file1 = newFileDto(project).setName("File1");
     ComponentDto file2 = newFileDto(project).setName("File2");
     componentIndexer.indexOnAnalysis(project.branchUuid());
-    authorizationIndexerTester.allowOnlyAnyone(project);
+    authorizationIndexerTester.allowOnlyAnyone(projectData.getProjectDto());
 
     SuggestionsWsResponse response = ws.newRequest()
       .setMethod("POST")
@@ -513,13 +514,13 @@ public class SuggestionsActionIT {
 
   @Test
   public void should_return_empty_qualifiers() {
-    ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
-    componentIndexer.indexOnAnalysis(project.branchUuid());
-    authorizationIndexerTester.allowOnlyAnyone(project);
+    ProjectData project = db.components().insertPrivateProject();
+    componentIndexer.indexOnAnalysis(project.getMainBranchComponent().uuid());
+    authorizationIndexerTester.allowOnlyAnyone(project.getProjectDto());
 
     SuggestionsWsResponse response = ws.newRequest()
       .setMethod("POST")
-      .setParam(PARAM_QUERY, project.name())
+      .setParam(PARAM_QUERY, project.getProjectDto().getName())
       .executeProtobuf(SuggestionsWsResponse.class);
 
     assertThat(response.getResultsList())
@@ -531,17 +532,19 @@ public class SuggestionsActionIT {
   public void should_only_provide_project_for_certain_qualifiers() {
     String query = randomAlphabetic(10);
 
-    ComponentDto app = db.components().insertPublicApplication(v -> v.setName(query)).getMainBranchComponent();
+    ProjectData appData = db.components().insertPublicApplication(v -> v.setName(query));
+    ComponentDto app = appData.getMainBranchComponent();
     ComponentDto view = db.components().insertPublicPortfolio(v -> v.setName(query));
     ComponentDto subView = db.components().insertSubView(view, v -> v.setName(query));
-    ComponentDto project = db.components().insertPrivateProject(p -> p.setName(query)).getMainBranchComponent();
+    ProjectData projectData = db.components().insertPrivateProject(p -> p.setName(query));
+    ComponentDto project = projectData.getMainBranchComponent();
     ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "path").setName(query));
     ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project, dir).setName(query));
     ComponentDto test = db.components().insertComponent(ComponentTesting.newFileDto(project, dir).setName(query).setQualifier(UNIT_TEST_FILE));
     componentIndexer.indexAll();
-    authorizationIndexerTester.allowOnlyAnyone(project);
+    authorizationIndexerTester.allowOnlyAnyone(projectData.getProjectDto());
     authorizationIndexerTester.allowOnlyAnyone(view);
-    authorizationIndexerTester.allowOnlyAnyone(app);
+    authorizationIndexerTester.allowOnlyAnyone(appData.getProjectDto());
 
     SuggestionsWsResponse response = ws.newRequest()
       .setMethod("POST")
index b28fc33bb0dc36712dfc5b17e5d8f6673564b20a..5bd03992e8855de2e63a2056f5e08953ec1ba2f0 100644 (file)
@@ -73,7 +73,7 @@ public class AddCommentActionIT {
   private static final Random RANDOM = new Random();
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
index 950326e7cfd02af09f8009a6a528a5412b12f833..239c235fab9a87048cfe34c04f98d58407bb54dd 100644 (file)
@@ -49,7 +49,9 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ProjectData;
+import org.sonar.db.entity.EntityDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.rule.RuleTesting;
 import org.sonar.db.user.UserDto;
@@ -91,7 +93,7 @@ import static org.sonar.db.component.ComponentTesting.newFileDto;
 public class AssignActionIT {
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
@@ -204,12 +206,12 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenAssigneeForPrivateProject() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
 
-    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
-    UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project);
+    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+    UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto());
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
 
@@ -220,12 +222,12 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenUnassignedForPrivateProject() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
     UserDto assignee = insertUser(randomAlphanumeric(15));
-    IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setAssigneeUuid(assignee.getUuid()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file, h -> h.setAssigneeUuid(assignee.getUuid()));
 
-    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
+    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), isNull(), any(IssueChangeContext.class))).thenReturn(true);
 
@@ -236,14 +238,14 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenAssigneeForPrivateProjectBranch() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto branch = dbTester.components().insertProjectBranch(project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.uuid()));
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto branch = dbTester.components().insertProjectBranch(project.getMainBranchComponent());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent().uuid()));
     IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
 
-    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
-    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
-    UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project);
+    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+    userSessionRule.addProjectBranchMapping(project.projectUuid(), branch);
+    UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto());
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
 
@@ -254,11 +256,11 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenAssigneeDoesNotHaveAccessToPrivateProject_shouldFail() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
 
-    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
+    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
     UserDto assignee = insertUser(randomAlphanumeric(15));
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
@@ -271,13 +273,13 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenAssigneeDoesNotHaveAccessToPrivateProjectBranch_shouldFail() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto branch = dbTester.components().insertProjectBranch(project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.uuid()));
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto branch = dbTester.components().insertProjectBranch(project.getMainBranchComponent());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent()));
     IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
 
-    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
-    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
+    insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+    userSessionRule.addProjectBranchMapping(project.projectUuid(), branch);
     UserDto assignee = insertUser(randomAlphanumeric(15));
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
@@ -290,12 +292,11 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenAssignHotspotToMeForPrivateProject() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
 
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
-
-    UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.USER);
+    UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true);
 
@@ -474,11 +475,11 @@ public class AssignActionIT {
 
   @Test
   public void wsExecution_whenMissingBrowserAthentication_shouldFail() {
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
+    ProjectData project = dbTester.components().insertPrivateProject();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
 
-    UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project, UserRole.CODEVIEWER);
+    UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.CODEVIEWER);
 
     when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true);
 
@@ -611,21 +612,19 @@ public class AssignActionIT {
     return dbTester.users().insertUser(login);
   }
 
-  private UserDto insertUserWithProjectPermission(String login, ComponentDto project, String permission) {
+  private UserDto insertUserWithProjectPermission(String login, EntityDto project, String permission) {
     UserDto user = dbTester.users().insertUser(login);
     dbTester.users().insertProjectPermissionOnUser(user, permission, project);
     return user;
   }
 
-  private UserDto insertUserWithProjectUserPermission(String login, ComponentDto project) {
+  private UserDto insertUserWithProjectUserPermission(String login, EntityDto project) {
     return insertUserWithProjectPermission(login, project, UserRole.USER);
   }
 
-  private UserDto insertAndLoginAsUserWithProjectUserPermission(String login, ComponentDto project, String permission) {
+  private UserDto insertAndLoginAsUserWithProjectUserPermission(String login, ProjectDto project, String permission) {
     UserDto user = insertUserWithProjectUserPermission(login, project);
-    userSessionRule.logIn(user)
-      .addProjectPermission(permission,
-        dbClient.componentDao().selectByUuid(dbTester.getSession(), project.uuid()).get());
+    userSessionRule.logIn(user).addProjectPermission(permission, project);
     return user;
   }
 
index 1c7b22197087a88676330dd9a0d6c6bc53dfff6d..23f41395aeecf44ae191c17f7e688e1a76b79f7d 100644 (file)
@@ -93,7 +93,7 @@ public class ChangeStatusActionIT {
   private static final List<String> RESOLUTION_TYPES = List.of(RESOLUTION_FIXED, RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED);
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
@@ -475,7 +475,6 @@ public class ChangeStatusActionIT {
   @Test
   public void wsExecution_whenOnNonMainBranch_shouldDistributeEvents() {
     ProjectDto project = dbTester.components().insertPublicProject().getProjectDto();
-    ComponentDto projectComponentDto = dbTester.components().getComponentDto(project);
     BranchDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey("develop"));
     ComponentDto branchComponentDto = dbTester.components().getComponentDto(branch);
 
index 769104cb79febcf8dd05d5886bb46d4ebb2e29c5..94a75fa2d5d0b8bc98c10d35bb572f21d4487000 100644 (file)
@@ -46,7 +46,7 @@ import static org.mockito.Mockito.mock;
 public class DeleteCommentActionIT {
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
 
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
@@ -72,13 +72,13 @@ public class DeleteCommentActionIT {
   public void delete_comment_from_hotspot_private_project() {
     UserDto userDeletingOwnComment = dbTester.users().insertUser();
 
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData projectData = dbTester.components().insertPrivateProject();
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project));
+    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(projectData.getMainBranchComponent()));
     IssueChangeDto comment = dbTester.issues().insertComment(hotspot, userDeletingOwnComment, "Some comment");
 
     userSessionRule.logIn(userDeletingOwnComment);
-    userSessionRule.addProjectPermission(UserRole.USER, project);
+    userSessionRule.addProjectPermission(UserRole.USER, projectData.getProjectDto());
 
     TestRequest request = newRequest(comment.getKey());
 
@@ -138,13 +138,13 @@ public class DeleteCommentActionIT {
     UserDto userTryingToDelete = dbTester.users().insertUser();
     UserDto userWithHotspotComment = dbTester.users().insertUser();
 
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData projectData = dbTester.components().insertPrivateProject();
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project));
+    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(projectData.getMainBranchComponent()));
     IssueChangeDto comment = dbTester.issues().insertComment(hotspot, userWithHotspotComment, "Some comment");
 
     userSessionRule.logIn(userTryingToDelete);
-    userSessionRule.addProjectPermission(UserRole.USER, project);
+    userSessionRule.addProjectPermission(UserRole.USER, projectData.getProjectDto());
 
     TestRequest request = newRequest(comment.getKey());
 
index d942876c457bcb9b87768020f163195043b84c56..707464a2298f7b19bdc14260ec9a0f6ba5800579 100644 (file)
@@ -46,7 +46,7 @@ import static org.mockito.Mockito.mock;
 public class EditCommentActionIT {
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
 
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
@@ -77,16 +77,16 @@ public class EditCommentActionIT {
   public void edit_comment_from_hotspot_private_project() {
     UserDto userEditingOwnComment = dbTester.users().insertUser();
 
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData project = dbTester.components().insertPrivateProject();
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project));
+    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project.getMainBranchComponent()));
     IssueChangeDto comment = dbTester.issues().insertComment(hotspot, userEditingOwnComment, "Some comment");
 
     assertThat(getHotspotCommentByKey(comment.getKey()))
       .isNotEmpty();
 
     userSessionRule.logIn(userEditingOwnComment);
-    userSessionRule.addProjectPermission(UserRole.USER, project);
+    userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto());
 
     TestRequest request = newRequest(comment.getKey(), "new comment");
 
@@ -145,13 +145,13 @@ public class EditCommentActionIT {
     UserDto userTryingToDelete = dbTester.users().insertUser();
     UserDto userWithHotspotComment = dbTester.users().insertUser();
 
-    ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData project = dbTester.components().insertPrivateProject();
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project));
+    IssueDto hotspot = dbTester.issues().insertHotspot(h -> h.setProject(project.getMainBranchComponent()));
     IssueChangeDto comment = dbTester.issues().insertComment(hotspot, userWithHotspotComment, "Some comment");
 
     userSessionRule.logIn(userTryingToDelete);
-    userSessionRule.addProjectPermission(UserRole.USER, project);
+    userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto());
 
     TestRequest request = newRequest(comment.getKey(), "new comment");
 
index 70fb645091a0e9050d9c8e447435fc456bfd0583..050faa6032e25fffb55245b08cb49e36ccba4664 100644 (file)
@@ -77,7 +77,7 @@ public class PullActionIT {
   public UserSessionRule userSession = UserSessionRule.standalone();
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   private final System2 system2 = mock(System2.class);
   private final PullHotspotsActionProtobufObjectGenerator pullActionProtobufObjectGenerator = new PullHotspotsActionProtobufObjectGenerator();
@@ -92,21 +92,21 @@ public class PullActionIT {
   private final WsActionTester tester = new WsActionTester(underTest);
 
   private ProjectDto project;
-  private ComponentDto correctProject, incorrectProject;
+  private ComponentDto correctMainBranch, incorrectMainBranch;
   private ComponentDto correctFile, incorrectFile;
 
   @Before
   public void before() {
     when(system2.now()).thenReturn(NOW);
     ProjectData projectData = db.components().insertPrivateProject();
-    correctProject = projectData.getMainBranchComponent();
+    correctMainBranch = projectData.getMainBranchComponent();
     project = projectData.getProjectDto();
 
-    correctFile = db.components().insertComponent(newFileDto(correctProject));
+    correctFile = db.components().insertComponent(newFileDto(correctMainBranch));
 
     ProjectData incorrectProjectData = db.components().insertPrivateProject();
-    incorrectProject = incorrectProjectData.getMainBranchComponent();
-    incorrectFile = db.components().insertComponent(newFileDto(incorrectProject));
+    incorrectMainBranch = incorrectProjectData.getMainBranchComponent();
+    incorrectFile = db.components().insertComponent(newFileDto(incorrectMainBranch));
   }
 
   @Test
@@ -133,7 +133,7 @@ public class PullActionIT {
     userSession.logIn();
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     assertThatThrownBy(request::execute)
@@ -232,7 +232,7 @@ public class PullActionIT {
     ComponentDto developBranch = projectData.getMainBranchComponent();
     ComponentDto developFile = db.components().insertComponent(newFileDto(developBranch));
     List<String> hotspotKeys = generateHotspots(developBranch, developFile, 1);
-    loginWithBrowsePermission(project, developFile.uuid());
+    loginWithBrowsePermission(project);
 
     TestRequest request = tester.newRequest()
       .setParam("projectKey", developBranch.getKey())
@@ -277,12 +277,12 @@ public class PullActionIT {
 
   @Test
   public void wsExecution_whenDifferentHotspotsInTheTable_shouldReturnOnlyThatBelongToSelectedProject() throws IOException {
-    loginWithBrowsePermission(project, correctFile.uuid());
-    List<String> correctIssueKeys = generateHotspots(correctProject, correctFile, 10);
-    List<String> incorrectIssueKeys = generateHotspots(incorrectProject, incorrectFile, 5);
+    loginWithBrowsePermission(project);
+    List<String> correctIssueKeys = generateHotspots(correctMainBranch, correctFile, 10);
+    List<String> incorrectIssueKeys = generateHotspots(incorrectMainBranch, incorrectFile, 5);
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     TestResponse response = request.execute();
@@ -297,11 +297,11 @@ public class PullActionIT {
 
   @Test
   public void wsExecution_whenNoIssuesBelongToTheProject_shouldReturnZeroIssues() throws IOException {
-    loginWithBrowsePermission(project, correctFile.uuid());
-    generateHotspots(incorrectProject, incorrectFile, 5);
+    loginWithBrowsePermission(project);
+    generateHotspots(incorrectMainBranch, incorrectFile, 5);
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     TestResponse response = request.execute();
@@ -312,7 +312,7 @@ public class PullActionIT {
 
   @Test
   public void wsExecution_whenLanguagesParam_shouldReturnOneIssue() throws IOException {
-    loginWithBrowsePermission(project, correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setLanguage("java"));
 
     IssueDto javaIssue = issueDbTester.insertHotspot(p -> p.setSeverity("MINOR")
@@ -322,11 +322,11 @@ public class PullActionIT {
       .setRuleUuid(javaRule.getUuid())
       .setStatus(Issue.STATUS_TO_REVIEW)
       .setLanguage("java")
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("languages", "java");
 
@@ -340,7 +340,7 @@ public class PullActionIT {
 
   @Test
   public void wsExecution_whenChangedSinceParam_shouldReturnMatchingIssue() throws IOException {
-    loginWithBrowsePermission(project, correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setLanguage("java"));
 
     IssueDto issueBefore = issueDbTester.insertHotspot(p -> p.setSeverity("MINOR")
@@ -350,7 +350,7 @@ public class PullActionIT {
       .setRuleUuid(javaRule.getUuid())
       .setStatus(Issue.STATUS_TO_REVIEW)
       .setLanguage("java")
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile));
 
     IssueDto issueAfter = issueDbTester.insertHotspot(p -> p.setSeverity("MINOR")
@@ -360,12 +360,12 @@ public class PullActionIT {
       .setRuleUuid(javaRule.getUuid())
       .setStatus(Issue.STATUS_TO_REVIEW)
       .setLanguage("java")
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setUpdatedAt(NOW)
       .setComponent(correctFile));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("languages", "java")
       .setParam("changedSince", String.valueOf(issueBefore.getIssueUpdateTime() + 1L));
@@ -380,7 +380,7 @@ public class PullActionIT {
 
   @Test
   public void wsExecution_whenWrongLanguageSet_shouldReturnZeroIssues() throws IOException {
-    loginWithBrowsePermission(project, correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javascriptRule = db.rules().insert(r -> r.setLanguage("javascript"));
 
     issueDbTester.insertHotspot(p -> p.setSeverity("MINOR")
@@ -389,11 +389,11 @@ public class PullActionIT {
       .setRule(javascriptRule)
       .setRuleUuid(javascriptRule.getUuid())
       .setStatus(Issue.STATUS_TO_REVIEW)
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("languages", "java");
 
@@ -429,19 +429,11 @@ public class PullActionIT {
   private void loginWithBrowsePermission(IssueDto issueDto) {
     BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), issueDto.getProjectUuid()).get();
     ProjectDto projectDto = db.getDbClient().projectDao().selectByUuid(db.getSession(), branchDto.getProjectUuid()).get();
-    loginWithBrowsePermission(projectDto, issueDto.getComponentUuid());
+    loginWithBrowsePermission(projectDto);
   }
 
-  private void loginWithBrowsePermission(ProjectDto project, String componentUuid) {
+  private void loginWithBrowsePermission(ProjectDto project) {
     UserDto user = db.users().insertUser("john");
-    userSession.logIn(user)
-      .addProjectPermission(USER, project)
-      .addProjectPermission(USER, getComponentOrFail(componentUuid, "component not found"));
-  }
-
-  private ComponentDto getComponentOrFail(String componentUuid, String failMessage) {
-    return db.getDbClient().componentDao()
-      .selectByUuid(db.getSession(), componentUuid)
-      .orElseGet(() -> fail(failMessage));
+    userSession.logIn(user).addProjectPermission(USER, project);
   }
 }
index 4db590cb6dc6f02c2b5b17ad095a157c1e9e3aab..b730530b7664ffb043c529ef286f51e4c157c9eb 100644 (file)
@@ -78,7 +78,6 @@ import org.sonar.server.view.index.ViewIndexer;
 import org.sonar.server.ws.TestRequest;
 import org.sonar.server.ws.WsActionTester;
 import org.sonarqube.ws.Common;
-import org.sonarqube.ws.Hotspots;
 import org.sonarqube.ws.Hotspots.Component;
 import org.sonarqube.ws.Hotspots.SearchWsResponse;
 
@@ -143,7 +142,7 @@ public class SearchActionIT {
   private static final List<String> RESOLUTION_TYPES = List.of(RESOLUTION_FIXED, RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED);
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
   @Rule
   public EsTester es = EsTester.create();
   @Rule
@@ -256,7 +255,7 @@ public class SearchActionIT {
         Stream.of(randomAlphabetic(3)))
       .filter(t -> !STATUS_REVIEWED.equals(t))
       .filter(t -> !STATUS_TO_REVIEW.equals(t))
-      .map(t -> new Object[]{t})
+      .map(t -> new Object[] {t})
       .toArray(Object[][]::new);
   }
 
@@ -293,7 +292,7 @@ public class SearchActionIT {
         Stream.of(randomAlphabetic(4)))
       .flatMap(t -> t)
       .filter(t -> !RESOLUTION_TYPES.contains(t))
-      .map(t -> new Object[]{t})
+      .map(t -> new Object[] {t})
       .toArray(Object[][]::new);
   }
 
@@ -324,7 +323,7 @@ public class SearchActionIT {
 
   @DataProvider
   public static Object[][] fixedOrSafeResolution() {
-    return new Object[][]{
+    return new Object[][] {
       {RESOLUTION_SAFE},
       {RESOLUTION_FIXED}
     };
@@ -417,10 +416,9 @@ public class SearchActionIT {
     ComponentDto project = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(USER, project);
+    userSessionRule.logIn().addProjectPermission(USER, projectData.getProjectDto());
 
-    SearchWsResponse response = newRequest(project)
-      .executeProtobuf(SearchWsResponse.class);
+    SearchWsResponse response = newRequest(project).executeProtobuf(SearchWsResponse.class);
 
     assertThat(response.getHotspotsList()).isEmpty();
     assertThat(response.getComponentsList()).isEmpty();
@@ -432,8 +430,7 @@ public class SearchActionIT {
     ComponentDto application = applicationData.getMainBranchComponent();
     userSessionRule.logIn().registerApplication(applicationData.getProjectDto()).addProjectPermission(USER, applicationData.getProjectDto());
 
-    SearchWsResponse response = newRequest(application)
-      .executeProtobuf(SearchWsResponse.class);
+    SearchWsResponse response = newRequest(application).executeProtobuf(SearchWsResponse.class);
 
     assertThat(response.getHotspotsList()).isEmpty();
     assertThat(response.getComponentsList()).isEmpty();
@@ -804,7 +801,7 @@ public class SearchActionIT {
 
   @DataProvider
   public static Object[][] onlyMineParamValues() {
-    return new Object[][]{
+    return new Object[][] {
       {"yes", true},
       {"true", true},
       {"no", false},
@@ -1012,7 +1009,7 @@ public class SearchActionIT {
 
   @DataProvider
   public static Object[][] validStatusesAndResolutions() {
-    return new Object[][]{
+    return new Object[][] {
       {STATUS_TO_REVIEW, null},
       {STATUS_REVIEWED, RESOLUTION_FIXED},
       {STATUS_REVIEWED, RESOLUTION_SAFE},
@@ -1045,13 +1042,13 @@ public class SearchActionIT {
   public static Object[][] allSQCategories() {
     Stream<Object[]> allCategoriesButOTHERS = SecurityStandards.CWES_BY_SQ_CATEGORY.entrySet()
       .stream()
-      .map(t -> new Object[]{
+      .map(t -> new Object[] {
         t.getValue().stream().map(c -> "cwe:" + c).collect(toSet()),
         t.getKey()
       });
     Stream<Object[]> sqCategoryOTHERS = Stream.of(
-      new Object[]{Collections.emptySet(), SQCategory.OTHERS},
-      new Object[]{of("foo", "donut", "acme"), SQCategory.OTHERS});
+      new Object[] {Collections.emptySet(), SQCategory.OTHERS},
+      new Object[] {of("foo", "donut", "acme"), SQCategory.OTHERS});
     return Stream.concat(allCategoriesButOTHERS, sqCategoryOTHERS).toArray(Object[][]::new);
   }
 
@@ -1750,6 +1747,7 @@ public class SearchActionIT {
     ComponentDto project = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
+    userSessionRule.addProjectBranchMapping(projectData.projectUuid(), project);
     indexPermissions();
     ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
     long periodDate = 800_996_999_332L;
@@ -1960,7 +1958,8 @@ public class SearchActionIT {
     long referenceDate = 800_996_999_332L;
 
     system2.setNow(referenceDate + 10_000);
-    ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto();
+    ProjectData applicationData = dbTester.components().insertPublicApplication();
+    ProjectDto application = applicationData.getProjectDto();
     BranchDto applicationBranch = dbTester.components().insertProjectBranch(application, branchDto -> branchDto.setKey("application_branch_1"));
     ProjectDto project = dbTester.components().insertPublicProject().getProjectDto();
     BranchDto projectBranch = dbTester.components().insertProjectBranch(project, branchDto -> branchDto.setKey("project_1_branch_1"));
@@ -1998,7 +1997,7 @@ public class SearchActionIT {
 
     indexIssues();
 
-    ComponentDto applicationComponentDto = dbClient.componentDao().selectByUuid(dbTester.getSession(), application.getUuid()).get();
+    ComponentDto applicationComponentDto = applicationData.getMainBranchComponent();
     SearchWsResponse responseAll = newRequest(applicationComponentDto,
       t -> t.setParam(PARAM_BRANCH, applicationBranch.getKey()))
       .executeProtobuf(SearchWsResponse.class);
index 4a7e254b19c977bf70fe8f1169d36b7c8c43a3fe..23829c2657496e0e3ec1258d8ccc36c8419e27dc 100644 (file)
@@ -54,6 +54,7 @@ import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ProjectData;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbCommons.TextRange;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.protobuf.DbIssues.Flow;
@@ -85,6 +86,7 @@ import org.sonarqube.ws.Common.Location;
 import org.sonarqube.ws.Common.User;
 import org.sonarqube.ws.Hotspots;
 
+import static java.util.Collections.emptySet;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
 import static org.assertj.core.api.Assertions.assertThat;
@@ -159,10 +161,10 @@ public class ShowActionIT {
   @Test
   @UseDataProvider("ruleTypesButHotspot")
   public void fails_with_NotFoundException_if_issue_is_not_a_hotspot(RuleType ruleType) {
-    ComponentDto project = dbTester.components().insertPublicProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto mainBranchComponent = dbTester.components().insertPublicProject().getMainBranchComponent();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(ruleType);
-    IssueDto notAHotspot = dbTester.issues().insertIssue(rule, project, file, i -> i.setType(ruleType));
+    IssueDto notAHotspot = dbTester.issues().insertIssue(rule, mainBranchComponent, file, i -> i.setType(ruleType));
     TestRequest request = newRequest(notAHotspot);
 
     assertThatThrownBy(request::execute)
@@ -180,10 +182,10 @@ public class ShowActionIT {
 
   @Test
   public void fails_with_NotFoundException_if_issue_is_hotspot_is_closed() {
-    ComponentDto project = dbTester.components().insertPublicProject().getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto mainBranchComponent = dbTester.components().insertPublicProject().getMainBranchComponent();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(Issue.STATUS_CLOSED));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setStatus(Issue.STATUS_CLOSED));
     TestRequest request = newRequest(hotspot);
 
     assertThatThrownBy(request::execute)
@@ -194,12 +196,12 @@ public class ShowActionIT {
   @Test
   public void fails_with_ForbiddenException_if_project_is_private_and_not_allowed() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     TestRequest request = newRequest(hotspot);
 
     assertThatThrownBy(request::execute)
@@ -210,9 +212,9 @@ public class ShowActionIT {
   @Test
   public void succeeds_on_hotspot_with_flow() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    ComponentDto anotherFile = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
+    ComponentDto anotherFile = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder()
       .addFlow(Flow.newBuilder()
         .setDescription("FLOW DESCRIPTION")
@@ -241,7 +243,7 @@ public class ShowActionIT {
           .setComponentId(file.uuid())
           .build()));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    var hotspot = dbTester.issues().insertHotspot(rule, project, file, i -> i.setLocations(locations.build()));
+    var hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, i -> i.setLocations(locations.build()));
     mockChangelogAndCommentsFormattingContext();
     userSessionRule.registerProjects(projectData.getProjectDto());
 
@@ -269,12 +271,12 @@ public class ShowActionIT {
   @Test
   public void succeeds_on_public_project() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -286,13 +288,13 @@ public class ShowActionIT {
   @Test
   public void succeeds_on_private_project_with_permission() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -322,15 +324,15 @@ public class ShowActionIT {
   @UseDataProvider("allPublicProjectPermissionsButSECURITYHOTSPOT_ADMIN")
   public void return_canChangeStatus_false_on_public_project_when_authenticated_without_SECURITYHOTSPOT_ADMIN_permission(@Nullable String permission) {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.logIn().registerProjects(projectData.getProjectDto());
     if (permission != null) {
-      userSessionRule.addProjectPermission(permission, project);
+      userSessionRule.addProjectPermission(permission, projectData.getProjectDto());
     }
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -343,16 +345,16 @@ public class ShowActionIT {
   @UseDataProvider("allPublicProjectPermissionsButSECURITYHOTSPOT_ADMIN")
   public void return_canChangeStatus_true_on_public_project_when_authenticated_with_SECURITYHOTSPOT_ADMIN_permission(@Nullable String permission) {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto())
       .addProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN, projectData.getProjectDto());
     if (permission != null) {
-      userSessionRule.addProjectPermission(permission, project);
+      userSessionRule.addProjectPermission(permission, projectData.getProjectDto());
     }
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -375,7 +377,7 @@ public class ShowActionIT {
   @UseDataProvider("allPrivateProjectPermissionsButSECURITYHOTSPOT_ADMIN_and_USER")
   public void return_canChangeStatus_false_on_private_project_without_SECURITYHOTSPOT_ADMIN_permission(@Nullable String permission) {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
     userSessionRule
       .registerProjects(projectData.getProjectDto())
       .logIn()
@@ -383,9 +385,9 @@ public class ShowActionIT {
     if (permission != null) {
       userSessionRule.addProjectPermission(permission, projectData.getProjectDto());
     }
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -433,13 +435,13 @@ public class ShowActionIT {
   @UseDataProvider("statusAndResolutionCombinations")
   public void returns_status_and_resolution(String status, @Nullable String resolution) {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(status).setResolution(resolution));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setStatus(status).setResolution(resolution));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -465,11 +467,11 @@ public class ShowActionIT {
   @Test
   public void dispatch_description_sections_of_advanced_rule_in_relevant_field() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     RuleDescriptionSectionDto introductionSection = generateSectionWithKey(INTRODUCTION_SECTION_KEY);
     RuleDescriptionSectionDto rootCauseSection = generateSectionWithKey(ROOT_CAUSE_SECTION_KEY);
@@ -487,7 +489,7 @@ public class ShowActionIT {
         .addRuleDescriptionSectionDto(dummySection)
         .setDescriptionFormat(HTML));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -501,11 +503,11 @@ public class ShowActionIT {
   @Test
   public void fallbacks_to_default_section_in_case_of_legacy_rule() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     RuleDescriptionSectionDto introductionSection = generateSectionWithKey(DEFAULT_KEY);
 
@@ -513,7 +515,7 @@ public class ShowActionIT {
       r -> r.addRuleDescriptionSectionDto(introductionSection)
         .setDescriptionFormat(HTML));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -527,11 +529,11 @@ public class ShowActionIT {
   @Test
   public void ignore_default_section_if_root_cause_provided() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     RuleDescriptionSectionDto introductionSection = generateSectionWithKey(INTRODUCTION_SECTION_KEY);
     RuleDescriptionSectionDto rootCauseSection = generateSectionWithKey(ROOT_CAUSE_SECTION_KEY);
@@ -543,7 +545,7 @@ public class ShowActionIT {
         .addRuleDescriptionSectionDto(assesTheProblemSection)
         .setDescriptionFormat(HTML));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -565,11 +567,11 @@ public class ShowActionIT {
   @Test
   public void returns_html_description_for_custom_rules() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     String description = "== Title\n<div>line1\nline2</div>";
 
@@ -584,7 +586,7 @@ public class ShowActionIT {
         .addRuleDescriptionSectionDto(sectionDto)
         .setDescriptionFormat(MARKDOWN));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -596,15 +598,15 @@ public class ShowActionIT {
   @Test
   public void handles_null_description_for_custom_rules() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     RuleDto rule = newRuleWithoutSection(SECURITY_HOTSPOT, r -> r.setTemplateUuid("123"));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -616,11 +618,11 @@ public class ShowActionIT {
   @Test
   public void handle_given_description_section_with_3_contexts_return_one_alphabetically() {
     ProjectData projectData = dbTester.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    userSessionRule.logIn().addProjectPermission(UserRole.USER, projectData.getProjectDto());
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
 
     RuleDescriptionSectionDto vaadinSection = newContextSpecificDescriptionSection("vaadin");
     RuleDescriptionSectionDto gsonSection = newContextSpecificDescriptionSection("gson");
@@ -633,7 +635,7 @@ public class ShowActionIT {
         .addRuleDescriptionSectionDto(gsonSection)
         .setDescriptionFormat(HTML));
 
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -654,12 +656,12 @@ public class ShowActionIT {
   @Test
   public void returns_hotspot_component_and_rule() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -667,7 +669,7 @@ public class ShowActionIT {
 
     assertThat(response.getKey()).isEqualTo(hotspot.getKey());
     verifyComponent(response.getComponent(), file, null, null);
-    verifyComponent(response.getProject(), project, null, null);
+    verifyProject(response.getProject(), projectData.getProjectDto(), null, null);
     verifyRule(response.getRule(), rule);
     assertThat(response.hasTextRange()).isFalse();
   }
@@ -675,12 +677,12 @@ public class ShowActionIT {
   @Test
   public void returns_no_textRange_when_locations_have_none() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setLocations(DbIssues.Locations.newBuilder().build()));
     mockChangelogAndCommentsFormattingContext();
 
@@ -694,12 +696,12 @@ public class ShowActionIT {
   @UseDataProvider("randomTextRangeValues")
   public void returns_textRange(int startLine, int endLine, int startOffset, int endOffset) {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setLocations(DbIssues.Locations.newBuilder().setTextRange(textRange(startLine, endLine, startOffset, endOffset)).build()));
     mockChangelogAndCommentsFormattingContext();
 
@@ -717,12 +719,12 @@ public class ShowActionIT {
   @Test
   public void returns_no_assignee_when_user_does_not_exist() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(randomAlphabetic(10)));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(randomAlphabetic(10)));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -734,13 +736,13 @@ public class ShowActionIT {
   @Test
   public void returns_assignee_details_when_user_exists() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto assignee = dbTester.users().insertUser();
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(assignee.getUuid()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -758,13 +760,13 @@ public class ShowActionIT {
   @Test
   public void returns_no_avatar_if_assignee_has_no_email() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto assignee = dbTester.users().insertUser(t -> t.setEmail(null));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(assignee.getUuid()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -777,13 +779,13 @@ public class ShowActionIT {
   @Test
   public void returns_inactive_when_assignee_is_inactive() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto assignee = dbTester.users().insertUser(t -> t.setActive(false));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(assignee.getUuid()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -796,13 +798,13 @@ public class ShowActionIT {
   @Test
   public void returns_author_login_when_user_does_not_exist() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     String authorLogin = randomAlphabetic(10);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(authorLogin));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(authorLogin));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -815,13 +817,13 @@ public class ShowActionIT {
   @Test
   public void returns_author_details_when_user_exists() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto author = dbTester.users().insertUser();
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(author.getLogin()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -838,13 +840,13 @@ public class ShowActionIT {
   @Test
   public void returns_no_avatar_if_author_has_no_email() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto author = dbTester.users().insertUser(t -> t.setEmail(null));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(author.getLogin()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -857,13 +859,13 @@ public class ShowActionIT {
   @Test
   public void returns_inactive_if_author_is_inactive() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     UserDto author = dbTester.users().insertUser(t -> t.setActive(false));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(author.getLogin()));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -887,12 +889,12 @@ public class ShowActionIT {
   @Test
   public void returns_textRange_missing_fields() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setLocations(DbIssues.Locations.newBuilder()
         .setTextRange(TextRange.newBuilder().build())
         .build()));
@@ -914,12 +916,12 @@ public class ShowActionIT {
   public void returns_securityCategory_and_vulnerabilityProbability_of_rule(Set<String> standards,
     SQCategory expected) {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT, t -> t.setSecurityStandards(standards));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setLocations(DbIssues.Locations.newBuilder()
         .setTextRange(TextRange.newBuilder().build())
         .build()));
@@ -943,7 +945,7 @@ public class ShowActionIT {
         t.getKey()
       });
     Stream<Object[]> others = Stream.of(
-      new Object[] {Collections.emptySet(), SQCategory.OTHERS},
+      new Object[] {emptySet(), SQCategory.OTHERS},
       new Object[] {ImmutableSet.of("foo", "bar", "acme"), SQCategory.OTHERS});
     return Stream.concat(allButOthers, others)
       .toArray(Object[][]::new);
@@ -952,11 +954,11 @@ public class ShowActionIT {
   @Test
   public void returns_project_twice_when_hotspot_on_project() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, project,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, mainBranchComponent,
       t -> t.setLocations(DbIssues.Locations.newBuilder()
         .setTextRange(TextRange.newBuilder().build())
         .build()));
@@ -965,18 +967,18 @@ public class ShowActionIT {
     Hotspots.ShowWsResponse response = newRequest(hotspot)
       .executeProtobuf(Hotspots.ShowWsResponse.class);
 
-    verifyComponent(response.getProject(), project, null, null);
-    verifyComponent(response.getComponent(), project, null, null);
+    verifyProject(response.getProject(), projectData.getProjectDto(), null, null);
+    verifyComponent(response.getComponent(), mainBranchComponent, null, null);
   }
 
   @Test
   public void returns_branch_but_no_pullRequest_on_component_and_project_on_non_main_branch() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
     String branchName = randomAlphanumeric(248);
-    ComponentDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchName));
-    userSessionRule.addProjectBranchMapping(project.uuid(), branch);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.uuid()));
+    ComponentDto branch = dbTester.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
+    userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), branch);
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
     IssueDto hotspot = dbTester.issues().insertHotspot(rule, branch, file,
@@ -988,18 +990,18 @@ public class ShowActionIT {
     Hotspots.ShowWsResponse response = newRequest(hotspot)
       .executeProtobuf(Hotspots.ShowWsResponse.class);
 
-    verifyComponent(response.getProject(), branch, branchName, null);
+    verifyProject(response.getProject(), projectData.getProjectDto(), branchName, null);
     verifyComponent(response.getComponent(), file, branchName, null);
   }
 
   @Test
   public void returns_pullRequest_but_no_branch_on_component_and_project_on_pullRequest() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
     String pullRequestKey = randomAlphanumeric(100);
-    ComponentDto pullRequest = dbTester.components().insertProjectBranch(project,
+    ComponentDto pullRequest = dbTester.components().insertProjectBranch(mainBranchComponent,
       t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
-    userSessionRule.addProjectBranchMapping(project.uuid(), pullRequest);
+    userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), pullRequest);
     ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
@@ -1012,19 +1014,19 @@ public class ShowActionIT {
     Hotspots.ShowWsResponse response = newRequest(hotspot)
       .executeProtobuf(Hotspots.ShowWsResponse.class);
 
-    verifyComponent(response.getProject(), pullRequest, null, pullRequestKey);
+    verifyProject(response.getProject(), projectData.getProjectDto(), null, pullRequestKey);
     verifyComponent(response.getComponent(), file, null, pullRequestKey);
   }
 
   @Test
   public void returns_hotspot_changelog_and_comments() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setLocations(DbIssues.Locations.newBuilder()
         .setTextRange(TextRange.newBuilder().build())
         .build()));
@@ -1047,10 +1049,7 @@ public class ShowActionIT {
     assertThat(response.getCommentList())
       .extracting(Common.Comment::getKey)
       .containsExactly(comments.stream().map(Common.Comment::getKey).toArray(String[]::new));
-    verify(issueChangeSupport).newFormattingContext(any(DbSession.class),
-      argThat(new IssueDtoSetArgumentMatcher(hotspot)),
-      eq(Load.ALL),
-      eq(Collections.emptySet()), eq(ImmutableSet.of(project, file)));
+    verify(issueChangeSupport).newFormattingContext(any(DbSession.class), argThat(new IssueDtoSetArgumentMatcher(hotspot)), eq(Load.ALL), eq(emptySet()), eq(Set.of(file)));
     verify(issueChangeSupport).formatChangelog(argThat(new IssueDtoArgumentMatcher(hotspot)), eq(formattingContext));
     verify(issueChangeSupport).formatComments(argThat(new IssueDtoArgumentMatcher(hotspot)), any(Common.Comment.Builder.class), eq(formattingContext));
   }
@@ -1058,12 +1057,12 @@ public class ShowActionIT {
   @Test
   public void returns_user_details_of_users_from_ChangelogAndComments() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file);
     FormattingContext formattingContext = mockChangelogAndCommentsFormattingContext();
     Set<UserDto> changeLogAndCommentsUsers = IntStream.range(0, 1 + RANDOM.nextInt(14))
       .mapToObj(i -> UserTesting.newUserDto())
@@ -1084,14 +1083,14 @@ public class ShowActionIT {
   @Test
   public void returns_user_of_users_from_ChangelogAndComments_and_assignee_and_author() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     UserDto author = dbTester.users().insertUser();
     UserDto assignee = dbTester.users().insertUser();
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setAuthorLogin(author.getLogin())
         .setAssigneeUuid(assignee.getUuid()));
     FormattingContext formattingContext = mockChangelogAndCommentsFormattingContext();
@@ -1116,13 +1115,13 @@ public class ShowActionIT {
   @Test
   public void do_not_duplicate_user_if_author_assignee_ChangeLogComment_user() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     UserDto author = dbTester.users().insertUser();
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file,
       t -> t.setAuthorLogin(author.getLogin())
         .setAssigneeUuid(author.getUuid()));
     FormattingContext formattingContext = mockChangelogAndCommentsFormattingContext();
@@ -1139,12 +1138,12 @@ public class ShowActionIT {
   @Test
   public void response_shouldContainCodeVariants() {
     ProjectData projectData = dbTester.components().insertPublicProject();
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto());
-    ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
+    ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
     RuleDto rule = newRule(SECURITY_HOTSPOT);
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setCodeVariants(List.of("variant1", "variant2")));
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setCodeVariants(List.of("variant1", "variant2")));
     mockChangelogAndCommentsFormattingContext();
 
     Hotspots.ShowWsResponse response = newRequest(hotspot)
@@ -1159,13 +1158,13 @@ public class ShowActionIT {
       .setName("test-project")
       .setLongName("test-project")
       .setKey("com.sonarsource:test-project"));
-    ComponentDto project = projectData.getMainBranchComponent();
+    ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
 
     userSessionRule.registerProjects(projectData.getProjectDto())
       .addProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN, projectData.getProjectDto());
 
     ComponentDto file = dbTester.components().insertComponent(
-      newFileDto(project)
+      newFileDto(mainBranchComponent)
         .setKey("com.sonarsource:test-project:src/main/java/com/sonarsource/FourthClass.java")
         .setName("FourthClass.java")
         .setLongName("src/main/java/com/sonarsource/FourthClass.java")
@@ -1178,7 +1177,7 @@ public class ShowActionIT {
       .setRepositoryKey("java")
       .setName("rule-name")
       .setSecurityStandards(Sets.newHashSet(SQCategory.WEAK_CRYPTOGRAPHY.getKey())));
-    IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, h -> h
+    IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, h -> h
       .setAssigneeUuid("assignee-uuid")
       .setAuthorLogin("joe")
       .setMessage("message")
@@ -1257,6 +1256,24 @@ public class ShowActionIT {
     }
   }
 
+  private static void verifyProject(Hotspots.Component wsComponent, ProjectDto dto, @Nullable String branch, @Nullable String pullRequest) {
+    assertThat(wsComponent.getKey()).isEqualTo(dto.getKey());
+    assertThat(wsComponent.hasPath()).isFalse();
+    assertThat(wsComponent.getQualifier()).isEqualTo(dto.getQualifier());
+    assertThat(wsComponent.getName()).isEqualTo(dto.getName());
+    assertThat(wsComponent.getLongName()).isEqualTo(dto.getName());
+    if (branch == null) {
+      assertThat(wsComponent.hasBranch()).isFalse();
+    } else {
+      assertThat(wsComponent.getBranch()).isEqualTo(branch);
+    }
+    if (pullRequest == null) {
+      assertThat(wsComponent.hasPullRequest()).isFalse();
+    } else {
+      assertThat(wsComponent.getPullRequest()).isEqualTo(pullRequest);
+    }
+  }
+
   private static TextRange textRange(int startLine, int endLine, int startOffset, int endOffset) {
     return TextRange.newBuilder()
       .setStartLine(startLine)
index 2f074b1d3868a27cab447c65afacdce81dfb3413..f08fcd042e1b28759e38de29563c8e8484658ecf 100644 (file)
@@ -70,7 +70,7 @@ public class IssueChangeWSSupportIT {
   private static final Random RANDOM = new Random();
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
   @Rule
   public UserSessionRule userSessionRule = UserSessionRule.standalone();
 
@@ -654,11 +654,11 @@ public class IssueChangeWSSupportIT {
   }
 
   private static IssueChangeDto newComment(IssueDto issue) {
-    return IssueTesting.newIssuechangeDto(issue).setChangeType(TYPE_COMMENT);
+    return IssueTesting.newIssueChangeDto(issue).setChangeType(TYPE_COMMENT);
   }
 
   private static IssueChangeDto newFieldChange(IssueDto issue) {
-    return IssueTesting.newIssuechangeDto(issue).setChangeType(TYPE_FIELD_CHANGE);
+    return IssueTesting.newIssueChangeDto(issue).setChangeType(TYPE_FIELD_CHANGE);
   }
 
   @SafeVarargs
index e1a8df1a18a17d27699e0f04aa0cc9941e22e2b1..9d3505b71be71db53f476937134530d1f971c8f6 100644 (file)
@@ -48,7 +48,7 @@ public class IssueFinderIT {
   public UserSessionRule userSession = UserSessionRule.standalone();
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   private RuleDbTester ruleDbTester = new RuleDbTester(db);
   private IssueDbTester issueDbTester = new IssueDbTester(db);
index 844e312972dd757a73bc609db2ab2d585af75c99..16b9ce591649d89f3ca2bfac6d2a8a4ac2c59b78 100644 (file)
@@ -55,7 +55,7 @@ public class WebIssueStorageIT {
   private final System2 system2 = new TestSystem2().setNow(2_000_000_000L);
 
   @org.junit.Rule
-  public DbTester db = DbTester.create(system2);
+  public DbTester db = DbTester.create(system2, true);
 
   private final DbClient dbClient = db.getDbClient();
   private final IssueIndexer issueIndexer = mock(IssueIndexer.class);
index e1db9707d4e32d9ea9c1a9eb45a22e75730bf929..e09284e3f39f83a9a99918c824020ab6b3647760 100644 (file)
@@ -75,7 +75,7 @@ public class AddCommentActionIT {
 
 
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
 
   @Rule
   public EsTester es = EsTester.create();
index eb0ce958b7d145998f708ad87a421c4fc7603a00..0583e5454c13ea7802542c829d43b547c26a2bd5 100644 (file)
@@ -75,7 +75,7 @@ public class AssignActionIT {
   @Rule
   public EsTester es = EsTester.create();
   @Rule
-  public DbTester db = DbTester.create(system2);
+  public DbTester db = DbTester.create(system2, true);
   public DbClient dbClient = db.getDbClient();
   private DbSession session = db.getSession();
   private NotificationManager notificationManager = mock(NotificationManager.class);
index 3904df5dd7f623fb609a0f6a65fa11fbe918d38b..183d311e612fe2e9e9d936d933fe95279873d8b0 100644 (file)
@@ -26,10 +26,7 @@ import org.sonar.api.server.ws.WebService.Param;
 import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ProjectData;
-import org.sonar.db.component.ResourceTypesRule;
 import org.sonar.db.rule.RuleDto;
-import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.es.EsTester;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.exceptions.UnauthorizedException;
@@ -54,7 +51,6 @@ import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.sonar.api.resources.Qualifiers.PROJECT;
 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
 import static org.sonar.db.component.ComponentTesting.newFileDto;
@@ -63,7 +59,7 @@ import static org.sonar.test.JsonAssert.assertJson;
 
 public class AuthorsActionIT {
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
   @Rule
@@ -75,20 +71,18 @@ public class AuthorsActionIT {
   private final PermissionIndexerTester permissionIndexer = new PermissionIndexerTester(es, issueIndexer);
   private final ViewIndexer viewIndexer = new ViewIndexer(db.getDbClient(), es.client());
   private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
-  private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT);
   private final WsActionTester ws = new WsActionTester(new AuthorsAction(userSession, db.getDbClient(), issueIndex,
-    issueIndexSyncProgressChecker, new ComponentFinder(db.getDbClient(), resourceTypes)));
+    issueIndexSyncProgressChecker));
 
   @Test
   public void search_authors() {
     String leia = "leia.organa";
     String luke = "luke.skywalker";
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranchComponent));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
+    db.issues().insertIssue(rule, mainBranchComponent, mainBranchComponent, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, mainBranchComponent, mainBranchComponent, issue -> issue.setAuthorLogin(luke));
     indexIssues();
     userSession.logIn();
 
@@ -102,12 +96,11 @@ public class AuthorsActionIT {
   public void search_authors_by_query() {
     String leia = "leia.organa";
     String luke = "luke.skywalker";
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto mainBranchComponent = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranchComponent));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
+    db.issues().insertIssue(rule, mainBranchComponent, mainBranchComponent, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, mainBranchComponent, mainBranchComponent, issue -> issue.setAuthorLogin(luke));
     indexIssues();
     userSession.logIn();
 
@@ -124,45 +117,42 @@ public class AuthorsActionIT {
   public void search_authors_by_project() {
     String leia = "leia.organa";
     String luke = "luke.skywalker";
-    ProjectData projectData1 = db.components().insertPrivateProject();
-    ComponentDto project1 = projectData1.getMainBranchComponent();
-    ProjectData projectData2 = db.components().insertPrivateProject();
-    ComponentDto project2 = projectData2.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData1.getProjectDto(), projectData2.getProjectDto());
+    ComponentDto mainBranch1 = db.components().insertPrivateProject().getMainBranchComponent();
+    ComponentDto mainBranch2 = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranch1), db.components().getProjectDtoByMainBranch(mainBranch2));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project1, project1, issue -> issue.setAuthorLogin(leia));
-    db.issues().insertIssue(rule, project2, project2, issue -> issue.setAuthorLogin(luke));
+    db.issues().insertIssue(rule, mainBranch1, mainBranch1, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, mainBranch2, mainBranch2, issue -> issue.setAuthorLogin(luke));
     indexIssues();
     userSession.logIn();
 
     assertThat(ws.newRequest()
-      .setParam("project", project1.getKey())
+      .setParam("project", mainBranch1.getKey())
       .executeProtobuf(AuthorsResponse.class).getAuthorsList())
-        .containsExactlyInAnyOrder(leia);
+      .containsExactlyInAnyOrder(leia);
     assertThat(ws.newRequest()
-      .setParam("project", project1.getKey())
+      .setParam("project", mainBranch1.getKey())
       .setParam(TEXT_QUERY, "eia")
       .executeProtobuf(AuthorsResponse.class).getAuthorsList())
-        .containsExactlyInAnyOrder(leia);
+      .containsExactlyInAnyOrder(leia);
     assertThat(ws.newRequest()
-      .setParam("project", project1.getKey())
+      .setParam("project", mainBranch1.getKey())
       .setParam(TEXT_QUERY, "luke")
       .executeProtobuf(AuthorsResponse.class).getAuthorsList())
-        .isEmpty();
+      .isEmpty();
 
-    verify(issueIndexSyncProgressChecker, times(3)).checkIfComponentNeedIssueSync(any(), eq(project1.getKey()));
+    verify(issueIndexSyncProgressChecker, times(3)).checkIfComponentNeedIssueSync(any(), eq(mainBranch1.getKey()));
   }
 
   @Test
   public void search_authors_by_portfolio() {
     String leia = "leia.organa";
     ComponentDto portfolio = db.components().insertPrivatePortfolio();
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    db.components().insertComponent(newProjectCopy(project, portfolio));
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto mainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    db.components().insertComponent(newProjectCopy(mainBranch, portfolio));
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranch));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin(leia));
     indexIssues();
     viewIndexer.indexAll();
     userSession.logIn();
@@ -170,27 +160,26 @@ public class AuthorsActionIT {
     assertThat(ws.newRequest()
       .setParam("project", portfolio.getKey())
       .executeProtobuf(AuthorsResponse.class).getAuthorsList())
-        .containsExactlyInAnyOrder(leia);
+      .containsExactlyInAnyOrder(leia);
   }
 
   @Test
   public void search_authors_by_application() {
     String leia = "leia.organa";
-    ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    db.components().insertComponent(newProjectCopy(project, application));
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto appMainBranch = db.components().insertPrivateApplication().getMainBranchComponent();
+    ComponentDto projectMainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    db.components().insertComponent(newProjectCopy(projectMainBranch, appMainBranch));
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(projectMainBranch));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, projectMainBranch, projectMainBranch, issue -> issue.setAuthorLogin(leia));
     indexIssues();
     viewIndexer.indexAll();
     userSession.logIn();
 
     assertThat(ws.newRequest()
-      .setParam("project", application.getKey())
+      .setParam("project", appMainBranch.getKey())
       .executeProtobuf(AuthorsResponse.class).getAuthorsList())
-        .containsExactlyInAnyOrder(leia);
+      .containsExactlyInAnyOrder(leia);
   }
 
   @Test
@@ -198,13 +187,12 @@ public class AuthorsActionIT {
     String han = "han.solo";
     String leia = "leia.organa";
     String luke = "luke.skywalker";
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto mainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranch));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(han));
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin(han));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin(leia));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin(luke));
     indexIssues();
     userSession.logIn();
 
@@ -220,10 +208,9 @@ public class AuthorsActionIT {
   @Test
   public void should_ignore_authors_of_hotspot() {
     String luke = "luke.skywalker";
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
-    db.issues().insertHotspot(project, project, issue -> issue
+    ComponentDto mainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranch));
+    db.issues().insertHotspot(mainBranch, mainBranch, issue -> issue
       .setAuthorLogin(luke));
     indexIssues();
     userSession.logIn();
@@ -245,23 +232,6 @@ public class AuthorsActionIT {
       .isInstanceOf(UnauthorizedException.class);
   }
 
-  @Test
-  public void fail_when_project_is_not_a_project() {
-    userSession.logIn();
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    ComponentDto file = db.components().insertComponent(newFileDto(project));
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
-
-    assertThatThrownBy(() -> {
-      ws.newRequest()
-        .setParam("project", file.getKey())
-        .execute();
-    })
-      .isInstanceOf(NotFoundException.class)
-      .hasMessage(format("Component '%s' not found", file.getKey()));
-  }
-
   @Test
   public void fail_when_project_does_not_exist() {
     userSession.logIn();
@@ -272,17 +242,16 @@ public class AuthorsActionIT {
         .execute();
     })
       .isInstanceOf(NotFoundException.class)
-      .hasMessage("Component 'unknown' not found");
+      .hasMessage("Entity not found: unknown");
   }
 
   @Test
   public void json_example() {
-    ProjectData projectData = db.components().insertPrivateProject();
-    ComponentDto project = projectData.getMainBranchComponent();
-    permissionIndexer.allowOnlyAnyone(projectData.getProjectDto());
+    ComponentDto mainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    permissionIndexer.allowOnlyAnyone(db.components().getProjectDtoByMainBranch(mainBranch));
     RuleDto rule = db.rules().insertIssueRule();
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin("luke.skywalker"));
-    db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin("leia.organa"));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin("luke.skywalker"));
+    db.issues().insertIssue(rule, mainBranch, mainBranch, issue -> issue.setAuthorLogin("leia.organa"));
     indexIssues();
     userSession.logIn();
 
index 17c9d0c420797e84a3f7c8e0134cec42f980eb25..f469d127ee8806142e7d25d22f0b0ecc68945fbd 100644 (file)
@@ -59,7 +59,7 @@ import static org.sonar.test.JsonAssert.assertJson;
 public class ChangelogActionIT {
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
index eca330c8545fa542a45b4a6d9c209783ddcc2a32..e90b40a2677641ee871317725f78b8fdf95250d8 100644 (file)
@@ -83,7 +83,7 @@ public class DoTransitionActionIT {
   private System2 system2 = new TestSystem2().setNow(NOW);
 
   @Rule
-  public DbTester db = DbTester.create(system2);
+  public DbTester db = DbTester.create(system2, true);
 
   @Rule
   public EsTester es = EsTester.create();
index a9b45330c532dca0316050f3fbe7c2ea17017614..206236b20ab10b631a0e77235fd00820f4b0367c 100644 (file)
@@ -23,6 +23,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -32,9 +33,11 @@ import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDbTester;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
 import org.sonar.db.component.ResourceTypesRule;
 import org.sonar.db.issue.IssueDbTester;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbCommons;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.rule.RuleDto;
@@ -71,7 +74,7 @@ public class PullActionIT {
   public UserSessionRule userSession = UserSessionRule.standalone();
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   private final System2 system2 = mock(System2.class);
   private final TaintChecker taintChecker = mock(TaintChecker.class);
@@ -87,19 +90,22 @@ public class PullActionIT {
   private final WsActionTester tester = new WsActionTester(underTest);
 
   private RuleDto correctRule, incorrectRule;
-  private ComponentDto correctProject, incorrectProject;
+  private ComponentDto correctMainBranch, incorrectMainBranch;
+  private ProjectDto project;
   private ComponentDto correctFile, incorrectFile;
 
   @Before
   public void setUp() {
     when(system2.now()).thenReturn(NOW);
     correctRule = db.rules().insertIssueRule();
-    correctProject = db.components().insertPrivateProject().getMainBranchComponent();
-    correctFile = db.components().insertComponent(newFileDto(correctProject));
+    ProjectData projectData = db.components().insertPrivateProject();
+    correctMainBranch = projectData.getMainBranchComponent();
+    project = projectData.getProjectDto();
+    correctFile = db.components().insertComponent(newFileDto(correctMainBranch));
 
     incorrectRule = db.rules().insertIssueRule();
-    incorrectProject = db.components().insertPrivateProject().getMainBranchComponent();
-    incorrectFile = db.components().insertComponent(newFileDto(incorrectProject));
+    incorrectMainBranch = db.components().insertPrivateProject().getMainBranchComponent();
+    incorrectFile = db.components().insertComponent(newFileDto(incorrectMainBranch));
 
     when(taintChecker.getTaintRepositories()).thenReturn(List.of("roslyn.sonaranalyzer.security.cs",
       "javasecurity", "jssecurity", "tssecurity", "phpsecurity", "pythonsecurity"));
@@ -129,7 +135,7 @@ public class PullActionIT {
     userSession.logIn();
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     assertThatThrownBy(request::execute)
@@ -267,7 +273,7 @@ public class PullActionIT {
     ComponentDto developBranch = db.components().insertPrivateProjectWithCustomBranch("develop").getMainBranchComponent();
     ComponentDto developFile = db.components().insertComponent(newFileDto(developBranch));
     generateIssues(correctRule, developBranch, developFile, 1);
-    loginWithBrowsePermission(developBranch.uuid(), developFile.uuid());
+    loginWithBrowsePermission(developBranch.branchUuid());
 
     TestRequest request = tester.newRequest()
       .setParam("projectKey", developBranch.getKey())
@@ -313,12 +319,12 @@ public class PullActionIT {
 
   @Test
   public void given15IssuesInTheTable_returnOnly10ThatBelongToProject() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
-    generateIssues(correctRule, correctProject, correctFile, 10);
-    generateIssues(incorrectRule, incorrectProject, incorrectFile, 5);
+    loginWithBrowsePermission(project);
+    generateIssues(correctRule, correctMainBranch, correctFile, 10);
+    generateIssues(incorrectRule, incorrectMainBranch, incorrectFile, 5);
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     TestResponse response = request.execute();
@@ -329,11 +335,11 @@ public class PullActionIT {
 
   @Test
   public void givenNoIssuesBelongToTheProject_return0Issues() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
-    generateIssues(incorrectRule, incorrectProject, incorrectFile, 5);
+    loginWithBrowsePermission(project);
+    generateIssues(incorrectRule, incorrectMainBranch, incorrectFile, 5);
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH);
 
     TestResponse response = request.execute();
@@ -344,7 +350,7 @@ public class PullActionIT {
 
   @Test
   public void testLanguagesParam_return1Issue() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setLanguage("java"));
 
     IssueDto javaIssue = issueDbTester.insertIssue(p -> p.setSeverity("MINOR")
@@ -355,12 +361,12 @@ public class PullActionIT {
       .setRuleUuid(javaRule.getUuid())
       .setStatus(Issue.STATUS_OPEN)
       .setLanguage("java")
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile)
       .setType(Common.RuleType.BUG.getNumber()));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("languages", "java");
 
@@ -373,7 +379,7 @@ public class PullActionIT {
 
   @Test
   public void testLanguagesParam_givenWrongLanguage_return0Issues() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javascriptRule = db.rules().insert(r -> r.setLanguage("javascript"));
 
     issueDbTester.insertIssue(p -> p.setSeverity("MINOR")
@@ -383,12 +389,12 @@ public class PullActionIT {
       .setRule(javascriptRule)
       .setRuleUuid(javascriptRule.getUuid())
       .setStatus(Issue.STATUS_OPEN)
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile)
       .setType(2));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("languages", "java");
 
@@ -400,7 +406,7 @@ public class PullActionIT {
 
   @Test
   public void testRuleRepositoriesParam_return1IssueForGivenRepository() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setRepositoryKey("java"));
     RuleDto javaScriptRule = db.rules().insert(r -> r.setRepositoryKey("javascript"));
 
@@ -410,7 +416,7 @@ public class PullActionIT {
       .setCreatedAt(NOW)
       .setRule(javaRule)
       .setStatus(Issue.STATUS_OPEN)
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile)
       .setType(2));
 
@@ -421,12 +427,12 @@ public class PullActionIT {
       .setCreatedAt(NOW)
       .setRule(javaScriptRule)
       .setStatus(Issue.STATUS_OPEN)
-      .setProject(correctProject)
+      .setProject(correctMainBranch)
       .setComponent(correctFile)
       .setType(Common.RuleType.BUG.getNumber()));
 
     TestRequest request = tester.newRequest()
-      .setParam("projectKey", correctProject.getKey())
+      .setParam("projectKey", correctMainBranch.getKey())
       .setParam("branchName", DEFAULT_BRANCH)
       .setParam("ruleRepositories", "java");
 
@@ -460,15 +466,18 @@ public class PullActionIT {
   }
 
   private void loginWithBrowsePermission(IssueDto issueDto) {
-    loginWithBrowsePermission(issueDto.getProjectUuid(), issueDto.getComponentUuid());
+    loginWithBrowsePermission(issueDto.getProjectUuid());
   }
 
-  private void loginWithBrowsePermission(String projectUuid, String componentUuid) {
+  private void loginWithBrowsePermission(String branchUuid) {
+    Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectByBranchUuid(db.getSession(), branchUuid);
+    loginWithBrowsePermission(projectDto.get());
+  }
+
+  private void loginWithBrowsePermission(ProjectDto projectDto) {
     UserDto user = db.users().insertUser("john");
     userSession.logIn(user)
-      .addProjectPermission(USER,
-        db.getDbClient().componentDao().selectByUuid(db.getSession(), projectUuid).get(),
-        db.getDbClient().componentDao().selectByUuid(db.getSession(), componentUuid).get());
+      .addProjectPermission(USER, projectDto);
   }
 
 }
index 41b81fa2b982be1086fa435258bbdbbed92ea437..b1dae4cbea6c10700a642d2ec692d3d5cf5e55e7 100644 (file)
@@ -23,6 +23,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -32,9 +33,11 @@ import org.sonar.api.utils.System2;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ComponentDbTester;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ProjectData;
 import org.sonar.db.component.ResourceTypesRule;
 import org.sonar.db.issue.IssueDbTester;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbCommons;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.rule.RuleDto;
@@ -75,7 +78,7 @@ public class PullTaintActionIT {
   public UserSessionRule userSession = UserSessionRule.standalone();
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   private final System2 system2 = mock(System2.class);
   private final TaintChecker taintChecker = mock(TaintChecker.class);
@@ -90,6 +93,7 @@ public class PullTaintActionIT {
 
   private RuleDto correctRule, incorrectRule;
   private ComponentDto correctProject, incorrectProject;
+  private ProjectDto project;
   private ComponentDto correctFile, incorrectFile;
 
   @Before
@@ -99,7 +103,9 @@ public class PullTaintActionIT {
     db.getDbClient().ruleRepositoryDao().insert(db.getSession(), List.of(repository));
     correctRule = db.rules().insertIssueRule(r -> r.setRepositoryKey("javasecurity").setRuleKey("S1000").setSeverity(3));
 
-    correctProject = db.components().insertPrivateProject().getMainBranchComponent();
+    ProjectData projectData = db.components().insertPrivateProject();
+    correctProject = projectData.getMainBranchComponent();
+    project = projectData.getProjectDto();
     correctFile = db.components().insertComponent(newFileDto(correctProject));
 
     incorrectRule = db.rules().insertIssueRule();
@@ -207,7 +213,7 @@ public class PullTaintActionIT {
 
   @Test
   public void givenValidProjectKeyAndOneTaintOnBranch_returnOneTaint_WithMetadataSeverity() throws IOException {
-    loginWithBrowsePermission(correctProject.branchUuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     DbCommons.TextRange textRange = DbCommons.TextRange.newBuilder()
       .setStartLine(1)
       .setEndLine(2)
@@ -266,7 +272,7 @@ public class PullTaintActionIT {
     ComponentDto developBranch = db.components().insertPrivateProjectWithCustomBranch("develop").getMainBranchComponent();
     ComponentDto developFile = db.components().insertComponent(newFileDto(developBranch));
     generateTaints(correctRule, developBranch, developFile, 1);
-    loginWithBrowsePermission(developBranch.uuid(), developFile.uuid());
+    loginWithBrowsePermission(developBranch.uuid());
 
     TestRequest request = tester.newRequest()
       .setParam("projectKey", developBranch.getKey())
@@ -280,7 +286,7 @@ public class PullTaintActionIT {
 
   @Test
   public void given15TaintsInTheTable_returnOnly10ThatBelongToProject() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     generateTaints(correctRule, correctProject, correctFile, 10);
     generateTaints(incorrectRule, incorrectProject, incorrectFile, 5);
 
@@ -296,7 +302,7 @@ public class PullTaintActionIT {
 
   @Test
   public void givenNoTaintsBelongToTheProject_return0Taints() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     generateTaints(incorrectRule, incorrectProject, incorrectFile, 5);
 
     TestRequest request = tester.newRequest()
@@ -311,7 +317,7 @@ public class PullTaintActionIT {
 
   @Test
   public void testLanguagesParam_return1Taint() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setLanguage("java").setRepositoryKey("javasecurity"));
     RuleDto javascriptRule = db.rules().insert(r -> r.setLanguage("javascript").setRepositoryKey("javasecurity"));
 
@@ -353,7 +359,7 @@ public class PullTaintActionIT {
 
   @Test
   public void testLanguagesParam_givenWrongLanguage_return0Taints() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javascriptRule = db.rules().insert(r -> r.setLanguage("jssecurity"));
 
     issueDbTester.insertIssue(p -> p.setSeverity("MINOR")
@@ -380,7 +386,7 @@ public class PullTaintActionIT {
 
   @Test
   public void given1TaintAnd1NormalIssue_return1Taint() throws IOException {
-    loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+    loginWithBrowsePermission(project);
     RuleDto javaRule = db.rules().insert(r -> r.setRepositoryKey("javasecurity"));
     RuleDto javaScriptRule = db.rules().insert(r -> r.setRepositoryKey("javascript"));
 
@@ -488,15 +494,18 @@ public class PullTaintActionIT {
   }
 
   private void loginWithBrowsePermission(IssueDto issueDto) {
-    loginWithBrowsePermission(issueDto.getProjectUuid(), issueDto.getComponentUuid());
+    loginWithBrowsePermission(issueDto.getProjectUuid());
   }
 
-  private void loginWithBrowsePermission(String projectUuid, String componentUuid) {
+  private void loginWithBrowsePermission(String branchUuid) {
+    Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectByBranchUuid(db.getSession(), branchUuid);
+    loginWithBrowsePermission(projectDto.get());
+  }
+
+  private void loginWithBrowsePermission(ProjectDto project) {
     UserDto user = db.users().insertUser("john");
     userSession.logIn(user)
-      .addProjectPermission(USER,
-        db.getDbClient().componentDao().selectByUuid(db.getSession(), projectUuid).get(),
-        db.getDbClient().componentDao().selectByUuid(db.getSession(), componentUuid).get());
+      .addProjectPermission(USER, project);
   }
 
 }
index cc0564d78a3f26a4f2c4bd37257fab313987fd3d..1ecc574bcd153d2ad3bf2afb35cb82ce38afb522 100644 (file)
@@ -87,26 +87,26 @@ public class SearchActionComponentsIT {
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
 
-  private DbClient dbClient = db.getDbClient();
-  private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession));
-  private IssueIndexer issueIndexer = new IssueIndexer(es.client(), dbClient, new IssueIteratorFactory(dbClient), null);
-  private ViewIndexer viewIndexer = new ViewIndexer(dbClient, es.client());
-  private IssueQueryFactory issueQueryFactory = new IssueQueryFactory(dbClient, Clock.systemUTC(), userSession);
-  private IssueFieldsSetter issueFieldsSetter = new IssueFieldsSetter();
-  private IssueWorkflow issueWorkflow = new IssueWorkflow(new FunctionExecutor(issueFieldsSetter), issueFieldsSetter);
-  private SearchResponseLoader searchResponseLoader = new SearchResponseLoader(userSession, dbClient, new TransitionService(userSession, issueWorkflow));
-  private Languages languages = new Languages();
-  private UserResponseFormatter userFormatter = new UserResponseFormatter(new AvatarResolverImpl());
-  private SearchResponseFormat searchResponseFormat = new SearchResponseFormat(new Durations(), languages, new TextRangeResponseFormatter(), userFormatter);
-  private PermissionIndexerTester permissionIndexer = new PermissionIndexerTester(es, issueIndexer);
-
-  private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = new IssueIndexSyncProgressChecker(db.getDbClient());
-
-  private WsActionTester ws = new WsActionTester(
+  private final DbClient dbClient = db.getDbClient();
+  private final IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession));
+  private final IssueIndexer issueIndexer = new IssueIndexer(es.client(), dbClient, new IssueIteratorFactory(dbClient), null);
+  private final ViewIndexer viewIndexer = new ViewIndexer(dbClient, es.client());
+  private final IssueQueryFactory issueQueryFactory = new IssueQueryFactory(dbClient, Clock.systemUTC(), userSession);
+  private final IssueFieldsSetter issueFieldsSetter = new IssueFieldsSetter();
+  private final IssueWorkflow issueWorkflow = new IssueWorkflow(new FunctionExecutor(issueFieldsSetter), issueFieldsSetter);
+  private final SearchResponseLoader searchResponseLoader = new SearchResponseLoader(userSession, dbClient, new TransitionService(userSession, issueWorkflow));
+  private final Languages languages = new Languages();
+  private final UserResponseFormatter userFormatter = new UserResponseFormatter(new AvatarResolverImpl());
+  private final SearchResponseFormat searchResponseFormat = new SearchResponseFormat(new Durations(), languages, new TextRangeResponseFormatter(), userFormatter);
+  private final PermissionIndexerTester permissionIndexer = new PermissionIndexerTester(es, issueIndexer);
+
+  private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = new IssueIndexSyncProgressChecker(db.getDbClient());
+
+  private final WsActionTester ws = new WsActionTester(
     new SearchAction(userSession, issueIndex, issueQueryFactory, issueIndexSyncProgressChecker, searchResponseLoader, searchResponseFormat,
       System2.INSTANCE, dbClient));
 
@@ -325,7 +325,8 @@ public class SearchActionComponentsIT {
     IssueDto issue1 = db.issues().insertIssue(rule, project1, project1);
     IssueDto issue2 = db.issues().insertIssue(rule, project2, project2);
     allowAnyoneOnApplication(applicationData.getProjectDto(), projectData1.getProjectDto(), projectData2.getProjectDto());
-    userSession.addProjectPermission(USER, application);
+    userSession.addProjectPermission(USER, applicationData.getProjectDto());
+    userSession.addProjectBranchMapping(applicationData.projectUuid(), application);
     indexIssuesAndViews();
 
     SearchWsResponse result = ws.newRequest()
@@ -451,6 +452,7 @@ public class SearchActionComponentsIT {
     IssueDto project2Issue2 = db.issues().insertIssue(rule, project2, project2, i -> i.setIssueCreationDate(addDays(now, -30)));
     // Permissions and index
     allowAnyoneOnApplication(applicationData.getProjectDto(), projectData1.getProjectDto(), projectData2.getProjectDto());
+    userSession.addProjectBranchMapping(applicationData.projectUuid(), application);
     indexIssuesAndViews();
 
     SearchWsResponse result = ws.newRequest()
@@ -477,6 +479,7 @@ public class SearchActionComponentsIT {
     IssueDto issue1 = db.issues().insertIssue(rule, project1, project1);
     IssueDto issue2 = db.issues().insertIssue(rule, project2, project2);
     allowAnyoneOnApplication(applicationData.getProjectDto(), projectData1.getProjectDto(), projectData2.getProjectDto());
+    userSession.addProjectBranchMapping(applicationData.getProjectDto().getUuid(), application);
     indexIssuesAndViews();
 
     SearchWsResponse result = ws.newRequest()
@@ -511,6 +514,7 @@ public class SearchActionComponentsIT {
     IssueDto project2Issue2 = db.issues().insertIssue(rule, project2, project2, i -> i.setIssueCreationDate(addDays(now, -30)));
     // Permissions and index
     allowAnyoneOnApplication(applicationData.getProjectDto(), projectData1.getProjectDto(), projectData2.getProjectDto());
+    userSession.addProjectBranchMapping(applicationData.projectUuid(), application);
     indexIssuesAndViews();
 
     SearchWsResponse result = ws.newRequest()
@@ -546,6 +550,7 @@ public class SearchActionComponentsIT {
     IssueDto project2Issue2 = db.issues().insertIssue(rule, project2, project2, i -> i.setIssueCreationDate(addDays(now, -30)));
     // Permissions and index
     allowAnyoneOnApplication(applicationData.getProjectDto(), projectData1.getProjectDto(), projectData2.getProjectDto());
+    userSession.addProjectBranchMapping(applicationData.projectUuid(), application);
     indexIssuesAndViews();
 
     SearchWsResponse result = ws.newRequest()
index d975f360a1a8a100de471b6e61120864468f5c21..8d2d1a009cd302af2a77943aef19f3b4267facad 100644 (file)
@@ -74,7 +74,7 @@ public class SearchActionFacetsIT {
   @Rule
   public UserSessionRule userSession = standalone();
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
 
index 07e45cb9b15d0d35958574930bc451b573668bf5..0f765cb8196270979b0c79066d28ba6fec4440c7 100644 (file)
@@ -135,7 +135,7 @@ public class SearchActionIT {
   @Rule
   public UserSessionRule userSession = standalone();
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
 
@@ -469,7 +469,8 @@ public class SearchActionIT {
     UserDto simon = db.users().insertUser(u -> u.setLogin("simon").setName("Simon").setEmail("simon@email.com"));
     UserDto fabrice = db.users().insertUser(u -> u.setLogin("fabrice").setName("Fabrice").setEmail("fabrice@email.com"));
 
-    ProjectData project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java"));
+    ProjectData project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID").setLanguage("java"));
     grantPermissionToAnyone(project.getProjectDto(), ISSUE_ADMIN);
     indexPermissions();
     ComponentDto file = db.components().insertComponent(newFileDto(project.getMainBranchComponent(), null, "FILE_ID").setKey("FILE_KEY").setLanguage("js"));
@@ -492,7 +493,8 @@ public class SearchActionIT {
   @Test
   public void search_by_rule_key() {
     RuleDto rule = newIssueRule();
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID").setLanguage("java")).getMainBranchComponent();
     ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("java"));
 
     db.issues().insertIssue(rule, project, file);
@@ -536,7 +538,8 @@ public class SearchActionIT {
   @Test
   public void search_by_non_existing_rule_key() {
     RuleDto rule = newIssueRule();
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID").setLanguage("java")).getMainBranchComponent();
     ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("java"));
 
     db.issues().insertIssue(rule, project, file);
@@ -557,7 +560,8 @@ public class SearchActionIT {
   @Test
   public void search_by_variants_with_facets() {
     RuleDto rule = newIssueRule();
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY").setLanguage("java")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID").setLanguage("java")).getMainBranchComponent();
     ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY").setLanguage("java"));
     db.issues().insertIssue(rule, project, file, i -> i.setCodeVariants(List.of("variant1")));
     db.issues().insertIssue(rule, project, file, i -> i.setCodeVariants(List.of("variant2")));
@@ -664,7 +668,8 @@ public class SearchActionIT {
   public void filter_by_new_code_period() {
     UserDto john = db.users().insertUser(u -> u.setLogin("john").setName("John").setEmail("john@email.com"));
     UserDto alice = db.users().insertUser(u -> u.setLogin("alice").setName("Alice").setEmail("alice@email.com"));
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID")).getMainBranchComponent();
     SnapshotDto snapshotDto = db.components().insertSnapshot(project, s -> s.setLast(true).setPeriodDate(parseDateTime("2014-09-05T00:00:00+0100").getTime()));
     indexPermissions();
 
@@ -914,7 +919,9 @@ public class SearchActionIT {
 
   @Test
   public void filter_by_test_scope() {
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")).getMainBranchComponent();
+    ProjectData projectData = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID"));
+    ComponentDto project = projectData.getMainBranchComponent();
     indexPermissions();
     ComponentDto mainCodeFile = db.components().insertComponent(
       newFileDto(project, null, "FILE_ID").setKey("FILE_KEY"));
@@ -955,7 +962,8 @@ public class SearchActionIT {
 
   @Test
   public void filter_by_main_scope() {
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID")).getMainBranchComponent();
     indexPermissions();
     ComponentDto mainCodeFile = db.components().insertComponent(
       newFileDto(project, null, "FILE_ID").setKey("FILE_KEY"));
@@ -996,7 +1004,8 @@ public class SearchActionIT {
 
   @Test
   public void filter_by_scope_always_returns_all_scope_facet_values() {
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID")).getMainBranchComponent();
     indexPermissions();
     ComponentDto mainCodeFile = db.components().insertComponent(
       newFileDto(project, null, "FILE_ID").setKey("FILE_KEY"));
@@ -1029,7 +1038,8 @@ public class SearchActionIT {
   @Test
   public void sort_by_updated_at() {
     RuleDto rule = newIssueRule();
-    ComponentDto project = db.components().insertPublicProject("PROJECT_ID", c -> c.setKey("PROJECT_KEY")).getMainBranchComponent();
+    ComponentDto project = db.components().insertPublicProject("PROJECT_ID",
+      c -> c.setKey("PROJECT_KEY").setName("NAME_PROJECT_ID").setLongName("LONG_NAME_PROJECT_ID")).getMainBranchComponent();
     indexPermissions();
     ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setKey("FILE_KEY"));
     dbClient.issueDao().insert(session, newIssue(rule, project, file)
@@ -1135,7 +1145,6 @@ public class SearchActionIT {
     assertThat(result.getIssuesList())
       .extracting(Issue::getKey)
       .containsExactlyInAnyOrder(issueDto1.getKey(), issueDto3.getKey());
-
   }
 
   @Test
index 25f5602b8899b66dac925ec693670a085f535d58..7c0ad40546605df568ae382e12323414d1fb5978 100644 (file)
@@ -78,7 +78,7 @@ import static org.sonar.db.component.ComponentTesting.newPublicProjectDto;
 public class SetTagsActionIT {
 
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   @Rule
   public EsTester es = EsTester.create();
   @Rule
@@ -192,7 +192,7 @@ public class SetTagsActionIT {
     IssueDto issueDto = db.issues().insertIssue();
     logInAndAddProjectPermission(issueDto, ISSUE_ADMIN);
 
-    assertThatThrownBy(() ->  call(issueDto.getKey(), "bug"))
+    assertThatThrownBy(() -> call(issueDto.getKey(), "bug"))
       .isInstanceOf(ForbiddenException.class);
   }
 
@@ -247,9 +247,13 @@ public class SetTagsActionIT {
 
   private void logIn(IssueDto issueDto) {
     UserDto user = db.users().insertUser("john");
-    ProjectDto projectDto = retrieveProjectDto(issueDto);
+    BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), issueDto.getProjectUuid())
+      .orElseThrow();
+    ProjectDto projectDto = db.getDbClient().projectDao().selectByUuid(db.getSession(), branchDto.getProjectUuid())
+      .orElseThrow();
     userSession.logIn(user)
-      .registerProjects(projectDto);
+      .registerProjects(projectDto)
+      .registerBranches(branchDto);
   }
 
   @NotNull
index 30f34056ab2ea778c825636bab112fec485006fe..a4390a180bb97d982d23d21df5387e6f460dddb8 100644 (file)
@@ -71,14 +71,14 @@ public class TagsActionIT {
   @Rule
   public EsTester es = EsTester.create();
 
-  private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession));
-  private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
-  private IssueIndexer issueIndexer = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null);
-  private ViewIndexer viewIndexer = new ViewIndexer(db.getDbClient(), es.client());
-  private PermissionIndexerTester permissionIndexer = new PermissionIndexerTester(es, issueIndexer);
-  private ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT);
-
-  private WsActionTester ws = new WsActionTester(new TagsAction(issueIndex, issueIndexSyncProgressChecker, db.getDbClient(), new ComponentFinder(db.getDbClient(), resourceTypes)));
+  private final IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession));
+  private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
+  private final IssueIndexer issueIndexer = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null);
+  private final ViewIndexer viewIndexer = new ViewIndexer(db.getDbClient(), es.client());
+  private final PermissionIndexerTester permissionIndexer = new PermissionIndexerTester(es, issueIndexer);
+  private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT);
+
+  private final WsActionTester ws = new WsActionTester(new TagsAction(issueIndex, issueIndexSyncProgressChecker, db.getDbClient(), new ComponentFinder(db.getDbClient(), resourceTypes)));
 
   @Test
   public void search_tags() {
index 75b2bc885219627990e966d8862639ede7a8f13b..b3f5d795494c2b0eb3b99c17c1f1b351337a5325 100644 (file)
@@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.tuple;
 public class SearchActionIT {
 
   @Rule
-  public DbTester db = DbTester.create(System2.INSTANCE);
+  public DbTester db = DbTester.create(System2.INSTANCE, true);
 
   private final DbClient dbClient = db.getDbClient();
   private final DbSession dbSession = db.getSession();
index f6c058b9dbe33a261a1109fd36c1258f22821553..13542b317642cf3f32918e4029483896743fd679 100644 (file)
@@ -56,10 +56,9 @@ public class CreateActionIT {
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE);
 
-  private DbClient dbClient = db.getDbClient();
-  private DbSession dbSession = db.getSession();
-
-  private WsActionTester ws = new WsActionTester(new CreateAction(dbClient, userSession, TestComponentFinder.from(db), UuidFactoryFast.getInstance()));
+  private final DbClient dbClient = db.getDbClient();
+  private final DbSession dbSession = db.getSession();
+  private final WsActionTester ws = new WsActionTester(new CreateAction(dbClient, userSession, TestComponentFinder.from(db), UuidFactoryFast.getInstance()));
 
   @Test
   public void example_with_key() {
index 0f3637ac02326ca3533a56b62736dc414c4f86e4..05e3e7c351304353016012e4533495d1c58d3976 100644 (file)
@@ -47,10 +47,9 @@ public class DeleteActionIT {
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE, true);
 
-  private DbClient dbClient = db.getDbClient();
-  private DbSession dbSession = db.getSession();
-
-  private WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSession));
+  private final DbClient dbClient = db.getDbClient();
+  private final DbSession dbSession = db.getSession();
+  private final WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSession));
 
   @Test
   public void no_response() {
index 3a6a3971a7fdbe11ad41b48ec6e674c7357fa6d9..a19e9e74022b34a53ad67ba9f380245bb092880c 100644 (file)
@@ -54,9 +54,8 @@ public class SearchActionIT {
   @Rule
   public DbTester db = DbTester.create(System2.INSTANCE, true);
 
-  private DbClient dbClient = db.getDbClient();
-
-  private WsActionTester ws = new WsActionTester(new SearchAction(dbClient, userSession, TestComponentFinder.from(db)));
+  private final DbClient dbClient = db.getDbClient();
+  private final WsActionTester ws = new WsActionTester(new SearchAction(dbClient, userSession, TestComponentFinder.from(db)));
 
   @Test
   public void example() {
index 4025c51221a2f978bbb0bd58078689b7ef756d09..2f018c8d0c6f6717e6e4627e9cc5d0b93cd6e27d 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.server.qualitygate.ws;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbTester;
index bdcc1a4feda27be31f5685755808ea58d05679b1..0e6a06f7971812592cd649720292d9509aafa4a6 100644 (file)
@@ -982,7 +982,7 @@ public class SearchActionIT {
       .executeProtobuf(SearchResponse.class);
 
     assertThat(result.getRulesCount()).isEqualTo(3);
-    assertThat(result.getRulesList()).extracting("key", "status.name").containsExactlyInAnyOrder(
+    assertThat(result.getRulesList()).extracting(Rule::getKey, r -> r.getStatus().name()).containsExactlyInAnyOrder(
       tuple(rule1.getKey().toString(), rule1.getStatus().name()),
       tuple(rule2.getKey().toString(), rule2.getStatus().name()),
       tuple(rule3.getKey().toString(), rule3.getStatus().name()));
index db7e55a404fa62c334101baa89ec9b6a51a259e5..bf82e2923ff5b6d57113becb3f8ffaea021de61d 100644 (file)
@@ -51,7 +51,7 @@ public class ClearActionIT {
   @Rule
   public UserSessionRule userSession = UserSessionRule.standalone();
   @Rule
-  public DbTester dbTester = DbTester.create(System2.INSTANCE);
+  public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
 
   private final ScannerAnalysisCacheDao dao = new ScannerAnalysisCacheDao();
   private final ProjectDao projectDao = new ProjectDao(System2.INSTANCE, new NoOpAuditPersister());
index e3d81ce096794b697baffd81988d2009a2af26a4..9e9e122643e979585ec6ff167efc0672f6242a52 100644 (file)
@@ -8,7 +8,7 @@
       "longName": "null/NAME_file1",
       "q": "FIL",
       "project": "KEY_projectUuid",
-      "projectName": "LONG_NAME_projectUuid",
+      "projectName": "NAME_projectUuid",
       "measures": {}
     },
     "sources": [
index 0ac0a38381e29d93f97dadf0f05a53a47f918397..068ab3e99b7a7462762d178c43dd7b00116b38d8 100644 (file)
@@ -8,7 +8,7 @@
       "longName": "null/NAME_file2",
       "q": "FIL",
       "project": "KEY_projectUuid",
-      "projectName": "LONG_NAME_projectUuid",
+      "projectName": "NAME_projectUuid",
       "measures": {}
     },
     "sources": [
       "longName": "null/NAME_file1",
       "q": "FIL",
       "project": "KEY_projectUuid",
-      "projectName": "LONG_NAME_projectUuid",
+      "projectName": "NAME_projectUuid",
       "measures": {}
     },
     "sources": [
index 5bddeccff2969821ea7097a26ce9758d18bce9cd..965fe7b362b10003118e2ec59c7a216e03d3be7a 100644 (file)
@@ -8,7 +8,7 @@
       "longName": "null/NAME_file",
       "q": "FIL",
       "project": "KEY_projectUuid",
-      "projectName": "LONG_NAME_projectUuid"
+      "projectName": "NAME_projectUuid"
     },
     "sources": [
       {
         "utCoveredConditions": 9,
         "coveredConditions": 9,
         "duplicated": true,
-        "isNew": true,
+        "isNew": true
       },
       {
         "line": 8,
index ca60c2a7d71a2e54101da43c1064a0df8a0690d5..df819ddc9bc4c501eb9a94116bd38af80f1928a5 100644 (file)
@@ -8,7 +8,7 @@
       "longName": "null/NAME_file",
       "q": "FIL",
       "project": "KEY_projectUuid",
-      "projectName": "LONG_NAME_projectUuid",
+      "projectName": "NAME_projectUuid",
       "measures": {
         "lines": "200.0",
         "coverage": "95.4",
index 8cc84c4468f0802120f30e6aefc4e26874046817..fdd54e406e8b139f785071a24a4497ac8b6fb047 100644 (file)
@@ -58,7 +58,7 @@ public class ComponentService {
   public void updateKey(DbSession dbSession, ProjectDto project, String newKey) {
     userSession.checkEntityPermission(UserRole.ADMIN, project);
     checkProjectKey(newKey);
-    dbClient.componentKeyUpdaterDao().updateKey(dbSession, project.getUuid(), newKey);
+    dbClient.componentKeyUpdaterDao().updateKey(dbSession, project.getUuid(), project.getKey(), newKey);
     projectIndexers.commitAndIndexProjects(dbSession, singletonList(project), ProjectIndexer.Cause.PROJECT_KEY_UPDATE);
     Project newProject = new Project(project.getUuid(), newKey, project.getName(), project.getDescription(), project.getTags());
     projectLifeCycleListeners.onProjectsRekeyed(singleton(new RekeyedProject(newProject, project.getKey())));
index b183208c47a335d09c04e64b16266ff981c836ac..fe74b6911824dee9c1759b000e9b95afade16451 100644 (file)
@@ -28,6 +28,7 @@ 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.entity.EntityDto;
 import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.user.UserSession;
 
@@ -41,7 +42,6 @@ public class AppAction implements ComponentsWsAction {
   static final String PARAM_COMPONENT = "component";
 
   private final DbClient dbClient;
-
   private final UserSession userSession;
   private final ComponentFinder componentFinder;
   private final ComponentViewerJsonWriter componentViewerJsonWriter;
@@ -90,7 +90,10 @@ public class AppAction implements ComponentsWsAction {
     try (DbSession session = dbClient.openSession(false)) {
       ComponentDto component = loadComponent(session, request);
       userSession.checkComponentPermission(UserRole.USER, component);
-      writeJsonResponse(response, session, component, request);
+
+      EntityDto entity = dbClient.entityDao().selectByComponentUuid(session, component.uuid())
+        .orElseThrow(() -> new IllegalStateException("Couldn't find entity for component " + component.uuid()));
+      writeJsonResponse(response, session, entity, component, request);
     }
   }
 
@@ -101,10 +104,10 @@ public class AppAction implements ComponentsWsAction {
     return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
   }
 
-  private void writeJsonResponse(Response response, DbSession session, ComponentDto component, Request request) {
+  private void writeJsonResponse(Response response, DbSession session, EntityDto entity, ComponentDto component, Request request) {
     try (JsonWriter json = response.newJsonWriter()) {
       json.beginObject();
-      componentViewerJsonWriter.writeComponent(json, component, userSession, session, request.param(PARAM_BRANCH),
+      componentViewerJsonWriter.writeComponent(json, entity, component, userSession, session, request.param(PARAM_BRANCH),
         request.param(PARAM_PULL_REQUEST));
       appendPermissions(json, userSession);
       componentViewerJsonWriter.writeMeasures(json, component, session);
index 05d8af6c3dd903f9f2679174bb28308b372c96bd..8afae70dd1e298d79d3afa9c026eb396f7e9e016 100644 (file)
@@ -31,6 +31,7 @@ import org.sonar.api.utils.text.JsonWriter;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.entity.EntityDto;
 import org.sonar.db.measure.LiveMeasureDto;
 import org.sonar.db.metric.MetricDto;
 import org.sonar.db.property.PropertyDto;
@@ -62,7 +63,7 @@ public class ComponentViewerJsonWriter {
     this.dbClient = dbClient;
   }
 
-  public void writeComponentWithoutFav(JsonWriter json, ComponentDto component, DbSession session, @Nullable String branch, @Nullable String pullRequest) {
+  public void writeComponentWithoutFav(JsonWriter json, EntityDto entity, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
     json.prop("key", component.getKey());
     json.prop("uuid", component.uuid());
     json.prop("path", component.path());
@@ -70,10 +71,8 @@ public class ComponentViewerJsonWriter {
     json.prop("longName", component.longName());
     json.prop("q", component.qualifier());
 
-    ComponentDto project = dbClient.componentDao().selectOrFailByUuid(session, component.branchUuid());
-
-    json.prop("project", project.getKey());
-    json.prop("projectName", project.longName());
+    json.prop("project", entity.getKey());
+    json.prop("projectName", entity.getName());
     if (branch != null) {
       json.prop("branch", branch);
     }
@@ -82,15 +81,15 @@ public class ComponentViewerJsonWriter {
     }
   }
 
-  public void writeComponent(JsonWriter json, ComponentDto component, UserSession userSession, DbSession session, @Nullable String branch,
+  public void writeComponent(JsonWriter json, EntityDto entity, ComponentDto component, UserSession userSession, DbSession session, @Nullable String branch,
     @Nullable String pullRequest) {
-    writeComponentWithoutFav(json, component, session, branch, pullRequest);
+    writeComponentWithoutFav(json, entity, component, branch, pullRequest);
 
     List<PropertyDto> propertyDtos = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
-      .setKey("favourite")
-      .setEntityUuid(component.uuid())
-      .setUserUuid(userSession.getUuid())
-      .build(),
+        .setKey("favourite")
+        .setEntityUuid(entity.getUuid())
+        .setUserUuid(userSession.getUuid())
+        .build(),
       session);
     boolean isFavourite = propertyDtos.size() == 1;
     json.prop("fav", isFavourite);
index 4da51c59666cda2d97cebff53abcd20cab4ee5d4..be7713895db84dea51c781c6e605a87f63d082d3 100644 (file)
@@ -24,6 +24,7 @@ import com.google.common.collect.Ordering;
 import com.google.common.collect.Sets;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -50,7 +51,7 @@ import org.sonar.core.platform.PlatformEditionProvider;
 import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
-import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.SnapshotDto;
 import org.sonar.db.project.ProjectDto;
 import org.sonar.db.property.PropertyDto;
@@ -73,6 +74,7 @@ import org.sonarqube.ws.Components.SearchProjectsWsResponse;
 import static com.google.common.base.MoreObjects.firstNonNull;
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.collect.Sets.newHashSet;
+import static java.util.Collections.emptyList;
 import static java.util.Collections.emptyMap;
 import static java.util.Objects.requireNonNull;
 import static java.util.Optional.ofNullable;
@@ -112,10 +114,8 @@ public class SearchProjectsAction implements ComponentsWsAction {
   private final PlatformEditionProvider editionProvider;
   private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
 
-  public SearchProjectsAction(DbClient dbClient, ProjectMeasuresIndex index, UserSession userSession,
-    ProjectsInWarning projectsInWarning,
-    PlatformEditionProvider editionProvider,
-    IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) {
+  public SearchProjectsAction(DbClient dbClient, ProjectMeasuresIndex index, UserSession userSession, ProjectsInWarning projectsInWarning,
+    PlatformEditionProvider editionProvider, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) {
     this.dbClient = dbClient;
     this.index = index;
     this.userSession = userSession;
@@ -249,9 +249,17 @@ public class SearchProjectsAction implements ComponentsWsAction {
     List<String> projectUuids = esResults.getUuids();
     Ordering<ProjectDto> ordering = Ordering.explicit(projectUuids).onResultOf(ProjectDto::getUuid);
     List<ProjectDto> projects = ordering.immutableSortedCopy(dbClient.projectDao().selectByUuids(dbSession, new HashSet<>(projectUuids)));
-    Map<String, SnapshotDto> analysisByProjectUuid = getSnapshots(dbSession, request, projectUuids);
-
-    Map<String, Long> applicationsLeakPeriod = getApplicationsLeakPeriod(dbSession, request, qualifiersBasedOnEdition, projectUuids);
+    Map<String, BranchDto> mainBranchByUuid = dbClient.branchDao().selectMainBranchesByProjectUuids(dbSession, projectUuids)
+      .stream()
+      .collect(Collectors.toMap(BranchDto::getUuid, b -> b));
+
+    List<SnapshotDto> snapshots = getSnapshots(dbSession, request, mainBranchByUuid.keySet());
+    Map<String, SnapshotDto> analysisByProjectUuid = snapshots.stream()
+      .collect(Collectors.toMap(s -> mainBranchByUuid.get(s.getComponentUuid()).getProjectUuid(), s -> s));
+    Map<String, Long> applicationsBranchLeakPeriod = getApplicationsLeakPeriod(dbSession, request, qualifiersBasedOnEdition, mainBranchByUuid.keySet());
+    Map<String, Long> applicationsLeakPeriod = applicationsBranchLeakPeriod.entrySet()
+      .stream()
+      .collect(Collectors.toMap(e -> mainBranchByUuid.get(e.getKey()).getProjectUuid(), Entry::getValue));
 
     List<String> projectsInsync = getProjectUuidsWithBranchesNeedIssueSync(dbSession, Sets.newHashSet(projectUuids));
 
@@ -315,30 +323,26 @@ public class SearchProjectsAction implements ComponentsWsAction {
         .build(),
       dbSession);
 
-    List<String> favoriteDbUuids = props.stream()
+    Set<String> favoriteDbUuids = props.stream()
       .map(PropertyDto::getEntityUuid)
       .filter(Objects::nonNull)
-      .collect(MoreCollectors.toList(props.size()));
+      .collect(MoreCollectors.toSet(props.size()));
 
-    return dbClient.componentDao().selectByUuids(dbSession, favoriteDbUuids).stream()
-      .filter(ComponentDto::isEnabled)
-      .filter(f -> f.qualifier().equals(Qualifiers.PROJECT) || f.qualifier().equals(Qualifiers.APP))
-      .map(ComponentDto::uuid)
+    return dbClient.projectDao().selectByUuids(dbSession, favoriteDbUuids).stream()
+      .map(ProjectDto::getUuid)
       .collect(MoreCollectors.toSet());
   }
 
-  private Map<String, SnapshotDto> getSnapshots(DbSession dbSession, SearchProjectsRequest request, List<String> projectUuids) {
+  private List<SnapshotDto> getSnapshots(DbSession dbSession, SearchProjectsRequest request, Collection<String> mainBranchUuids) {
     if (request.getAdditionalFields().contains(ANALYSIS_DATE) || request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) {
-      return dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, projectUuids)
-        .stream()
-        .collect(MoreCollectors.uniqueIndex(SnapshotDto::getComponentUuid));
+      return dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, mainBranchUuids);
     }
-    return emptyMap();
+    return emptyList();
   }
 
-  private Map<String, Long> getApplicationsLeakPeriod(DbSession dbSession, SearchProjectsRequest request, Set<String> qualifiers, List<String> projectUuids) {
+  private Map<String, Long> getApplicationsLeakPeriod(DbSession dbSession, SearchProjectsRequest request, Set<String> qualifiers, Collection<String> mainBranchUuids) {
     if (qualifiers.contains(Qualifiers.APP) && request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) {
-      return dbClient.liveMeasureDao().selectByComponentUuidsAndMetricKeys(dbSession, projectUuids, Collections.singleton(METRIC_LEAK_PROJECTS_KEY))
+      return dbClient.liveMeasureDao().selectByComponentUuidsAndMetricKeys(dbSession, mainBranchUuids, Collections.singleton(METRIC_LEAK_PROJECTS_KEY))
         .stream()
         .filter(lm -> !Objects.isNull(lm.getDataAsString()))
         .map(lm -> Maps.immutableEntry(lm.getComponentUuid(), ApplicationLeakProjects.parse(lm.getDataAsString()).getOldestLeak()))
index b0035bb3013e2bca0dca082b70951636c7a6d9e2..f1b2b4957a3e4beb480d503d7dee5768dc457c8a 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.server.hotspot.ws;
 import javax.annotation.Nullable;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonarqube.ws.Hotspots;
 
 import static java.util.Optional.ofNullable;
@@ -32,6 +33,18 @@ public class HotspotWsResponseFormatter {
     // nothing to do here
   }
 
+  Hotspots.Component formatProject(Hotspots.Component.Builder builder, ProjectDto project, @Nullable String branch, @Nullable String pullRequest) {
+    builder
+      .clear()
+      .setKey(project.getKey())
+      .setQualifier(project.getQualifier())
+      .setName(project.getName())
+      .setLongName(project.getName());
+    ofNullable(branch).ifPresent(builder::setBranch);
+    ofNullable(pullRequest).ifPresent(builder::setPullRequest);
+    return builder.build();
+  }
+
   Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
     builder
       .clear()
index dfc7c1ce6b9c3f487f270bc5063f6c51b5697ba5..27f597c1898c892ed0d25011923e757efa8a363b 100644 (file)
@@ -31,6 +31,8 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueDto;
 import org.sonar.db.project.ProjectDto;
+import org.sonar.server.component.ComponentFinder;
+import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.user.UserSession;
 
@@ -53,7 +55,7 @@ public class HotspotWsSupport {
     return userSession.checkLoggedIn().getUuid();
   }
 
-  BranchDto loadAndCheckBranch(DbSession dbSession, String hotspotKey) {
+  ProjectAndBranch loadAndCheckBranch(DbSession dbSession, String hotspotKey) {
     IssueDto hotspot = loadHotspot(dbSession, hotspotKey);
     return loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
   }
@@ -65,7 +67,7 @@ public class HotspotWsSupport {
       .orElseThrow(() -> new NotFoundException(format("Hotspot '%s' does not exist", hotspotKey)));
   }
 
-  BranchDto loadAndCheckBranch(DbSession dbSession, IssueDto hotspot, String userRole) {
+  ProjectAndBranch loadAndCheckBranch(DbSession dbSession, IssueDto hotspot, String userRole) {
     String branchUuid = hotspot.getProjectUuid();
     checkArgument(branchUuid != null, "Hotspot '%s' has no branch", hotspot.getKee());
 
@@ -75,11 +77,11 @@ public class HotspotWsSupport {
       .orElseThrow(() -> new NotFoundException(format("Project with uuid '%s' does not exist", branch.getProjectUuid())));
 
     userSession.checkEntityPermission(userRole, project);
-    return branch;
+    return new ProjectAndBranch(project, branch);
   }
 
-  boolean canChangeStatus(ComponentDto project) {
-    return userSession.hasComponentPermission(UserRole.SECURITYHOTSPOT_ADMIN, project);
+  boolean canChangeStatus(ProjectDto project) {
+    return userSession.hasEntityPermission(UserRole.SECURITYHOTSPOT_ADMIN, project);
   }
 
   IssueChangeContext newIssueChangeContextWithoutMeasureRefresh() {
index 62d33df164b398430a0c934223182d1fb8c70b99..d60e1e294a69f344496670509fe48d268a7530ab 100644 (file)
@@ -377,16 +377,17 @@ public class SearchAction implements HotspotsWsAction {
 
     if (projectOrAppAndBranch != null) {
       ProjectDto projectOrApp = projectOrAppAndBranch.getProject();
+      BranchDto projectOrAppBranch = projectOrAppAndBranch.getBranch();
 
       if (Qualifiers.APP.equals(projectOrApp.getQualifier())) {
-        builder.viewUuids(singletonList(projectOrApp.getUuid()));
+        builder.viewUuids(singletonList(projectOrAppBranch.getUuid()));
         if (wsRequest.isInNewCodePeriod() && wsRequest.getPullRequest().isEmpty()) {
-          addInNewCodePeriodFilterByProjects(builder, dbSession, projectOrAppAndBranch.getBranch());
+          addInNewCodePeriodFilterByProjects(builder, dbSession, projectOrAppBranch);
         }
       } else {
         builder.projectUuids(singletonList(projectOrApp.getUuid()));
         if (wsRequest.isInNewCodePeriod() && wsRequest.getPullRequest().isEmpty()) {
-          addInNewCodePeriodFilter(dbSession, projectOrApp, builder);
+          addInNewCodePeriodFilter(dbSession, projectOrAppBranch, builder);
         }
       }
 
@@ -465,8 +466,8 @@ public class SearchAction implements HotspotsWsAction {
     }
   }
 
-  private void addInNewCodePeriodFilter(DbSession dbSession, @NotNull ProjectDto project, IssueQuery.Builder builder) {
-    Optional<SnapshotDto> snapshot = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, project.getUuid());
+  private void addInNewCodePeriodFilter(DbSession dbSession, @NotNull BranchDto projectBranch, IssueQuery.Builder builder) {
+    Optional<SnapshotDto> snapshot = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, projectBranch.getUuid());
 
     boolean isLastAnalysisUsingReferenceBranch = snapshot.map(SnapshotDto::getPeriodMode)
       .orElse("").equals(REFERENCE_BRANCH.name());
index 5af876ed042ba2fd0d6e8595d654cfba99eff474..be101f7c095336f08a45038a022475a11d8cb11f 100644 (file)
@@ -42,6 +42,7 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.protobuf.DbIssues.Locations;
 import org.sonar.db.rule.RuleDescriptionSectionContextDto;
@@ -49,6 +50,7 @@ import org.sonar.db.rule.RuleDescriptionSectionDto;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
 import org.sonar.markdown.Markdown;
+import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.issue.IssueChangeWSSupport;
 import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext;
@@ -177,9 +179,9 @@ public class ShowAction implements HotspotsWsAction {
 
   private void formatComponents(Components components, ShowWsResponse.Builder responseBuilder) {
     responseBuilder
-      .setProject(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getBranchComponent(), components.getBranch(), components.getPullRequest()))
+      .setProject(responseFormatter.formatProject(Hotspots.Component.newBuilder(), components.getProjectDto(), components.getBranch(), components.getPullRequest()))
       .setComponent(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getComponent(), components.getBranch(), components.getPullRequest()));
-    responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getBranchComponent()));
+    responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProjectDto()));
   }
 
   private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDto ruleDto) {
@@ -266,9 +268,8 @@ public class ShowAction implements HotspotsWsAction {
       .filter(Optional::isPresent)
       .map(Optional::get)
       .collect(toSet());
-    Set<ComponentDto> preloadedComponents = ImmutableSet.of(components.branchComponent, components.component);
     FormattingContext formattingContext = issueChangeSupport
-      .newFormattingContext(dbSession, singleton(hotspot), Load.ALL, preloadedUsers, preloadedComponents);
+      .newFormattingContext(dbSession, singleton(hotspot), Load.ALL, preloadedUsers, Set.of(components.component));
 
     issueChangeSupport.formatChangelog(hotspot, formattingContext)
       .forEach(responseBuilder::addChangelog);
@@ -300,24 +301,23 @@ public class ShowAction implements HotspotsWsAction {
     String componentUuid = hotspot.getComponentUuid();
     checkArgument(componentUuid != null, "Hotspot '%s' has no component", hotspot.getKee());
 
-    BranchDto branch = hotspotWsSupport.loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
+    ProjectAndBranch projectAndBranch = hotspotWsSupport.loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
+    BranchDto branch = projectAndBranch.getBranch();
     ComponentDto component = dbClient.componentDao().selectByUuid(dbSession, componentUuid)
         .orElseThrow(() -> new NotFoundException(format("Component with uuid '%s' does not exist", componentUuid)));
     boolean hotspotOnBranch = Objects.equals(branch.getUuid(), componentUuid);
-    ComponentDto branchComponent = hotspotOnBranch ? component : dbClient.componentDao().selectByUuid(dbSession, branch.getUuid())
-      .orElseThrow(() -> new NotFoundException(format("Component with uuid '%s' does not exist", componentUuid)));
 
-    return new Components(branchComponent, component, branch);
+    return new Components(projectAndBranch.getProject(), component, branch);
   }
 
   private static final class Components {
-    private final ComponentDto branchComponent;
+    private final ProjectDto project;
     private final ComponentDto component;
     private final String branch;
     private final String pullRequest;
 
-    private Components(ComponentDto branchComponent, ComponentDto component, BranchDto branch) {
-      this.branchComponent = branchComponent;
+    private Components(ProjectDto projectDto, ComponentDto component, BranchDto branch) {
+      this.project = projectDto;
       this.component = component;
       if (branch.isMain()) {
         this.branch = null;
@@ -331,6 +331,10 @@ public class ShowAction implements HotspotsWsAction {
       }
     }
 
+    public ProjectDto getProjectDto() {
+      return project;
+    }
+
     @CheckForNull
     public String getBranch() {
       return branch;
@@ -341,10 +345,6 @@ public class ShowAction implements HotspotsWsAction {
       return pullRequest;
     }
 
-    public ComponentDto getBranchComponent() {
-      return branchComponent;
-    }
-
     public ComponentDto getComponent() {
       return component;
     }
index e99e929498da6390ca1642592d1b6f8f726040b0..f3e12e9e0b12000dc7d553246f9ed81805258896 100644 (file)
@@ -36,7 +36,6 @@ import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.BranchDto;
 import org.sonar.db.entity.EntityDto;
-import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.exceptions.NotFoundException;
 import org.sonar.server.issue.index.IssueIndex;
 import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
@@ -44,7 +43,6 @@ import org.sonar.server.issue.index.IssueQuery;
 import org.sonar.server.user.UserSession;
 import org.sonarqube.ws.Issues.AuthorsResponse;
 
-import static com.google.common.base.Preconditions.checkArgument;
 import static java.util.Optional.ofNullable;
 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
@@ -60,15 +58,12 @@ public class AuthorsAction implements IssuesWsAction {
   private final DbClient dbClient;
   private final IssueIndex issueIndex;
   private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
-  private final ComponentFinder componentFinder;
 
-  public AuthorsAction(UserSession userSession, DbClient dbClient, IssueIndex issueIndex,
-    IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, ComponentFinder componentFinder) {
+  public AuthorsAction(UserSession userSession, DbClient dbClient, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) {
     this.userSession = userSession;
     this.dbClient = dbClient;
     this.issueIndex = issueIndex;
     this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
-    this.componentFinder = componentFinder;
   }
 
   @Override
@@ -76,8 +71,8 @@ public class AuthorsAction implements IssuesWsAction {
     NewAction action = controller.createAction("authors")
       .setSince("5.1")
       .setDescription("Search SCM accounts which match a given query.<br/>" +
-                      "Requires authentication."
-                      + "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
+        "Requires authentication."
+        + "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
       .setResponseExample(Resources.getResource(this.getClass(), "authors-example.json"))
       .setChangelog(new Change("7.4", "The maximum size of 'ps' is set to 100"))
       .setHandler(this);
@@ -99,7 +94,7 @@ public class AuthorsAction implements IssuesWsAction {
       checkIfComponentNeedIssueSync(dbSession, request.param(PARAM_PROJECT));
 
       Optional<EntityDto> entity = getEntity(dbSession, request.param(PARAM_PROJECT));
-      List<String> authors = getAuthors(entity.orElse(null), request, dbSession);
+      List<String> authors = getAuthors(dbSession, entity.orElse(null), request);
       AuthorsResponse wsResponse = AuthorsResponse.newBuilder().addAllAuthors(authors).build();
       writeProtobuf(wsResponse, request, response);
     }
@@ -117,28 +112,23 @@ public class AuthorsAction implements IssuesWsAction {
     if (projectKey == null) {
       return Optional.empty();
     }
-    EntityDto entity = componentFinder.getEntityByKey(dbSession, projectKey);
-    return Optional.of(entity);
+    return Optional.of(dbClient.entityDao().selectByKey(dbSession, projectKey)
+      .filter(e -> !e.getQualifier().equals(Qualifiers.SUBVIEW))
+      .orElseThrow(() -> new NotFoundException("Entity not found: " + projectKey)));
   }
 
-  private List<String> getAuthors(@Nullable EntityDto entity, Request request, DbSession dbSession) {
+  private List<String> getAuthors(DbSession session, @Nullable EntityDto entity, Request request) {
     IssueQuery.Builder issueQueryBuilder = IssueQuery.builder();
-    ofNullable(entity).ifPresent(e -> {
-      switch (e.getQualifier()) {
-        case Qualifiers.PROJECT:
-          issueQueryBuilder.projectUuids(Set.of(e.getUuid()));
-          return;
-        case Qualifiers.VIEW:
-          issueQueryBuilder.viewUuids(Set.of(e.getUuid()));
-          return;
-        case Qualifiers.APP:
-          issueQueryBuilder.viewUuids(Set.of(e.getUuid()));
-          BranchDto branchDto = dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, entity.getUuid())
-            .orElseThrow(() -> new NotFoundException("Main branch of application %s not found".formatted(e.getUuid())));
-          issueQueryBuilder.branchUuid(branchDto.getUuid());
-          return;
-        default:
-          throw new IllegalArgumentException(String.format("Entity of type '%s' is not supported", e.getQualifier()));
+    ofNullable(entity).ifPresent(p -> {
+      switch (p.getQualifier()) {
+        case Qualifiers.PROJECT -> issueQueryBuilder.projectUuids(Set.of(p.getUuid()));
+        case Qualifiers.VIEW -> issueQueryBuilder.viewUuids(Set.of(p.getUuid()));
+        case Qualifiers.APP -> {
+          BranchDto appMainBranch = dbClient.branchDao().selectMainBranchByProjectUuid(session, entity.getUuid())
+            .orElseThrow(() -> new IllegalStateException("Couldn't find main branch for APP " + entity.getUuid()));
+          issueQueryBuilder.viewUuids(Set.of(appMainBranch.getUuid()));
+        }
+        default -> throw new IllegalArgumentException(String.format("Component of type '%s' is not supported", p.getQualifier()));
       }
     });
     return issueIndex.searchAuthors(
@@ -148,5 +138,4 @@ public class AuthorsAction implements IssuesWsAction {
       request.param(TEXT_QUERY),
       request.mandatoryParamAsInt(PAGE_SIZE));
   }
-
 }
index 2b57a4634414fbdb593453cba43624ab88c4d274..d00c4c1bec3a0b1b02ea4d880ff84e8ad3b2fa44 100644 (file)
@@ -245,7 +245,7 @@ public class BulkChangeAction implements IssuesWsAction {
 
   private static Predicate<DefaultIssue> bulkChange(IssueChangeContext issueChangeContext, BulkChangeData bulkChangeData, BulkChangeResult result) {
     return issue -> {
-      ActionContext actionContext = new ActionContext(issue, issueChangeContext, bulkChangeData.projectsByUuid.get(issue.projectUuid()));
+      ActionContext actionContext = new ActionContext(issue, issueChangeContext, bulkChangeData.branchComponentByUuid.get(issue.projectUuid()));
       bulkChangeData.getActionsWithoutComment().forEach(applyAction(actionContext, bulkChangeData, result));
       addCommentIfNeeded(actionContext, bulkChangeData);
       return result.success.contains(issue);
@@ -311,7 +311,7 @@ public class BulkChangeAction implements IssuesWsAction {
       return;
     }
 
-    issueChangeEventService.distributeIssueChangeEvent(issues, bulkChangeData.projectsByUuid, bulkChangeData.branchesByProjectUuid);
+    issueChangeEventService.distributeIssueChangeEvent(issues, bulkChangeData.branchComponentByUuid, bulkChangeData.branchesByProjectUuid);
   }
 
   @CheckForNull
@@ -322,7 +322,7 @@ public class BulkChangeAction implements IssuesWsAction {
     }
 
     RuleDto ruleDefinitionDto = bulkChangeData.rulesByKey.get(issue.ruleKey());
-    ComponentDto projectDto = bulkChangeData.projectsByUuid.get(issue.projectUuid());
+    ComponentDto projectDto = bulkChangeData.branchComponentByUuid.get(issue.projectUuid());
     if (ruleDefinitionDto == null || projectDto == null) {
       return null;
     }
@@ -369,7 +369,7 @@ public class BulkChangeAction implements IssuesWsAction {
     private final Map<String, Map<String, Object>> propertiesByActions;
     private final boolean sendNotification;
     private final Collection<DefaultIssue> issues;
-    private final Map<String, ComponentDto> projectsByUuid;
+    private final Map<String, ComponentDto> branchComponentByUuid;
     private final Map<String, BranchDto> branchesByProjectUuid;
     private final Map<String, ComponentDto> componentsByUuid;
     private final Map<RuleKey, RuleDto> rulesByKey;
@@ -386,9 +386,9 @@ public class BulkChangeAction implements IssuesWsAction {
         .filter(issueDto -> SECURITY_HOTSPOT.getDbConstant() != issueDto.getType())
         .toList();
 
-      List<ComponentDto> allProjects = getComponents(dbSession, allIssues.stream().map(IssueDto::getProjectUuid).collect(MoreCollectors.toSet()));
-      this.projectsByUuid = getAuthorizedProjects(allProjects).stream().collect(uniqueIndex(ComponentDto::uuid, identity()));
-      this.branchesByProjectUuid = dbClient.branchDao().selectByUuids(dbSession, projectsByUuid.keySet()).stream()
+      List<ComponentDto> allBranches = getComponents(dbSession, allIssues.stream().map(IssueDto::getProjectUuid).collect(MoreCollectors.toSet()));
+      this.branchComponentByUuid = getAuthorizedComponents(allBranches).stream().collect(uniqueIndex(ComponentDto::uuid, identity()));
+      this.branchesByProjectUuid = dbClient.branchDao().selectByUuids(dbSession, branchComponentByUuid.keySet()).stream()
         .collect(uniqueIndex(BranchDto::getUuid, identity()));
       this.issues = getAuthorizedIssues(allIssues);
       this.componentsByUuid = getComponents(dbSession,
@@ -408,14 +408,14 @@ public class BulkChangeAction implements IssuesWsAction {
       return dbClient.componentDao().selectByUuids(dbSession, componentUuids);
     }
 
-    private List<ComponentDto> getAuthorizedProjects(List<ComponentDto> projectDtos) {
+    private List<ComponentDto> getAuthorizedComponents(List<ComponentDto> projectDtos) {
       return userSession.keepAuthorizedComponents(UserRole.USER, projectDtos);
     }
 
     private List<DefaultIssue> getAuthorizedIssues(List<IssueDto> allIssues) {
-      Set<String> projectUuids = projectsByUuid.values().stream().map(ComponentDto::uuid).collect(MoreCollectors.toSet());
+      Set<String> branchUuids = branchComponentByUuid.values().stream().map(ComponentDto::uuid).collect(MoreCollectors.toSet());
       return allIssues.stream()
-        .filter(issue -> projectUuids.contains(issue.getProjectUuid()))
+        .filter(issue -> branchUuids.contains(issue.getProjectUuid()))
         .map(IssueDto::toDefaultIssue)
         .collect(MoreCollectors.toList());
     }
index 680f3912abf4bc02b00e2c6f96aae3f564501bb4..7ea25853c26fc910018a613f467ad271d4b71dac 100644 (file)
@@ -77,13 +77,13 @@ public class IssueUpdater {
 
   public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue, IssueChangeContext context, BranchDto branch) {
     Optional<RuleDto> rule = getRuleByKey(dbSession, issue.getRuleKey());
-    ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid());
+    ComponentDto branchComponent = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid());
     ComponentDto component = getComponent(dbSession, issue, issue.componentUuid());
-    IssueDto issueDto = doSaveIssue(dbSession, issue, context, rule.orElse(null), project, branch);
+    IssueDto issueDto = doSaveIssue(dbSession, issue, context, rule.orElse(null), branchComponent, branch);
 
     SearchResponseData result = new SearchResponseData(issueDto);
     rule.ifPresent(r -> result.addRules(singletonList(r)));
-    result.addComponents(singleton(project));
+    result.addComponents(singleton(branchComponent));
     result.addComponents(singleton(component));
 
     if (context.refreshMeasures()) {
index ea6a2d5791df0b2461cea707a444a04072b0b6d2..7f96af3ab02551cd5885a4b3bed6360fb071502b 100644 (file)
@@ -39,7 +39,7 @@ public class OperationResponseWriter {
 
   public void write(String issueKey, SearchResponseData preloadedResponseData, Request request, Response response) {
     SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(singletonList(issueKey));
-    SearchResponseData data = loader.load(preloadedResponseData, collector, ALL_ADDITIONAL_FIELDS,null);
+    SearchResponseData data = loader.load(preloadedResponseData, collector, ALL_ADDITIONAL_FIELDS, null);
 
     Issues.Operation responseBody = format.formatOperation(data);
 
index ed55f7438d32054c9946bd4767f3892f039836ed..f0763d11146e754fff2fc4f8bb05487df87b57cf 100644 (file)
@@ -450,7 +450,7 @@ public class SearchAction implements IssuesWsAction {
       completeFacets(facets, request, query);
       collectFacets(collector, facets);
     }
-    SearchResponseData preloadedData = new SearchResponseData(emptyList());
+    SearchResponseData preloadedData = new SearchResponseData();
     preloadedData.addRules(List.copyOf(query.rules()));
     SearchResponseData data = searchResponseLoader.load(preloadedData, collector, additionalFields, facets);
 
@@ -550,7 +550,7 @@ public class SearchAction implements IssuesWsAction {
       .setAssigned(request.paramAsBoolean(PARAM_ASSIGNED))
       .setAssigneesUuid(getLogins(dbSession, request.paramAsStrings(PARAM_ASSIGNEES)))
       .setAuthors(request.multiParam(PARAM_AUTHOR))
-      .setComponents(request.paramAsStrings(PARAM_COMPONENT_KEYS))
+      .setComponentKeys(request.paramAsStrings(PARAM_COMPONENT_KEYS))
       .setCreatedAfter(request.param(PARAM_CREATED_AFTER))
       .setCreatedAt(request.param(PARAM_CREATED_AT))
       .setCreatedBefore(request.param(PARAM_CREATED_BEFORE))
@@ -567,7 +567,7 @@ public class SearchAction implements IssuesWsAction {
       .setPullRequest(request.param(PARAM_PULL_REQUEST))
       .setPage(request.mandatoryParamAsInt(Param.PAGE))
       .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
-      .setProjects(request.paramAsStrings(PARAM_PROJECTS))
+      .setProjectKeys(request.paramAsStrings(PARAM_PROJECTS))
       .setResolutions(request.paramAsStrings(PARAM_RESOLUTIONS))
       .setResolved(request.paramAsBoolean(PARAM_RESOLVED))
       .setRules(request.paramAsStrings(PARAM_RULES))
@@ -590,7 +590,7 @@ public class SearchAction implements IssuesWsAction {
   }
 
   private void checkIfNeedIssueSync(DbSession dbSession, SearchRequest searchRequest) {
-    List<String> components = searchRequest.getComponents();
+    List<String> components = searchRequest.getComponentKeys();
     if (components != null && !components.isEmpty()) {
       issueIndexSyncProgressChecker.checkIfAnyComponentsNeedIssueSync(dbSession, components);
     } else {
index 1a470b8684160034a03d98b44af86491db862810..71d277aaf96c758e9b2da99b0b5bd2a734947a14 100644 (file)
@@ -34,6 +34,7 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueChangeDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.issue.workflow.Transition;
@@ -55,6 +56,11 @@ public class SearchResponseData {
   private final ListMultimap<String, Transition> transitionsByIssueKey = ArrayListMultimap.create();
   private final Set<String> updatableComments = new HashSet<>();
   private final Map<String, BranchDto> branchesByUuid = new HashMap<>();
+  private final Map<String, ProjectDto> projectsByUuid = new HashMap<>();
+
+  public SearchResponseData() {
+    this.issues = List.of();
+  }
 
   public SearchResponseData(IssueDto issue) {
     checkNotNull(issue);
@@ -151,6 +157,16 @@ public class SearchResponseData {
     return branchesByUuid.get(branchUuid);
   }
 
+  public void addProjects(List<ProjectDto> projectDtos) {
+    for (ProjectDto projectDto : projectDtos) {
+      projectsByUuid.put(projectDto.getUuid(), projectDto);
+    }
+  }
+
+  public ProjectDto getProject(String projectUuid) {
+    return projectsByUuid.get(projectUuid);
+  }
+
   void addActions(String issueKey, Iterable<String> actions) {
     actionsByIssueKey.putAll(issueKey, actions);
   }
index 75233dde0b289b46d0c4c30aeca3523a1de64804..8038a25ff580cb3c278fd70c882104995fb707d2 100644 (file)
@@ -40,6 +40,7 @@ import org.sonar.db.component.BranchType;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueChangeDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
@@ -164,9 +165,9 @@ public class SearchResponseFormat {
     ComponentDto component = data.getComponentByUuid(dto.getComponentUuid());
     issueBuilder.setComponent(component.getKey());
     setBranchOrPr(component, issueBuilder, data);
-    ComponentDto project = data.getComponentByUuid(dto.getProjectUuid());
-    if (project != null) {
-      issueBuilder.setProject(project.getKey());
+    ComponentDto branch = data.getComponentByUuid(dto.getProjectUuid());
+    if (branch != null) {
+      issueBuilder.setProject(branch.getKey());
     }
     issueBuilder.setRule(dto.getRuleKey().toString());
     if (dto.isExternal()) {
@@ -456,10 +457,10 @@ public class SearchResponseFormat {
     Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
     wsFacet.setProperty(FACET_PROJECTS);
     facet.forEach((uuid, count) -> {
-      ComponentDto component = datas.getComponentByUuid(uuid);
-      requireNonNull(component, format("Component has not been found for uuid '%s'", uuid));
+      ProjectDto project = datas.getProject(uuid);
+      requireNonNull(project, format("Project has not been found for uuid '%s'", uuid));
       wsFacet.addValuesBuilder()
-        .setVal(component.getKey())
+        .setVal(project.getKey())
         .setCount(count)
         .build();
     });
index a059721046c6b5f8a74ae8a8af413820b2881e64..243cc1a9e1cbe7c3b2ccf1966358ca4adb8aeebd 100644 (file)
@@ -41,6 +41,7 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.issue.IssueChangeDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbIssues;
 import org.sonar.db.rule.RuleDto;
 import org.sonar.db.user.UserDto;
@@ -101,6 +102,7 @@ public class SearchResponseLoader {
       loadComponents(preloadedResponseData, collector, dbSession, result);
       // for all loaded components in result we "join" branches to know to which branch components belong
       loadBranches(dbSession, result);
+      loadProjects(collector, dbSession, result);
 
       loadActionsAndTransitions(result, fields);
       completeTotalEffortFromFacet(facets, result);
@@ -148,10 +150,15 @@ public class SearchResponseLoader {
       result.addComponents(dbClient.componentDao().selectByUuids(dbSession, componentUuidsToLoad));
     }
 
-    // always load components and projects, because some issue fields still relate to component ids/keys.
+    // always load components and branches, because some issue fields still relate to component ids/keys.
     // They should be dropped but are kept for backward-compatibility (see SearchResponseFormat)
     result.addComponents(dbClient.componentDao().selectSubProjectsByComponentUuids(dbSession, collector.getComponentUuids()));
-    loadProjects(collector, dbSession, result);
+    loadBranchComponents(collector, dbSession, result);
+  }
+
+  private void loadProjects(Collector collector, DbSession dbSession, SearchResponseData result) {
+    List<ProjectDto> projects = dbClient.projectDao().selectByUuids(dbSession, collector.getProjectUuids());
+    result.addProjects(projects);
   }
 
   private void loadBranches(DbSession dbSession, SearchResponseData result) {
@@ -162,16 +169,16 @@ public class SearchResponseLoader {
     result.addBranches(branchDtos);
   }
 
-  private void loadProjects(Collector collector, DbSession dbSession, SearchResponseData result) {
+  private void loadBranchComponents(Collector collector, DbSession dbSession, SearchResponseData result) {
     Collection<ComponentDto> loadedComponents = result.getComponents();
     for (ComponentDto component : loadedComponents) {
-      collector.addProjectUuid(component.branchUuid());
+      collector.addBranchUuid(component.branchUuid());
     }
-    Set<String> loadedProjectUuids = loadedComponents.stream().filter(cpt -> cpt.uuid().equals(cpt.branchUuid())).map(ComponentDto::uuid).collect(MoreCollectors.toSet());
-    Set<String> projectUuidsToLoad = copyOf(difference(collector.getProjectUuids(), loadedProjectUuids));
-    if (!projectUuidsToLoad.isEmpty()) {
-      List<ComponentDto> projects = dbClient.componentDao().selectByUuids(dbSession, collector.getProjectUuids());
-      result.addComponents(projects);
+    Set<String> loadedBranchUuids = loadedComponents.stream().filter(cpt -> cpt.uuid().equals(cpt.branchUuid())).map(ComponentDto::uuid).collect(MoreCollectors.toSet());
+    Set<String> branchUuidsToLoad = copyOf(difference(collector.getBranchUuids(), loadedBranchUuids));
+    if (!branchUuidsToLoad.isEmpty()) {
+      List<ComponentDto> branchComponents = dbClient.componentDao().selectByUuids(dbSession, collector.getBranchUuids());
+      result.addComponents(branchComponents);
     }
   }
 
@@ -224,8 +231,8 @@ public class SearchResponseLoader {
       for (IssueDto issueDto : result.getIssues()) {
         // so that IssueDto can be used.
         if (fields.contains(ACTIONS)) {
-          ComponentDto project = componentsByProjectUuid.get(issueDto.getProjectUuid());
-          result.addActions(issueDto.getKey(), listAvailableActions(issueDto, project));
+          ComponentDto branch = componentsByProjectUuid.get(issueDto.getProjectUuid());
+          result.addActions(issueDto.getKey(), listAvailableActions(issueDto, branch));
         }
         if (fields.contains(TRANSITIONS) && !issueDto.isExternal()) {
           // TODO workflow and action engines must not depend on org.sonar.api.issue.Issue but on a generic interface
@@ -236,7 +243,7 @@ public class SearchResponseLoader {
     }
   }
 
-  private Set<String> listAvailableActions(IssueDto issue, ComponentDto project) {
+  private Set<String> listAvailableActions(IssueDto issue, ComponentDto branch) {
     Set<String> availableActions = newHashSet();
     String login = userSession.getLogin();
     if (login == null) {
@@ -249,7 +256,7 @@ public class SearchResponseLoader {
       return availableActions;
     }
     availableActions.add(ASSIGN_KEY);
-    if (ruleType != RuleType.SECURITY_HOTSPOT && userSession.hasComponentPermission(ISSUE_ADMIN, project)) {
+    if (ruleType != RuleType.SECURITY_HOTSPOT && userSession.hasComponentPermission(ISSUE_ADMIN, branch)) {
       availableActions.add(SET_TYPE_KEY);
       availableActions.add(SET_SEVERITY_KEY);
     }
@@ -270,6 +277,7 @@ public class SearchResponseLoader {
    */
   public static class Collector {
     private final Set<String> componentUuids = new HashSet<>();
+    private final Set<String> branchUuids = new HashSet<>();
     private final Set<String> projectUuids = new HashSet<>();
     private final List<String> issueKeys;
     private final Set<String> ruleUuids = new HashSet<>();
@@ -282,7 +290,7 @@ public class SearchResponseLoader {
     void collect(List<IssueDto> issues) {
       for (IssueDto issue : issues) {
         componentUuids.add(issue.getComponentUuid());
-        projectUuids.add(issue.getProjectUuid());
+        branchUuids.add(issue.getProjectUuid());
         Optional.ofNullable(issue.getRuleUuid()).ifPresent(ruleUuids::add);
         String issueAssigneeUuid = issue.getAssigneeUuid();
         if (issueAssigneeUuid != null) {
@@ -305,16 +313,16 @@ public class SearchResponseLoader {
       }
     }
 
-    void addProjectUuid(String uuid) {
-      this.projectUuids.add(uuid);
-    }
-
     void addProjectUuids(@Nullable Collection<String> uuids) {
       if (uuids != null) {
         this.projectUuids.addAll(uuids);
       }
     }
 
+    void addBranchUuid(String uuid) {
+      this.branchUuids.add(uuid);
+    }
+
     void addRuleIds(@Nullable Collection<String> ruleUuids) {
       if (ruleUuids != null) {
         this.ruleUuids.addAll(ruleUuids);
@@ -327,6 +335,10 @@ public class SearchResponseLoader {
       }
     }
 
+    public Set<String> getProjectUuids() {
+      return projectUuids;
+    }
+
     public List<String> getIssueKeys() {
       return issueKeys;
     }
@@ -335,8 +347,8 @@ public class SearchResponseLoader {
       return componentUuids;
     }
 
-    public Set<String> getProjectUuids() {
-      return projectUuids;
+    public Set<String> getBranchUuids() {
+      return branchUuids;
     }
 
     public Set<String> getRuleUuids() {
index 8bebeae11276f4b2492f55036b548c0e05a4160c..6abb9a2b2f9b3516f4dd94a0d9f6f3e57daed3a3 100644 (file)
@@ -62,9 +62,7 @@ public class TagsAction implements IssuesWsAction {
   private final DbClient dbClient;
   private final ComponentFinder componentFinder;
 
-  public TagsAction(IssueIndex issueIndex,
-    IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, DbClient dbClient,
-    ComponentFinder componentFinder) {
+  public TagsAction(IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, DbClient dbClient, ComponentFinder componentFinder) {
     this.issueIndex = issueIndex;
     this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
     this.dbClient = dbClient;
@@ -108,8 +106,8 @@ public class TagsAction implements IssuesWsAction {
       boolean all = request.mandatoryParamAsBoolean(PARAM_ALL);
       checkIfAnyComponentsNeedIssueSync(dbSession, projectKey);
 
-      Optional<EntityDto> entity = getProject(dbSession, projectKey);
-      Optional<BranchDto> branch = entity.flatMap(p -> dbClient.branchDao().selectByBranchKey(dbSession, p.getUuid(), branchKey));
+      Optional<EntityDto> entity = getEntity(dbSession, projectKey);
+      Optional<BranchDto> branch = branchKey == null ? Optional.empty() : entity.flatMap(p -> dbClient.branchDao().selectByBranchKey(dbSession, p.getUuid(), branchKey));
       List<String> tags = searchTags(entity.orElse(null), branch.orElse(null), request, all, dbSession);
 
       Issues.TagsResponse.Builder tagsResponseBuilder = Issues.TagsResponse.newBuilder();
@@ -118,12 +116,12 @@ public class TagsAction implements IssuesWsAction {
     }
   }
 
-  private Optional<EntityDto> getProject(DbSession dbSession, @Nullable String entityKey) {
+  private Optional<EntityDto> getEntity(DbSession dbSession, @Nullable String entityKey) {
     if (entityKey == null) {
       return Optional.empty();
     }
-    EntityDto entity = componentFinder.getEntityByKey(dbSession, entityKey);
-    return Optional.of(entity);
+    return Optional.of(componentFinder.getEntityByKey(dbSession, entityKey))
+      .filter(e -> !e.getQualifier().equals(Qualifiers.SUBVIEW));
   }
 
   private void checkIfAnyComponentsNeedIssueSync(DbSession session, @Nullable String projectKey) {
index fe4ae28be2b09992d6a00edda9c639e8c223d327..b919b3ae41d49bbc278dfbba2fa8ba99910262bc 100644 (file)
@@ -159,7 +159,7 @@ public class SearchAction implements ProjectsWsAction {
       Paging paging = buildPaging(dbSession, request, query);
       List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, query, paging.offset(), paging.pageSize());
       Set<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(MoreCollectors.toHashSet(components.size()));
-      Map<String, Long> lastAnalysisDateByComponentUuid = dbClient.snapshotDao().selectLastAnalysisDateByProjects(dbSession, componentUuids).stream()
+      Map<String, Long> lastAnalysisDateByComponentUuid = dbClient.snapshotDao().selectLastAnalysisDateByProjectUuids(dbSession, componentUuids).stream()
         .collect(Collectors.toMap(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate));
       Map<String, SnapshotDto> snapshotsByComponentUuid = dbClient.snapshotDao()
         .selectLastAnalysesByRootComponentUuids(dbSession, componentUuids).stream()
index 16527e79eb94c57dab98f76261a4b151fa561af2..6d55828626b103ec06196a7518f02f9128f9a201 100644 (file)
@@ -38,6 +38,7 @@ import org.sonar.db.component.BranchDto;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.SnapshotDto;
 import org.sonar.db.issue.IssueDto;
+import org.sonar.db.project.ProjectDto;
 import org.sonar.db.protobuf.DbCommons;
 import org.sonar.db.protobuf.DbFileSources;
 import org.sonar.db.protobuf.DbIssues;
@@ -87,9 +88,10 @@ public class IssueSnippetsAction implements SourcesWsAction {
     try (DbSession dbSession = dbClient.openSession(false)) {
       IssueDto issueDto = dbClient.issueDao().selectByKey(dbSession, issueKey)
         .orElseThrow(() -> new NotFoundException(format("Issue with key '%s' does not exist", issueKey)));
-      ComponentDto project = dbClient.componentDao().selectByUuid(dbSession, issueDto.getProjectUuid())
+      ProjectDto projectDto = dbClient.projectDao().selectByBranchUuid(dbSession, issueDto.getProjectUuid())
         .orElseThrow(() -> new NotFoundException(format("Project with uuid '%s' does not exist", issueDto.getProjectUuid())));
-      userSession.checkComponentPermission(UserRole.CODEVIEWER, project);
+
+      userSession.checkEntityPermission(UserRole.CODEVIEWER, projectDto);
 
       DbIssues.Locations locations = issueDto.parseLocations();
       String componentUuid = issueDto.getComponentUuid();
@@ -115,7 +117,7 @@ public class IssueSnippetsAction implements SourcesWsAction {
           for (Map.Entry<String, TreeSet<Integer>> e : linesPerComponent.entrySet()) {
             ComponentDto componentDto = componentsByUuid.get(e.getKey());
             if (componentDto != null) {
-              writeSnippet(dbSession, jsonWriter, componentDto, e.getValue(), branches.get(componentDto.branchUuid()));
+              writeSnippet(dbSession, jsonWriter, projectDto, componentDto, e.getValue(), branches.get(componentDto.branchUuid()));
             }
           }
 
@@ -125,7 +127,7 @@ public class IssueSnippetsAction implements SourcesWsAction {
     }
   }
 
-  private void writeSnippet(DbSession dbSession, JsonWriter writer, ComponentDto fileDto, Set<Integer> lines, BranchDto branchDto) {
+  private void writeSnippet(DbSession dbSession, JsonWriter writer, ProjectDto projectDto, ComponentDto fileDto, Set<Integer> lines, BranchDto branchDto) {
     Optional<Iterable<DbFileSources.Line>> lineSourcesOpt = sourceService.getLines(dbSession, fileDto.uuid(), lines);
     if (lineSourcesOpt.isEmpty()) {
       return;
@@ -142,7 +144,7 @@ public class IssueSnippetsAction implements SourcesWsAction {
     writer.name("component").beginObject();
     String branch = branchDto.isMain() ? null : branchDto.getBranchKey();
     String pullRequest = branchDto.getPullRequestKey();
-    componentViewerJsonWriter.writeComponentWithoutFav(writer, fileDto, dbSession, branch, pullRequest);
+    componentViewerJsonWriter.writeComponentWithoutFav(writer, projectDto, fileDto, branch, pullRequest);
     componentViewerJsonWriter.writeMeasures(writer, fileDto, dbSession);
     writer.endObject();
     linesJsonWriter.writeSource(lineSources, writer, periodDateSupplier);
index d6687e73f6b513684a946a8a4540ddfbfa1e067c..2656f772d0b325c20a706c1e74ca252542c669d0 100644 (file)
@@ -62,7 +62,7 @@ import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
 import static org.sonar.api.utils.DateUtils.formatDateTime;
 import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
 import static org.sonar.db.issue.IssueTesting.newIssue;
-import static org.sonar.db.issue.IssueTesting.newIssuechangeDto;
+import static org.sonar.db.issue.IssueTesting.newIssueChangeDto;
 import static org.sonar.db.rule.RuleTesting.newRule;
 import static org.sonar.db.user.UserTesting.newUserDto;
 import static org.sonar.server.issue.index.IssueScope.MAIN;
@@ -71,7 +71,7 @@ import static org.sonar.server.issue.index.IssueScope.TEST;
 @RunWith(MockitoJUnitRunner.class)
 public class SearchResponseFormatFormatOperationTest {
   @Rule
-  public DbTester db = DbTester.create();
+  public DbTester db = DbTester.create(true);
   private final Durations durations = new Durations();
   private final Languages languages = mock(Languages.class);
   private final TextRangeResponseFormatter textRangeResponseFormatter = mock(TextRangeResponseFormatter.class);
@@ -252,7 +252,7 @@ public class SearchResponseFormatFormatOperationTest {
 
   @Test
   public void formatOperation_should_add_comments_on_issues() {
-    IssueChangeDto issueChangeDto = newIssuechangeDto(issueDto);
+    IssueChangeDto issueChangeDto = newIssueChangeDto(issueDto);
     searchResponseData.setComments(List.of(issueChangeDto));
 
     Operation result = searchResponseFormat.formatOperation(searchResponseData);