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;
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
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
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"))
@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"));
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);
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();
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();
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.");
}
@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() {
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
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)
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)
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;
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();
.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();
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;
- }
}
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);
}
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();
}
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);
* 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);
}
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;
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.
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()));
/**
* 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) {
@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);
@CheckForNull
Long selectLastAnalysisDateByProject(String projectUuid);
- List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjects(@Param("projectUuids") Collection<String> projectUuids);
+ List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjectUuids(@Param("projectUuids") Collection<String> projectUuids);
}
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;
}
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);
}
@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);
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();
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;
}
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;
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) {
.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())
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;
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);
}
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) {
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))
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;
*/
package org.sonar.db.project;
+import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
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();
}
<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"/>
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>)
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
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
}
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"));
}
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;
}
@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);
}
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);
@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);
}
@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);
@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();
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
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
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
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
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
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);
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;
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;
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;
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
- doIndexByProjectUuid(Size.LARGE);
+ doIndexByEntityUuid(Size.LARGE);
}
public void indexAll() {
- doIndexByProjectUuid(Size.REGULAR);
+ doIndexByEntityUuid(Size.REGULAR);
}
@Override
}
@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
}
/**
- * @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()));
}
}
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)) {
/**
* 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);
*/
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()));
}
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) {
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);
}
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;
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;
}
@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;
}
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";
@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);
}
IndexingResult result = new IndexingResult();
result.add(doIndexIssueItems(dbSession, itemsByIssueKey));
- result.add(doIndexProjectItems(dbSession, itemsByProjectKey));
+ result.add(doIndexProjectItems(dbSession, itemsByProjectUuid));
return result;
}
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();
}
@Override
public String getId() {
- return idOf(projectUuid);
+ return idOf(entityUuid);
}
public static String idOf(String projectUuid) {
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());
}
@Override
protected Optional<String> getSimpleMainTypeRouting() {
- return Optional.of(projectUuid);
+ return Optional.of(entityUuid);
}
private AuthorizationDoc setAllowAnyone() {
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() {
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;
}
-
}
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 {
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
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();
}
* 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
return new IndexingResult();
}
- Set<String> views = items
+ Set<String> viewUuids = items
.stream()
.map(EsQueueDto::getDocId)
.collect(toHashSet(items.size()));
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();
}
.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"))
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");
@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
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
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
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;
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;
.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());
assertThat(underTest.selectByUuids(dbClient, dbSession, projectUuids))
.hasSize(3500)
- .extracting(IndexPermissions::getProjectUuid)
+ .extracting(IndexPermissions::getEntityUuid)
.containsAll(projectUuids);
}
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());
}
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());
}
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());
}
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());
}
}
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() {
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;
}
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;
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;
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));
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);
}
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);
}
}
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()
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);
}));
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));
}
}
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));
}
}
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;
.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()))
@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);
@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))
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);
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);
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)
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)
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);
.addProjectPermission(USER, projectData2.getProjectDto());
assertThat(underTest.create(new SearchRequest()
- .setComponents(singletonList(application.getKey())))
+ .setComponentKeys(singletonList(application.getKey())))
.viewUuids()).containsExactly(application.uuid());
}
// 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);
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)
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) {
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;
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)
if (resolved != null) {
assertThat(payload).contains("\"resolved\":" + resolved);
}
-
}
}
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();
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();
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);
.isInstanceOf(IllegalArgumentException.class);
}
-
@Test
public void delete_application_from_db_and_index() {
DbData data1 = insertProjectData();
assertExists(data3);
}
-
@Test
public void delete_webhooks_from_projects() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
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) {
@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();
@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
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);
@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.");
@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) {
assertThat(dbClient.componentDao().selectByKey(dbSession, newKey)).isPresent();
}
- private void logInAsProjectAdministrator(ComponentDto provisionedProject) {
+ private void logInAsProjectAdministrator(ProjectDto provisionedProject) {
userSession.logIn("john").addProjectPermission(UserRole.ADMIN, provisionedProject);
}
}
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");
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;
@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())
" \"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" +
@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())
" \"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" +
@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())
@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));
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())
@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())
@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();
@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();
@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()
@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();
@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));
" \"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" +
@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())
" \"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" +
@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())
" \"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" +
@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())
@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");
@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())
@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());
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;
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;
@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();
@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)));
@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)));
@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));
@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
@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)
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));
}
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;
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;
@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},
};
@DataProvider
public static Object[][] enterprise_or_datacenter_edition() {
- return new Object[][]{
+ return new Object[][] {
{Edition.ENTERPRISE},
{Edition.DATACENTER},
};
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()
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"));
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);
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"));
@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
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")));
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();
}
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;
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() {
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();
.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();
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);
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);
.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
@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")
@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())
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")
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();
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;
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();
@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);
@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);
@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);
@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);
@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);
@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);
@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);
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;
}
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();
@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);
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();
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());
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());
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();
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");
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");
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();
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
userSession.logIn();
TestRequest request = tester.newRequest()
- .setParam("projectKey", correctProject.getKey())
+ .setParam("projectKey", correctMainBranch.getKey())
.setParam("branchName", DEFAULT_BRANCH);
assertThatThrownBy(request::execute)
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())
@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();
@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();
@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")
.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");
@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")
.setRuleUuid(javaRule.getUuid())
.setStatus(Issue.STATUS_TO_REVIEW)
.setLanguage("java")
- .setProject(correctProject)
+ .setProject(correctMainBranch)
.setComponent(correctFile));
IssueDto issueAfter = issueDbTester.insertHotspot(p -> p.setSeverity("MINOR")
.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));
@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")
.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");
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);
}
}
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;
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
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);
}
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);
}
@DataProvider
public static Object[][] fixedOrSafeResolution() {
- return new Object[][]{
+ return new Object[][] {
{RESOLUTION_SAFE},
{RESOLUTION_FIXED}
};
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();
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();
@DataProvider
public static Object[][] onlyMineParamValues() {
- return new Object[][]{
+ return new Object[][] {
{"yes", true},
{"true", true},
{"no", false},
@DataProvider
public static Object[][] validStatusesAndResolutions() {
- return new Object[][]{
+ return new Object[][] {
{STATUS_TO_REVIEW, null},
{STATUS_REVIEWED, RESOLUTION_FIXED},
{STATUS_REVIEWED, RESOLUTION_SAFE},
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);
}
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;
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"));
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);
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;
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;
@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)
@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)
@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)
@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")
.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());
@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)
@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)
@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)
@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)
@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()
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)
@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)
@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);
.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)
@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);
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)
@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);
.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)
@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>";
.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)
@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)
@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");
.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)
@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)
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();
}
@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();
@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();
@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)
@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)
@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)
@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)
@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)
@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)
@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)
@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)
@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()));
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()));
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);
@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()));
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,
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);
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()));
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));
}
@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())
@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();
@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();
@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)
.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")
.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")
}
}
+ 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)
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();
}
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
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);
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);
@Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
+ public DbTester dbTester = DbTester.create(System2.INSTANCE, true);
@Rule
public EsTester es = EsTester.create();
@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);
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;
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;
public class AuthorsActionIT {
@Rule
- public DbTester db = DbTester.create();
+ public DbTester db = DbTester.create(true);
@Rule
public EsTester es = EsTester.create();
@Rule
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();
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();
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();
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
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();
@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();
.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();
.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();
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();
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();
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;
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;
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);
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"));
userSession.logIn();
TestRequest request = tester.newRequest()
- .setParam("projectKey", correctProject.getKey())
+ .setParam("projectKey", correctMainBranch.getKey())
.setParam("branchName", DEFAULT_BRANCH);
assertThatThrownBy(request::execute)
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())
@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();
@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();
@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")
.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");
@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")
.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");
@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"));
.setCreatedAt(NOW)
.setRule(javaRule)
.setStatus(Issue.STATUS_OPEN)
- .setProject(correctProject)
+ .setProject(correctMainBranch)
.setComponent(correctFile)
.setType(2));
.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");
}
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);
}
}
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;
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;
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);
private RuleDto correctRule, incorrectRule;
private ComponentDto correctProject, incorrectProject;
+ private ProjectDto project;
private ComponentDto correctFile, incorrectFile;
@Before
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();
@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)
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())
@Test
public void given15TaintsInTheTable_returnOnly10ThatBelongToProject() throws IOException {
- loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+ loginWithBrowsePermission(project);
generateTaints(correctRule, correctProject, correctFile, 10);
generateTaints(incorrectRule, incorrectProject, incorrectFile, 5);
@Test
public void givenNoTaintsBelongToTheProject_return0Taints() throws IOException {
- loginWithBrowsePermission(correctProject.uuid(), correctFile.uuid());
+ loginWithBrowsePermission(project);
generateTaints(incorrectRule, incorrectProject, incorrectFile, 5);
TestRequest request = tester.newRequest()
@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"));
@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")
@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"));
}
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);
}
}
@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));
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()
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()
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()
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()
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()
@Rule
public UserSessionRule userSession = standalone();
@Rule
- public DbTester db = DbTester.create();
+ public DbTester db = DbTester.create(true);
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = standalone();
@Rule
- public DbTester db = DbTester.create();
+ public DbTester db = DbTester.create(true);
@Rule
public EsTester es = EsTester.create();
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"));
@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);
@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);
@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")));
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();
@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"));
@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"));
@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"));
@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)
assertThat(result.getIssuesList())
.extracting(Issue::getKey)
.containsExactlyInAnyOrder(issueDto1.getKey(), issueDto3.getKey());
-
}
@Test
public class SetTagsActionIT {
@Rule
- public DbTester db = DbTester.create();
+ public DbTester db = DbTester.create(true);
@Rule
public EsTester es = EsTester.create();
@Rule
IssueDto issueDto = db.issues().insertIssue();
logInAndAddProjectPermission(issueDto, ISSUE_ADMIN);
- assertThatThrownBy(() -> call(issueDto.getKey(), "bug"))
+ assertThatThrownBy(() -> call(issueDto.getKey(), "bug"))
.isInstanceOf(ForbiddenException.class);
}
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
@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() {
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();
@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() {
@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() {
@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() {
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;
.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()));
@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());
"longName": "null/NAME_file1",
"q": "FIL",
"project": "KEY_projectUuid",
- "projectName": "LONG_NAME_projectUuid",
+ "projectName": "NAME_projectUuid",
"measures": {}
},
"sources": [
"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": [
"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,
"longName": "null/NAME_file",
"q": "FIL",
"project": "KEY_projectUuid",
- "projectName": "LONG_NAME_projectUuid",
+ "projectName": "NAME_projectUuid",
"measures": {
"lines": "200.0",
"coverage": "95.4",
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())));
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;
static final String PARAM_COMPONENT = "component";
private final DbClient dbClient;
-
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final ComponentViewerJsonWriter componentViewerJsonWriter;
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);
}
}
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);
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;
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());
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);
}
}
}
- 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);
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;
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;
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;
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;
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));
.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()))
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;
// 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()
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;
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);
}
.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());
.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() {
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);
}
}
}
}
- 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());
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;
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;
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) {
.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);
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;
}
}
+ public ProjectDto getProjectDto() {
+ return project;
+ }
+
@CheckForNull
public String getBranch() {
return branch;
return pullRequest;
}
- public ComponentDto getBranchComponent() {
- return branchComponent;
- }
-
public ComponentDto getComponent() {
return component;
}
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;
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;
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
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);
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);
}
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(
request.param(TEXT_QUERY),
request.mandatoryParamAsInt(PAGE_SIZE));
}
-
}
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);
return;
}
- issueChangeEventService.distributeIssueChangeEvent(issues, bulkChangeData.projectsByUuid, bulkChangeData.branchesByProjectUuid);
+ issueChangeEventService.distributeIssueChangeEvent(issues, bulkChangeData.branchComponentByUuid, bulkChangeData.branchesByProjectUuid);
}
@CheckForNull
}
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;
}
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;
.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,
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());
}
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()) {
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);
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);
.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))
.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))
}
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 {
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;
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);
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);
}
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;
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()) {
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();
});
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;
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);
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) {
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);
}
}
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
}
}
- 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) {
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);
}
*/
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<>();
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) {
}
}
- 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);
}
}
+ public Set<String> getProjectUuids() {
+ return projectUuids;
+ }
+
public List<String> getIssueKeys() {
return issueKeys;
}
return componentUuids;
}
- public Set<String> getProjectUuids() {
- return projectUuids;
+ public Set<String> getBranchUuids() {
+ return branchUuids;
}
public Set<String> getRuleUuids() {
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;
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();
}
}
- 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) {
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()
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;
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();
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()));
}
}
}
}
- 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;
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);
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;
@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);
@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);