Search in sources :

Example 1 with BRANCH

use of org.sonar.db.component.BranchType.BRANCH in project sonarqube by SonarSource.

the class ComponentDaoTest method selectPrivateProjectsWithNcloc.

@Test
public void selectPrivateProjectsWithNcloc() {
    MetricDto metric = db.measures().insertMetric(m -> m.setKey("ncloc"));
    // project1, not the biggest branch - not returned
    final ComponentDto project1 = db.components().insertPrivateProject(b -> b.setName("foo"));
    insertMeasure(20d, project1, metric);
    // branch of project1 - returned
    insertMeasure(30d, db.components().insertProjectBranch(project1, b -> b.setBranchType(BRANCH)), metric);
    // project2 - returned
    insertMeasure(10d, db.components().insertPrivateProject(b -> b.setName("bar")), metric);
    // public project - not returned
    insertMeasure(11d, db.components().insertPublicProject(b -> b.setName("other")), metric);
    List<ProjectNclocDistributionDto> result = underTest.selectPrivateProjectsWithNcloc(db.getSession());
    assertThat(result).extracting(ProjectNclocDistributionDto::getName).containsExactly("foo", "bar");
    assertThat(result).extracting(ProjectNclocDistributionDto::getNcloc).containsExactly(30L, 10L);
}
Also used : Arrays(java.util.Arrays) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) Scopes(org.sonar.api.resources.Scopes) DbSession(org.sonar.db.DbSession) STATUS_CLOSED(org.sonar.api.issue.Issue.STATUS_CLOSED) PULL_REQUEST(org.sonar.db.component.BranchType.PULL_REQUEST) Collections.singletonList(java.util.Collections.singletonList) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Collections.singleton(java.util.Collections.singleton) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) Collectors.toSet(java.util.stream.Collectors.toSet) DbTester(org.sonar.db.DbTester) APP(org.sonar.api.resources.Qualifiers.APP) ImmutableMap(com.google.common.collect.ImmutableMap) System2(org.sonar.api.utils.System2) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) AlwaysIncreasingSystem2(org.sonar.api.impl.utils.AlwaysIncreasingSystem2) ComponentTesting.newPortfolio(org.sonar.db.component.ComponentTesting.newPortfolio) DateUtils.parseDate(org.sonar.api.utils.DateUtils.parseDate) Collectors(java.util.stream.Collectors) BRANCH(org.sonar.db.component.BranchType.BRANCH) ComponentNewValue(org.sonar.db.audit.model.ComponentNewValue) STATUS_CONFIRMED(org.sonar.api.issue.Issue.STATUS_CONFIRMED) List(java.util.List) ComponentTesting.newSubPortfolio(org.sonar.db.component.ComponentTesting.newSubPortfolio) Stream(java.util.stream.Stream) VIEW(org.sonar.api.resources.Qualifiers.VIEW) ListAssert(org.assertj.core.api.ListAssert) ProjectDto(org.sonar.db.project.ProjectDto) Optional(java.util.Optional) SUBVIEW(org.sonar.api.resources.Qualifiers.SUBVIEW) ComponentTesting.newDirectory(org.sonar.db.component.ComponentTesting.newDirectory) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ComponentTesting.newBranchDto(org.sonar.db.component.ComponentTesting.newBranchDto) IssueDto(org.sonar.db.issue.IssueDto) RuleDefinitionDto(org.sonar.db.rule.RuleDefinitionDto) ComponentTesting.newFileDto(org.sonar.db.component.ComponentTesting.newFileDto) STATUS_OPEN(org.sonar.api.issue.Issue.STATUS_OPEN) RunWith(org.junit.runner.RunWith) ComponentTesting.newBranchComponent(org.sonar.db.component.ComponentTesting.newBranchComponent) CHILDREN(org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Supplier(java.util.function.Supplier) PROJECT(org.sonar.api.resources.Qualifiers.PROJECT) ComponentTesting.newApplication(org.sonar.db.component.ComponentTesting.newApplication) ArrayList(java.util.ArrayList) RowNotFoundException(org.sonar.db.RowNotFoundException) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) ComponentTesting.newProjectCopy(org.sonar.db.component.ComponentTesting.newProjectCopy) Nullable(javax.annotation.Nullable) ImmutableSet.of(com.google.common.collect.ImmutableSet.of) Collections.emptySet(java.util.Collections.emptySet) LEAVES(org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES) FileSourceDto(org.sonar.db.source.FileSourceDto) RandomStringUtils.randomAlphabetic(org.apache.commons.lang.RandomStringUtils.randomAlphabetic) Assertions.tuple(org.assertj.core.api.Assertions.tuple) UseDataProvider(com.tngtech.java.junit.dataprovider.UseDataProvider) Test(org.junit.Test) NoOpAuditPersister(org.sonar.db.audit.NoOpAuditPersister) Assertions.entry(org.assertj.core.api.Assertions.entry) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) ComponentTesting.newPrivateProjectDto(org.sonar.db.component.ComponentTesting.newPrivateProjectDto) AuditPersister(org.sonar.db.audit.AuditPersister) Rule(org.junit.Rule) MetricDto(org.sonar.db.metric.MetricDto) Qualifiers(org.sonar.api.resources.Qualifiers) Collections(java.util.Collections) ComponentTesting.newModuleDto(org.sonar.db.component.ComponentTesting.newModuleDto) MetricDto(org.sonar.db.metric.MetricDto) Test(org.junit.Test)

