Search in sources :

Example 6 with LiveMeasureDto

use of org.sonar.db.measure.LiveMeasureDto in project sonarqube by SonarSource.

the class MeasureAction method handle.

@Override
public void handle(Request request, Response response) throws Exception {
    response.setHeader("Cache-Control", "no-cache");
    response.stream().setMediaType(SVG);
    String metricKey = request.mandatoryParam(PARAM_METRIC);
    try (DbSession dbSession = dbClient.openSession(false)) {
        support.validateToken(request);
        BranchDto branch = support.getBranch(dbSession, request);
        MetricDto metric = dbClient.metricDao().selectByKey(dbSession, metricKey);
        checkState(metric != null && metric.isEnabled(), "Metric '%s' hasn't been found", metricKey);
        LiveMeasureDto measure = getMeasure(dbSession, branch, metricKey);
        String result = generateSvg(metric, measure);
        String eTag = getETag(result);
        Optional<String> requestedETag = request.header("If-None-Match");
        if (requestedETag.filter(eTag::equals).isPresent()) {
            response.stream().setStatus(304);
            return;
        }
        response.setHeader("ETag", eTag);
        write(result, response.stream().output(), UTF_8);
    } catch (ProjectBadgesException | ForbiddenException | NotFoundException e) {
        // There is an issue, so do not return any ETag but make this response expire now
        SimpleDateFormat sdf = new SimpleDateFormat(RFC1123_DATE, Locale.US);
        response.setHeader("Expires", sdf.format(new Date()));
        write(svgGenerator.generateError(e.getMessage()), response.stream().output(), UTF_8);
    }
}
Also used : DbSession(org.sonar.db.DbSession) BranchDto(org.sonar.db.component.BranchDto) MetricDto(org.sonar.db.metric.MetricDto) ForbiddenException(org.sonar.server.exceptions.ForbiddenException) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 7 with LiveMeasureDto

use of org.sonar.db.measure.LiveMeasureDto in project sonarqube by SonarSource.

the class PurgeDaoTest method close_issues_clean_index_and_file_sources_of_disabled_components_specified_by_uuid_in_configuration.

