Search in sources :

Example 66 with BranchDto

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

the class IssueUpdater method getBranch.

private BranchDto getBranch(DbSession dbSession, DefaultIssue issue, @Nullable String projectUuid) {
    String issueKey = issue.key();
    checkState(projectUuid != null, "Issue '%s' has no project", issueKey);
    BranchDto component = dbClient.branchDao().selectByUuid(dbSession, projectUuid).orElse(null);
    checkState(component != null, "Branch uuid '%s' for issue key '%s' cannot be found", projectUuid, issueKey);
    return component;
}
Also used : BranchDto(org.sonar.db.component.BranchDto)

Example 67 with BranchDto

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

the class LiveMeasureComputerImpl method refreshComponentsOnSameProject.

private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
    // load all the components to be refreshed, including their ancestors
    List<ComponentDto> components = loadTreeOfComponents(dbSession, touchedComponents);
    ComponentDto branchComponent = findBranchComponent(components);
    BranchDto branch = loadBranch(dbSession, branchComponent);
    ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
    Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
    if (!lastAnalysis.isPresent()) {
        return Optional.empty();
    }
    QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
    Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
    List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, metricKeys);
    Map<String, MetricDto> metricsPerId = metrics.stream().collect(uniqueIndex(MetricDto::getUuid));
    List<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(toArrayList(components.size()));
    List<LiveMeasureDto> dbMeasures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerId.keySet());
    // previous status must be load now as MeasureMatrix mutate the LiveMeasureDto which are passed to it
    Metric.Level previousStatus = loadPreviousStatus(metrics, dbMeasures);
    Configuration config = projectConfigurationLoader.loadProjectConfiguration(dbSession, branchComponent);
    DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
    MeasureMatrix matrix = new MeasureMatrix(components, metricsPerId.values(), dbMeasures);
    FormulaContextImpl context = new FormulaContextImpl(matrix, debtRatingGrid);
    long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
    components.forEach(c -> {
        IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByBaseComponent(dbSession, c, beginningOfLeak));
        for (IssueMetricFormula formula : formulaFactory.getFormulas()) {
            // use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
            if (shouldUseLeakFormulas(lastAnalysis.get(), branch) || !formula.isOnLeak()) {
                context.change(c, formula);
                try {
                    formula.compute(context, issueCounter);
                } catch (RuntimeException e) {
                    throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on " + context.getComponent().getDbKey(), e);
                }
            }
        }
    });
    EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix, config);
    // persist the measures that have been created or updated
    matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE).forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
    projectIndexer.commitAndIndexComponents(dbSession, singleton(branchComponent), ProjectIndexer.Cause.MEASURE_CHANGE);
    return Optional.of(new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) BranchDto(org.sonar.db.component.BranchDto) Configuration(org.sonar.api.config.Configuration) SnapshotDto(org.sonar.db.component.SnapshotDto) ComponentDto(org.sonar.db.component.ComponentDto) QGChangeEvent(org.sonar.server.qualitygate.changeevent.QGChangeEvent) QualityGate(org.sonar.server.qualitygate.QualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) MetricDto(org.sonar.db.metric.MetricDto) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) Metric(org.sonar.api.measures.Metric) DebtRatingGrid(org.sonar.server.measure.DebtRatingGrid)

Example 68 with BranchDto

use of org.sonar.db.component.BranchDto 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 project = componentFinder.getProjectByKey(dbSession, projectKey);
        userSession.checkProjectPermission(UserRole.ADMIN, project);
        Collection<BranchDto> branches = dbClient.branchDao().selectByProject(dbSession, project).stream().filter(b -> b.getBranchType() == BranchType.BRANCH).sorted(Comparator.comparing(BranchDto::getKey)).collect(toList());
        List<NewCodePeriodDto> newCodePeriods = newCodePeriodDao.selectAllByProject(dbSession, project.getUuid());
        Map<String, InheritedNewCodePeriod> newCodePeriodByBranchUuid = newCodePeriods.stream().collect(Collectors.toMap(NewCodePeriodDto::getBranchUuid, dto -> new InheritedNewCodePeriod(dto, dto.getBranchUuid() == null)));
        InheritedNewCodePeriod projectDefault = newCodePeriodByBranchUuid.getOrDefault(null, getGlobalOrDefault(dbSession));
        Map<String, String> analysis = newCodePeriods.stream().filter(newCodePeriodDto -> newCodePeriodDto.getType().equals(NewCodePeriodType.SPECIFIC_ANALYSIS)).collect(Collectors.toMap(NewCodePeriodDto::getUuid, NewCodePeriodDto::getValue));
        Map<String, Long> analysisUuidDateMap = dbClient.snapshotDao().selectByUuids(dbSession, new HashSet<>(analysis.values())).stream().collect(Collectors.toMap(SnapshotDto::getUuid, SnapshotDto::getCreatedAt));
        ListWSResponse.Builder builder = ListWSResponse.newBuilder();
        for (BranchDto branch : branches) {
            InheritedNewCodePeriod inherited = newCodePeriodByBranchUuid.getOrDefault(branch.getUuid(), projectDefault);
            String effectiveValue = null;
            // handles specific analysis only
            Long analysisDate = analysisUuidDateMap.get(analysis.get(inherited.getUuid()));
            if (analysisDate != null) {
                effectiveValue = DateUtils.formatDateTime(analysisDate);
            }
            builder.addNewCodePeriods(build(projectKey, branch.getKey(), inherited.getType(), inherited.getValue(), inherited.inherited, effectiveValue));
        }
        writeProtobuf(builder.build(), request, response);
    }
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) BranchDto(org.sonar.db.component.BranchDto) ComponentFinder(org.sonar.server.component.ComponentFinder) NewCodePeriodDao(org.sonar.db.newcodeperiod.NewCodePeriodDao) DbSession(org.sonar.db.DbSession) HashSet(java.util.HashSet) Request(org.sonar.api.server.ws.Request) WebService(org.sonar.api.server.ws.WebService) DateUtils(org.sonar.api.utils.DateUtils) Map(java.util.Map) Response(org.sonar.api.server.ws.Response) NewCodePeriodType(org.sonar.db.newcodeperiod.NewCodePeriodType) Nullable(javax.annotation.Nullable) ListWSResponse(org.sonarqube.ws.NewCodePeriods.ListWSResponse) MoreCollectors.toList(org.sonar.core.util.stream.MoreCollectors.toList) BranchType(org.sonar.db.component.BranchType) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) NewCodePeriods(org.sonarqube.ws.NewCodePeriods) DbClient(org.sonar.db.DbClient) NewCodePeriodDto(org.sonar.db.newcodeperiod.NewCodePeriodDto) List(java.util.List) UserRole(org.sonar.api.web.UserRole) ProjectDto(org.sonar.db.project.ProjectDto) UserSession(org.sonar.server.user.UserSession) Comparator(java.util.Comparator) SnapshotDto(org.sonar.db.component.SnapshotDto) ShowWSResponse.newBuilder(org.sonarqube.ws.NewCodePeriods.ShowWSResponse.newBuilder) WsUtils.writeProtobuf(org.sonar.server.ws.WsUtils.writeProtobuf) ListWSResponse(org.sonarqube.ws.NewCodePeriods.ListWSResponse) BranchDto(org.sonar.db.component.BranchDto) NewCodePeriodDto(org.sonar.db.newcodeperiod.NewCodePeriodDto) DbSession(org.sonar.db.DbSession)