Example 2 with BRANCH

use of org.sonar.db.component.BranchType.BRANCH in project sonarqube by SonarSource.

the class AsyncIssueIndexingImplTest method characteristics_are_defined.

@Test
public void characteristics_are_defined() {
    BranchDto dto = new BranchDto().setBranchType(BRANCH).setKey("branch_1").setUuid("branch_uuid1").setProjectUuid("project_uuid1");
    dbClient.branchDao().insert(dbTester.getSession(), dto);
    dbTester.commit();
    insertSnapshot("analysis_1", "project_uuid1", 1);
    BranchDto dto2 = new BranchDto().setBranchType(PULL_REQUEST).setKey("pr_1").setUuid("pr_uuid_1").setProjectUuid("project_uuid2");
    dbClient.branchDao().insert(dbTester.getSession(), dto2);
    dbTester.commit();
    insertSnapshot("analysis_2", "project_uuid2", 2);
    underTest.triggerOnIndexCreation();
    ArgumentCaptor<Collection<CeTaskSubmit>> captor = ArgumentCaptor.forClass(Collection.class);
    verify(ceQueue, times(1)).massSubmit(captor.capture());
    List<Collection<CeTaskSubmit>> captures = captor.getAllValues();
    assertThat(captures).hasSize(1);
    Collection<CeTaskSubmit> tasks = captures.get(0);
    assertThat(tasks).hasSize(2);
    assertThat(tasks).extracting(p -> p.getCharacteristics().get(BRANCH_TYPE_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.BRANCH_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.PULL_REQUEST)).containsExactlyInAnyOrder(tuple("BRANCH", "branch_1", null), tuple("PULL_REQUEST", null, "pr_1"));
}
Also used : BranchDto(org.sonar.db.component.BranchDto) Arrays(java.util.Arrays) BRANCH_TYPE_KEY(org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY) STATUS_PROCESSED(org.sonar.db.component.SnapshotDto.STATUS_PROCESSED) REPORT(org.sonar.db.ce.CeTaskTypes.REPORT) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) PULL_REQUEST(org.sonar.db.component.BranchType.PULL_REQUEST) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CeActivityDto(org.sonar.db.ce.CeActivityDto) ArgumentCaptor(org.mockito.ArgumentCaptor) Map(java.util.Map) BRANCH_ISSUE_SYNC(org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC) CeTaskCharacteristicDto(org.sonar.db.ce.CeTaskCharacteristicDto) Before(org.junit.Before) DbTester(org.sonar.db.DbTester) System2(org.sonar.api.utils.System2) Assertions.tuple(org.assertj.core.api.Assertions.tuple) Collection(java.util.Collection) UuidFactory(org.sonar.core.util.UuidFactory) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) BRANCH(org.sonar.db.component.BranchType.BRANCH) SequenceUuidFactory(org.sonar.core.util.SequenceUuidFactory) Mockito.verify(org.mockito.Mockito.verify) DbClient(org.sonar.db.DbClient) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) List(java.util.List) Rule(org.junit.Rule) LogTester(org.sonar.api.utils.log.LogTester) CeTaskSubmit(org.sonar.ce.queue.CeTaskSubmit) CeQueueDto(org.sonar.db.ce.CeQueueDto) Optional(java.util.Optional) Status(org.sonar.db.ce.CeActivityDto.Status) SnapshotDto(org.sonar.db.component.SnapshotDto) Assertions.assertThatCode(org.assertj.core.api.Assertions.assertThatCode) LoggerLevel(org.sonar.api.utils.log.LoggerLevel) CeQueue(org.sonar.ce.queue.CeQueue) Mockito.mock(org.mockito.Mockito.mock) BranchDto(org.sonar.db.component.BranchDto) Collection(java.util.Collection) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) CeTaskSubmit(org.sonar.ce.queue.CeTaskSubmit) Test(org.junit.Test)