@Test
public void close_issues_clean_index_and_file_sources_of_disabled_components_specified_by_uuid_in_configuration() {
    RuleDefinitionDto rule = db.rules().insert();
    ComponentDto project = db.components().insertPublicProject();
    db.components().insertSnapshot(project);
    db.components().insertSnapshot(project);
    db.components().insertSnapshot(project, s -> s.setLast(false));
    ComponentDto module = db.components().insertComponent(newModuleDto(project).setEnabled(false));
    ComponentDto dir = db.components().insertComponent(newDirectory(module, "sub").setEnabled(false));
    ComponentDto srcFile = db.components().insertComponent(newFileDto(module, dir).setEnabled(false));
    ComponentDto testFile = db.components().insertComponent(newFileDto(module, dir).setEnabled(false));
    ComponentDto enabledFile = db.components().insertComponent(newFileDto(module, dir).setEnabled(true));
    IssueDto openOnFile = db.issues().insert(rule, project, srcFile, issue -> issue.setStatus("OPEN"));
    IssueDto confirmOnFile = db.issues().insert(rule, project, srcFile, issue -> issue.setStatus("CONFIRM"));
    IssueDto openOnDir = db.issues().insert(rule, project, dir, issue -> issue.setStatus("OPEN"));
    IssueDto confirmOnDir = db.issues().insert(rule, project, dir, issue -> issue.setStatus("CONFIRM"));
    IssueDto openOnEnabledComponent = db.issues().insert(rule, project, enabledFile, issue -> issue.setStatus("OPEN"));
    IssueDto confirmOnEnabledComponent = db.issues().insert(rule, project, enabledFile, issue -> issue.setStatus("CONFIRM"));
    assertThat(db.countSql("select count(*) from snapshots where purge_status = 1")).isZero();
    assertThat(db.countSql("select count(*) from issues where status = 'CLOSED'")).isZero();
    assertThat(db.countSql("select count(*) from issues where resolution = 'REMOVED'")).isZero();
    db.fileSources().insertFileSource(srcFile);
    FileSourceDto nonSelectedFileSource = db.fileSources().insertFileSource(enabledFile);
    assertThat(db.countRowsOfTable("file_sources")).isEqualTo(2);
    MetricDto metric1 = db.measures().insertMetric();
    MetricDto metric2 = db.measures().insertMetric();
    LiveMeasureDto liveMeasureMetric1OnFile = db.measures().insertLiveMeasure(srcFile, metric1);
    LiveMeasureDto liveMeasureMetric2OnFile = db.measures().insertLiveMeasure(srcFile, metric2);
    LiveMeasureDto liveMeasureMetric1OnDir = db.measures().insertLiveMeasure(dir, metric1);
    LiveMeasureDto liveMeasureMetric2OnDir = db.measures().insertLiveMeasure(dir, metric2);
    LiveMeasureDto liveMeasureMetric1OnProject = db.measures().insertLiveMeasure(project, metric1);
    LiveMeasureDto liveMeasureMetric2OnProject = db.measures().insertLiveMeasure(project, metric2);
    LiveMeasureDto liveMeasureMetric1OnNonSelected = db.measures().insertLiveMeasure(enabledFile, metric1);
    LiveMeasureDto liveMeasureMetric2OnNonSelected = db.measures().insertLiveMeasure(enabledFile, metric2);
    assertThat(db.countRowsOfTable("live_measures")).isEqualTo(8);
    PurgeListener purgeListener = mock(PurgeListener.class);
    // back to present
    Set<String> selectedComponentUuids = ImmutableSet.of(module.uuid(), srcFile.uuid(), testFile.uuid());
    underTest.purge(dbSession, newConfigurationWith30Days(system2, project.uuid(), project.uuid(), selectedComponentUuids), purgeListener, new PurgeProfiler());
    dbSession.commit();
    verify(purgeListener).onComponentsDisabling(project.uuid(), selectedComponentUuids);
    verify(purgeListener).onComponentsDisabling(project.uuid(), ImmutableSet.of(dir.uuid()));
    // set purge_status=1 for non-last snapshot
    assertThat(db.countSql("select count(*) from snapshots where purge_status = 1")).isOne();
    // close open issues of selected
    assertThat(db.countSql("select count(*) from issues where status = 'CLOSED'")).isEqualTo(4);
    for (IssueDto issue : Arrays.asList(openOnFile, confirmOnFile, openOnDir, confirmOnDir)) {
        assertThat(db.getDbClient().issueDao().selectOrFailByKey(dbSession, issue.getKey())).extracting(IssueDto::getStatus, IssueDto::getResolution).containsExactlyInAnyOrder("CLOSED", "REMOVED");
    }
    for (IssueDto issue : Arrays.asList(openOnEnabledComponent, confirmOnEnabledComponent)) {
        assertThat(db.getDbClient().issueDao().selectByKey(dbSession, issue.getKey()).get()).extracting("status", "resolution").containsExactlyInAnyOrder(issue.getStatus(), null);
    }
    // delete file sources of selected
    assertThat(db.countRowsOfTable("file_sources")).isOne();
    assertThat(db.getDbClient().fileSourceDao().selectByFileUuid(dbSession, nonSelectedFileSource.getFileUuid())).isNotNull();
    // deletes live measure of selected
    assertThat(db.countRowsOfTable("live_measures")).isEqualTo(4);
    List<LiveMeasureDto> liveMeasureDtos = db.getDbClient().liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, ImmutableSet.of(srcFile.uuid(), dir.uuid(), project.uuid(), enabledFile.uuid()), ImmutableSet.of(metric1.getUuid(), metric2.getUuid()));
    assertThat(liveMeasureDtos).extracting(LiveMeasureDto::getComponentUuid).containsOnly(enabledFile.uuid(), project.uuid());
    assertThat(liveMeasureDtos).extracting(LiveMeasureDto::getMetricUuid).containsOnly(metric1.getUuid(), metric2.getUuid());
}
Also used : MetricDto(org.sonar.db.metric.MetricDto) FileSourceDto(org.sonar.db.source.FileSourceDto) ComponentDto(org.sonar.db.component.ComponentDto) RuleDefinitionDto(org.sonar.db.rule.RuleDefinitionDto) IssueDto(org.sonar.db.issue.IssueDto) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) Test(org.junit.Test)

Example 8 with LiveMeasureDto

use of org.sonar.db.measure.LiveMeasureDto 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)

Example 9 with LiveMeasureDto

use of org.sonar.db.measure.LiveMeasureDto in project sonarqube by SonarSource.