Example 69 with BranchDto

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

the class ShowAction method handle.

@Override
public void handle(Request request, Response response) throws Exception {
    String projectKey = request.getParam(PARAM_PROJECT).emptyAsNull().or(() -> null);
    String branchKey = request.getParam(PARAM_BRANCH).emptyAsNull().or(() -> null);
    if (projectKey == null && branchKey != null) {
        throw new IllegalArgumentException("If branch key is specified, project key needs to be specified too");
    }
    try (DbSession dbSession = dbClient.openSession(false)) {
        ProjectDto project = null;
        BranchDto branch = null;
        boolean inherited = false;
        if (projectKey != null) {
            try {
                project = getProject(dbSession, projectKey);
                checkPermission(project);
                if (branchKey != null) {
                    try {
                        branch = getBranch(dbSession, project, branchKey);
                    } catch (NotFoundException e) {
                        inherited = true;
                    }
                }
            } catch (NotFoundException e) {
                inherited = true;
            }
        }
        ShowWSResponse.Builder builder = get(dbSession, project, branch, inherited);
        if (project != null) {
            builder.setProjectKey(project.getKey());
        }
        if (branch != null) {
            builder.setBranchKey(branch.getKey());
        }
        writeProtobuf(builder.build(), request, response);
    }
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) DbSession(org.sonar.db.DbSession) BranchDto(org.sonar.db.component.BranchDto) ShowWSResponse(org.sonarqube.ws.NewCodePeriods.ShowWSResponse) NotFoundException(org.sonar.server.exceptions.NotFoundException)

Example 70 with BranchDto

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

the class ExportBranchesStep method execute.

@Override
public void execute(Context context) {
    long count = 0L;
    try {
        try (DbSession dbSession = dbClient.openSession(false);
            StreamWriter<ProjectDump.Branch> output = dumpWriter.newStreamWriter(DumpElement.BRANCHES)) {
            ProjectDump.Branch.Builder builder = ProjectDump.Branch.newBuilder();
            List<BranchDto> branches = dbSession.getMapper(ProjectExportMapper.class).selectBranchesForExport(projectHolder.projectDto().getUuid());
            for (BranchDto branch : branches) {
                builder.clear().setUuid(branch.getUuid()).setProjectUuid(branch.getProjectUuid()).setKee(branch.getKey()).setBranchType(branch.getBranchType().name()).setMergeBranchUuid(defaultString(branch.getMergeBranchUuid()));
                output.write(builder.build());
                ++count;
            }
            Loggers.get(getClass()).debug("{} branches exported", count);
        }
    } catch (Exception e) {
        throw new IllegalStateException(format("Branch export failed after processing %d branch(es) successfully", count), e);
    }
}
Also used : DbSession(org.sonar.db.DbSession) BranchDto(org.sonar.db.component.BranchDto) ProjectExportMapper(org.sonar.db.project.ProjectExportMapper)

Aggregations

BranchDto (org.sonar.db.component.BranchDto)111 Test (org.junit.Test)62 ComponentDto (org.sonar.db.component.ComponentDto)52 ProjectDto (org.sonar.db.project.ProjectDto)42 DbSession (org.sonar.db.DbSession)31 SnapshotDto (org.sonar.db.component.SnapshotDto)22 List (java.util.List)15 ComponentTesting.newBranchDto (org.sonar.db.component.ComponentTesting.newBranchDto)13 DbClient (org.sonar.db.DbClient)12 MetricDto (org.sonar.db.metric.MetricDto)12 Map (java.util.Map)9 Optional (java.util.Optional)9 Nullable (javax.annotation.Nullable)9 WebService (org.sonar.api.server.ws.WebService)9 System2 (org.sonar.api.utils.System2)9 NotFoundException (org.sonar.server.exceptions.NotFoundException)9 Collection (java.util.Collection)8 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)8 Rule (org.junit.Rule)8 Request (org.sonar.api.server.ws.Request)8