Example 3 with BRANCH

use of org.sonar.db.component.BranchType.BRANCH in project sonarqube by SonarSource.

the class SearchEventsAction method computeQualityGateChangeEvents.

private Stream<Event> computeQualityGateChangeEvents(DbSession dbSession, Map<String, ComponentDto> projectsByUuid, Map<String, BranchDto> branchesByUuids, List<SnapshotDto> analyses) {
    Map<String, EventDto> eventsByComponentUuid = new HashMap<>();
    dbClient.eventDao().selectByAnalysisUuids(dbSession, analyses.stream().map(SnapshotDto::getUuid).collect(toList(analyses.size()))).stream().sorted(comparing(EventDto::getDate)).filter(e -> EventCategory.QUALITY_GATE.getLabel().equals(e.getCategory())).forEach(e -> eventsByComponentUuid.put(e.getComponentUuid(), e));
    Predicate<EventDto> branchPredicate = e -> branchesByUuids.get(e.getComponentUuid()).getBranchType() == BRANCH;
    return eventsByComponentUuid.values().stream().sorted(comparing(EventDto::getDate)).filter(branchPredicate).map(e -> {
        BranchDto branch = branchesByUuids.get(e.getComponentUuid());
        ComponentDto project = projectsByUuid.get(branch.getProjectUuid());
        checkState(project != null, "Found event '%s', for a component that we did not search for", e.getUuid());
        return Event.newBuilder().setCategory(EventCategory.fromLabel(e.getCategory()).name()).setProject(project.getKey()).setMessage(branch.isMain() ? format("Quality Gate status of project '%s' changed to '%s'", project.name(), e.getName()) : format("Quality Gate status of project '%s' on branch '%s' changed to '%s'", project.name(), branch.getKey(), e.getName())).setLink(computeDashboardLink(project, branch)).setDate(formatDateTime(e.getDate())).build();
    });
}
Also used : IntStream(java.util.stream.IntStream) BranchDto(org.sonar.db.component.BranchDto) EventCategory(org.sonar.server.projectanalysis.ws.EventCategory) Date(java.util.Date) UuidFromPairs.fromDates(org.sonar.server.developers.ws.UuidFromPairs.fromDates) HashMap(java.util.HashMap) Server(org.sonar.api.platform.Server) DbSession(org.sonar.db.DbSession) PULL_REQUEST(org.sonar.db.component.BranchType.PULL_REQUEST) Request(org.sonar.api.server.ws.Request) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) WebService(org.sonar.api.server.ws.WebService) String.join(java.lang.String.join) IssueIndex(org.sonar.server.issue.index.IssueIndex) Map(java.util.Map) Response(org.sonar.api.server.ws.Response) Comparator.comparing(java.util.Comparator.comparing) DateUtils.formatDateTime(org.sonar.api.utils.DateUtils.formatDateTime) MoreCollectors.toList(org.sonar.core.util.stream.MoreCollectors.toList) Predicate(java.util.function.Predicate) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Collectors(java.util.stream.Collectors) KeyExamples(org.sonar.server.ws.KeyExamples) BRANCH(org.sonar.db.component.BranchType.BRANCH) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) DbClient(org.sonar.db.DbClient) BadRequestException.checkRequest(org.sonar.server.exceptions.BadRequestException.checkRequest) URLEncoder(java.net.URLEncoder) List(java.util.List) ComponentDto(org.sonar.db.component.ComponentDto) Stream(java.util.stream.Stream) UserRole(org.sonar.api.web.UserRole) IssueIndexSyncProgressChecker(org.sonar.server.issue.index.IssueIndexSyncProgressChecker) UuidFromPairs.componentUuids(org.sonar.server.developers.ws.UuidFromPairs.componentUuids) MoreCollectors.uniqueIndex(org.sonar.core.util.stream.MoreCollectors.uniqueIndex) ProjectStatistics(org.sonar.server.issue.index.ProjectStatistics) UserSession(org.sonar.server.user.UserSession) SnapshotDto(org.sonar.db.component.SnapshotDto) SearchEventsWsResponse(org.sonarqube.ws.Developers.SearchEventsWsResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EventDto(org.sonar.db.event.EventDto) DateUtils.parseDateTimeQuietly(org.sonar.api.utils.DateUtils.parseDateTimeQuietly) Event(org.sonarqube.ws.Developers.SearchEventsWsResponse.Event) WsUtils.writeProtobuf(org.sonar.server.ws.WsUtils.writeProtobuf) BranchDto(org.sonar.db.component.BranchDto) HashMap(java.util.HashMap) SnapshotDto(org.sonar.db.component.SnapshotDto) EventDto(org.sonar.db.event.EventDto) ComponentDto(org.sonar.db.component.ComponentDto)

Example 4 with BRANCH

use of org.sonar.db.component.BranchType.BRANCH in project sonarqube by SonarSource.

the class ListActionTest method status_on_branch.

@Test
public void status_on_branch() {
    ComponentDto project = db.components().insertPrivateProject();
    userSession.logIn().addProjectPermission(USER, project);
    ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(org.sonar.db.component.BranchType.BRANCH));
    db.measures().insertLiveMeasure(branch, qualityGateStatus, m -> m.setData("OK"));
    ListWsResponse response = ws.newRequest().setParam("project", project.getKey()).executeProtobuf(ListWsResponse.class);
    assertThat(response.getBranchesList()).extracting(b -> b.getStatus().hasQualityGateStatus(), b -> b.getStatus().getQualityGateStatus()).containsExactlyInAnyOrder(tuple(false, ""), tuple(true, "OK"));
}
Also used : SCAN_EXECUTION(org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION) ComponentFinder(org.sonar.server.component.ComponentFinder) PermissionIndexerTester(org.sonar.server.permission.index.PermissionIndexerTester) AsyncIssueIndexing(org.sonar.server.issue.index.AsyncIssueIndexing) RuleDefinitionDto(org.sonar.db.rule.RuleDefinitionDto) BranchType(org.sonarqube.ws.Common.BranchType) ProjectBranches(org.sonarqube.ws.ProjectBranches) EsTester(org.sonar.server.es.EsTester) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BUG(org.sonar.api.rules.RuleType.BUG) Branch(org.sonarqube.ws.ProjectBranches.Branch) PROJECT(org.sonar.api.resources.Qualifiers.PROJECT) DateUtils.dateToLong(org.sonar.api.utils.DateUtils.dateToLong) WebService(org.sonar.api.server.ws.WebService) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) SnapshotTesting.newAnalysis(org.sonar.db.component.SnapshotTesting.newAnalysis) IssueIteratorFactory(org.sonar.server.issue.index.IssueIteratorFactory) ComponentTesting(org.sonar.db.component.ComponentTesting) ResourceTypesRule(org.sonar.db.component.ResourceTypesRule) ResourceTypes(org.sonar.api.resources.ResourceTypes) Before(org.junit.Before) UserSessionRule(org.sonar.server.tester.UserSessionRule) DbTester(org.sonar.db.DbTester) System2(org.sonar.api.utils.System2) Assertions.tuple(org.assertj.core.api.Assertions.tuple) USER(org.sonar.api.web.UserRole.USER) JsonAssert.assertJson(org.sonar.test.JsonAssert.assertJson) Test(org.junit.Test) WsActionTester(org.sonar.server.ws.WsActionTester) BRANCH(org.sonar.db.component.BranchType.BRANCH) NotFoundException(org.sonar.server.exceptions.NotFoundException) String.format(java.lang.String.format) ComponentDto(org.sonar.db.component.ComponentDto) ALERT_STATUS_KEY(org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY) Rule(org.junit.Rule) MetricDto(org.sonar.db.metric.MetricDto) DateUtils.parseDateTime(org.sonar.api.utils.DateUtils.parseDateTime) ListWsResponse(org.sonarqube.ws.ProjectBranches.ListWsResponse) IssueIndexer(org.sonar.server.issue.index.IssueIndexer) Mockito.mock(org.mockito.Mockito.mock) ListWsResponse(org.sonarqube.ws.ProjectBranches.ListWsResponse) ComponentDto(org.sonar.db.component.ComponentDto) Test(org.junit.Test)