the class QualityGateActionTest method etag_should_be_different_if_quality_gate_is_different.

@Test
public void etag_should_be_different_if_quality_gate_is_different() {
    ComponentDto project = db.components().insertPublicProject();
    userSession.registerComponents(project);
    MetricDto metric = createQualityGateMetric();
    LiveMeasureDto liveMeasure = db.measures().insertLiveMeasure(project, metric, m -> m.setData(OK.name()));
    TestResponse response = ws.newRequest().setParam("project", project.getKey()).execute();
    String eTagOK = response.getHeader("ETag");
    liveMeasure.setData(ERROR.name());
    db.getDbClient().liveMeasureDao().insertOrUpdate(db.getSession(), liveMeasure);
    db.commit();
    response = ws.newRequest().setParam("project", project.getKey()).execute();
    String eTagERROR = response.getHeader("ETag");
    assertThat(Arrays.asList(eTagOK, eTagERROR)).doesNotContainNull().doesNotHaveDuplicates();
}
Also used : MetricDto(org.sonar.db.metric.MetricDto) TestResponse(org.sonar.server.ws.TestResponse) ComponentDto(org.sonar.db.component.ComponentDto) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) Test(org.junit.Test)

Example 10 with LiveMeasureDto

use of org.sonar.db.measure.LiveMeasureDto in project sonarqube by SonarSource.

the class ComponentTreeSortTest method sort_by_alert_status_ascending.

@Test
public void sort_by_alert_status_ascending() {
    components = newArrayList(newComponentWithoutSnapshotId("PROJECT OK 1", Qualifiers.PROJECT, "PROJECT_OK_PATH_1"), newComponentWithoutSnapshotId("PROJECT ERROR 1", Qualifiers.PROJECT, "PROJECT_ERROR_PATH_1"), newComponentWithoutSnapshotId("PROJECT OK 2", Qualifiers.PROJECT, "PROJECT_OK_PATH_2"), newComponentWithoutSnapshotId("PROJECT ERROR 2", Qualifiers.PROJECT, "PROJECT_ERROR_PATH_2"));
    metrics = singletonList(newMetricDto().setKey(CoreMetrics.ALERT_STATUS_KEY).setValueType(ValueType.LEVEL.name()));
    measuresByComponentUuidAndMetric = HashBasedTable.create();
    List<String> statuses = newArrayList("OK", "ERROR");
    for (int i = 0; i < components.size(); i++) {
        ComponentDto component = components.get(i);
        String alertStatus = statuses.get(i % 2);
        measuresByComponentUuidAndMetric.put(component.uuid(), metrics.get(0), createFromMeasureDto(new LiveMeasureDto().setData(alertStatus)));
    }
    ComponentTreeRequest wsRequest = newRequest(newArrayList(METRIC_SORT, NAME_SORT), true, CoreMetrics.ALERT_STATUS_KEY);
    List<ComponentDto> result = sortComponents(wsRequest);
    assertThat(result).extracting("name").containsExactly("PROJECT ERROR 1", "PROJECT ERROR 2", "PROJECT OK 1", "PROJECT OK 2");
}
Also used : ComponentDto(org.sonar.db.component.ComponentDto) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) Test(org.junit.Test)

Aggregations

LiveMeasureDto (org.sonar.db.measure.LiveMeasureDto)48 Test (org.junit.Test)29 MetricDto (org.sonar.db.metric.MetricDto)26 ComponentDto (org.sonar.db.component.ComponentDto)15 SnapshotDto (org.sonar.db.component.SnapshotDto)10 MetricTesting.newMetricDto (org.sonar.db.metric.MetricTesting.newMetricDto)9 UserRole (org.sonar.api.web.UserRole)8 DbSession (org.sonar.db.DbSession)8 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 Assertions.tuple (org.assertj.core.api.Assertions.tuple)7 ForbiddenException (org.sonar.server.exceptions.ForbiddenException)7 NotFoundException (org.sonar.server.exceptions.NotFoundException)7 Common (org.sonarqube.ws.Common)7 Double.parseDouble (java.lang.Double.parseDouble)6 String.format (java.lang.String.format)6 Map (java.util.Map)6 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)6 Rule (org.junit.Rule)6 Param (org.sonar.api.server.ws.WebService.Param)6 DbClient (org.sonar.db.DbClient)6