Example 5 with BRANCH

use of org.sonar.db.component.BranchType.BRANCH in project sonarqube by SonarSource.

the class ListAction method handle.

@Override
public void handle(Request request, Response response) throws Exception {
    String projectKey = request.mandatoryParam(PARAM_PROJECT);
    try (DbSession dbSession = dbClient.openSession(false)) {
        ProjectDto projectOrApp = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey);
        checkPermission(projectOrApp);
        Collection<BranchDto> branches = dbClient.branchDao().selectByProject(dbSession, projectOrApp).stream().filter(b -> b.getBranchType() == BRANCH).collect(toList());
        List<String> branchUuids = branches.stream().map(BranchDto::getUuid).collect(toList());
        Map<String, LiveMeasureDto> qualityGateMeasuresByComponentUuids = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricKeys(dbSession, branchUuids, singletonList(ALERT_STATUS_KEY)).stream().collect(uniqueIndex(LiveMeasureDto::getComponentUuid));
        Map<String, String> analysisDateByBranchUuid = dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, branchUuids).stream().collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> formatDateTime(s.getCreatedAt())));
        ProjectBranches.ListWsResponse.Builder protobufResponse = ProjectBranches.ListWsResponse.newBuilder();
        branches.forEach(b -> addBranch(protobufResponse, b, qualityGateMeasuresByComponentUuids.get(b.getUuid()), analysisDateByBranchUuid.get(b.getUuid())));
        WsUtils.writeProtobuf(protobufResponse.build(), request, response);
    }
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) BranchDto(org.sonar.db.component.BranchDto) AbstractUserSession.insufficientPrivilegesException(org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException) ComponentFinder(org.sonar.server.component.ComponentFinder) ProjectBranches(org.sonarqube.ws.ProjectBranches) DbSession(org.sonar.db.DbSession) Collections.singletonList(java.util.Collections.singletonList) Request(org.sonar.api.server.ws.Request) SCAN(org.sonar.db.permission.GlobalPermission.SCAN) WebService(org.sonar.api.server.ws.WebService) Map(java.util.Map) Response(org.sonar.api.server.ws.Response) DateUtils.formatDateTime(org.sonar.api.utils.DateUtils.formatDateTime) Nullable(javax.annotation.Nullable) MoreCollectors.toList(org.sonar.core.util.stream.MoreCollectors.toList) Resources(com.google.common.io.Resources) USER(org.sonar.api.web.UserRole.USER) Optional.ofNullable(java.util.Optional.ofNullable) Collection(java.util.Collection) WsUtils(org.sonar.server.ws.WsUtils) BranchesWs.addProjectParam(org.sonar.server.branch.ws.BranchesWs.addProjectParam) PARAM_PROJECT(org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT) BRANCH(org.sonar.db.component.BranchType.BRANCH) Common(org.sonarqube.ws.Common) DbClient(org.sonar.db.DbClient) List(java.util.List) ALERT_STATUS_KEY(org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY) UserRole(org.sonar.api.web.UserRole) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) ACTION_LIST(org.sonar.server.branch.ws.ProjectBranchesParameters.ACTION_LIST) ProjectDto(org.sonar.db.project.ProjectDto) MoreCollectors.uniqueIndex(org.sonar.core.util.stream.MoreCollectors.uniqueIndex) Change(org.sonar.api.server.ws.Change) UserSession(org.sonar.server.user.UserSession) SnapshotDto(org.sonar.db.component.SnapshotDto) DbSession(org.sonar.db.DbSession) BranchDto(org.sonar.db.component.BranchDto) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto)

Aggregations

BRANCH (org.sonar.db.component.BranchType.BRANCH)8 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)6 Rule (org.junit.Rule)6 Test (org.junit.Test)6 Mockito.mock (org.mockito.Mockito.mock)6 System2 (org.sonar.api.utils.System2)6 DbClient (org.sonar.db.DbClient)6 DbTester (org.sonar.db.DbTester)6 List (java.util.List)5 Map (java.util.Map)5 Mockito.verify (org.mockito.Mockito.verify)5 Date (java.util.Date)4 Assertions.tuple (org.assertj.core.api.Assertions.tuple)4 ArgumentCaptor (org.mockito.ArgumentCaptor)4 SequenceUuidFactory (org.sonar.core.util.SequenceUuidFactory)4 BranchDto (org.sonar.db.component.BranchDto)4 PULL_REQUEST (org.sonar.db.component.BranchType.PULL_REQUEST)4 ComponentDto (org.sonar.db.component.ComponentDto)4 SnapshotDto (org.sonar.db.component.SnapshotDto)4 RuleDefinitionDto (org.sonar.db.rule.RuleDefinitionDto)4