Esempio n. 1
0
  private void appendComponent(
      JsonWriter json, ComponentDto component, UserSession userSession, DbSession session) {
    List<PropertyDto> propertyDtos =
        dbClient
            .propertiesDao()
            .selectByQuery(
                PropertyQuery.builder()
                    .setKey("favourite")
                    .setComponentId(component.getId())
                    .setUserId(userSession.getUserId())
                    .build(),
                session);
    boolean isFavourite = propertyDtos.size() == 1;

    json.prop("key", component.key());
    json.prop("uuid", component.uuid());
    json.prop("path", component.path());
    json.prop("name", component.name());
    json.prop("longName", component.longName());
    json.prop("q", component.qualifier());

    ComponentDto parentProject = retrieveRootIfNotCurrentComponent(component, session);
    ComponentDto project =
        dbClient.componentDao().selectOrFailByUuid(session, component.projectUuid());

    // Do not display parent project if parent project and project are the same
    boolean displayParentProject =
        parentProject != null && !parentProject.uuid().equals(project.uuid());
    json.prop("subProject", displayParentProject ? parentProject.key() : null);
    json.prop("subProjectName", displayParentProject ? parentProject.longName() : null);
    json.prop("project", project.key());
    json.prop("projectName", project.longName());

    json.prop("fav", isFavourite);
  }
  @Test
  public void change_project_association_with_key_and_uuid() throws Exception {
    ComponentDto project = ComponentTesting.newProjectDto("ABCD").setId(1L);
    db.componentDao().insert(session, project);
    QualityProfileDto profile1 = QProfileTesting.newXooP1();
    QualityProfileDto profile2 = QProfileTesting.newXooP2();
    db.qualityProfileDao().insert(session, profile1, profile2);
    db.qualityProfileDao()
        .insertProjectProfileAssociation(project.uuid(), profile1.getKey(), session);

    session.commit();

    wsTester
        .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
        .setParam("profileKey", profile2.getKee())
        .setParam("projectUuid", project.uuid())
        .execute()
        .assertNoContent();
    assertThat(
            tester
                .get(QProfileFactory.class)
                .getByProjectAndLanguage(session, project.getKey(), "xoo")
                .getKee())
        .isEqualTo(profile2.getKee());
  }
Esempio n. 3
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    if (settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE)) {
      userSession.checkLoggedIn();
    } else {
      userSession.checkIsRoot();
    }

    String name = wsSupport.getAndCheckMandatoryName(request);
    String requestKey = getAndCheckKey(request);
    String key = useOrGenerateKey(requestKey, name);
    wsSupport.getAndCheckDescription(request);
    wsSupport.getAndCheckUrl(request);
    wsSupport.getAndCheckAvatar(request);

    try (DbSession dbSession = dbClient.openSession(false)) {
      checkKeyIsNotUsed(dbSession, key, requestKey, name);

      OrganizationDto dto = createOrganizationDto(request, name, key);
      dbClient.organizationDao().insert(dbSession, dto);
      GroupDto group = createOwnersGroup(dbSession, dto);
      addCurrentUserToGroup(dbSession, group);
      dbSession.commit();

      writeResponse(request, response, dto);
    }
  }
  @Test
  public void bulk_activate_rule_not_all() throws Exception {
    QualityProfileDto java = createProfile("java");
    QualityProfileDto php = createProfile("php");
    createRule(java.getLanguage(), "toto");
    createRule(java.getLanguage(), "tata");
    createRule(php.getLanguage(), "hello");
    createRule(php.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, php.getKey());
    request.setParam(PARAM_LANGUAGES, "php");
    request.execute().assertJson(getClass(), "bulk_activate_rule_not_all.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).hasSize(2);
  }
Esempio n. 5
0
  @Test
  public void count_users_with_one_permission_when_the_last_one_is_in_a_group() {
    DbClient dbClient = db.getDbClient();

    UserDto user = dbClient.userDao().insert(db.getSession(), new UserDto().setActive(true));
    GroupDto group = dbClient.groupDao().insert(db.getSession(), new GroupDto());
    dbClient
        .userGroupDao()
        .insert(
            db.getSession(), new UserGroupDto().setGroupId(group.getId()).setUserId(user.getId()));
    dbClient
        .roleDao()
        .insertGroupRole(
            db.getSession(),
            new GroupRoleDto().setGroupId(group.getId()).setRole(GlobalPermissions.SYSTEM_ADMIN));

    int resultWithoutExcludingGroup =
        underTest.countUserPermissions(db.getSession(), GlobalPermissions.SYSTEM_ADMIN, null);
    int resultWithGroupExclusion =
        underTest.countUserPermissions(
            db.getSession(), GlobalPermissions.SYSTEM_ADMIN, group.getId());

    assertThat(resultWithoutExcludingGroup).isEqualTo(1);
    assertThat(resultWithGroupExclusion).isEqualTo(0);
  }
  @Test
  public void activate_rule_override_severity() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule = createRule(profile.getLanguage(), "toto");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(RuleActivationActions.RULE_KEY, rule.getKey().toString());
    request.setParam(RuleActivationActions.SEVERITY, "MINOR");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile.getKey(), rule.getKey());

    assertThat(db.activeRuleDao().selectOrFailByKey(session, activeRuleKey).getSeverityString())
        .isEqualTo("MINOR");
  }
Esempio n. 7
0
  @Test
  public void returns_full_object_in_response() throws Exception {
    MetricDto metric =
        MetricTesting.newMetricDto()
            .setEnabled(true)
            .setValueType(ValueType.STRING.name())
            .setKey("metric-key");
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid").setKey("project-key");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setCreatedAt(100_000_000L)
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    WsTester.Result response =
        ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
            .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
            .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
            .setParam(PARAM_VALUE, "new-text-measure-value")
            .execute();

    response.assertJson(getClass(), "custom-measure.json");
    String responseAsString = response.outputAsString();
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", customMeasure.getId()));
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", metric.getId()));
    assertThat(responseAsString).matches(".*createdAt.*updatedAt.*");
  }
Esempio n. 8
0
  @Test
  public void search_groups_with_project_permissions() {
    dbClient.componentDao().insert(dbSession, newProjectDto("project-uuid").setKey("project-key"));
    ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, "project-uuid");
    GroupDto group = insertGroup(new GroupDto().setName("project-group-name"));
    insertGroupRole(
        new GroupRoleDto()
            .setGroupId(group.getId())
            .setRole(ISSUE_ADMIN)
            .setResourceId(project.getId()));
    userSession.login().addProjectUuidPermissions(UserRole.ADMIN, "project-uuid");

    String result =
        ws.newRequest()
            .setParam(PARAM_PERMISSION, ISSUE_ADMIN)
            .setParam(PARAM_PROJECT_ID, "project-uuid")
            .execute()
            .getInput();

    assertThat(result)
        .contains("project-group-name")
        .doesNotContain("group-1")
        .doesNotContain("group-2")
        .doesNotContain("group-3");
  }
  @Test
  public void bulk_deactivate_rule_by_profile() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule0 = createRule(profile.getLanguage(), "hello");
    RuleDto rule1 = createRule(profile.getLanguage(), "world");
    createActiveRule(rule0, profile);
    createActiveRule(rule1, profile);
    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(2);

    // 1. Deactivate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_DEACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(WebService.Param.TEXT_QUERY, "hello");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(1);
  }
Esempio n. 10
0
  @Override
  public void handle(Request wsRequest, Response wsResponse) throws Exception {
    userSession.checkAnyGlobalPermissions(AUTHORIZED_PERMISSIONS);

    String taskUuid = wsRequest.mandatoryParam(PARAM_TASK_UUID);
    DbSession dbSession = dbClient.openSession(false);
    try {
      WsCe.TaskResponse.Builder wsTaskResponse = WsCe.TaskResponse.newBuilder();
      Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskUuid);
      if (queueDto.isPresent()) {
        wsTaskResponse.setTask(wsTaskFormatter.formatQueue(dbSession, queueDto.get()));
      } else {
        Optional<CeActivityDto> activityDto =
            dbClient.ceActivityDao().selectByUuid(dbSession, taskUuid);
        if (activityDto.isPresent()) {
          wsTaskResponse.setTask(wsTaskFormatter.formatActivity(dbSession, activityDto.get()));
        } else {
          throw new NotFoundException();
        }
      }
      writeProtobuf(wsTaskResponse.build(), wsRequest, wsResponse);

    } finally {
      dbClient.closeSession(dbSession);
    }
  }
Esempio n. 11
0
  @Test
  public void update_description_only() throws Exception {
    MetricDto metric = insertNewMetric(ValueType.STRING);
    ComponentDto component = insertNewProject("project-uuid");
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_VALUE, "new-text-measure-value")
        .execute();

    CustomMeasureDto updatedCustomMeasure =
        dbClient.customMeasureDao().selectOrFail(dbSession, customMeasure.getId());
    assertThat(updatedCustomMeasure.getTextValue()).isEqualTo("new-text-measure-value");
    assertThat(updatedCustomMeasure.getDescription()).isEqualTo("custom-measure-description");
    assertThat(updatedCustomMeasure.getUpdatedAt()).isEqualTo(123_456_789L);
    assertThat(customMeasure.getCreatedAt()).isEqualTo(updatedCustomMeasure.getCreatedAt());
  }
Esempio n. 12
0
  @Test
  public void count_users_with_one_specific_permission() {
    DbClient dbClient = db.getDbClient();
    UserDto user = dbClient.userDao().insert(db.getSession(), new UserDto().setActive(true));
    dbClient
        .roleDao()
        .insertUserRole(
            db.getSession(),
            new UserRoleDto()
                .setUserId(user.getId())
                .setResourceId(123L)
                .setRole(GlobalPermissions.SYSTEM_ADMIN));
    dbClient
        .roleDao()
        .insertUserRole(
            db.getSession(),
            new UserRoleDto().setUserId(user.getId()).setRole(GlobalPermissions.SYSTEM_ADMIN));
    dbClient
        .roleDao()
        .insertUserRole(
            db.getSession(),
            new UserRoleDto().setUserId(user.getId()).setRole(GlobalPermissions.SCAN_EXECUTION));

    int result =
        underTest.countUserPermissions(db.getSession(), GlobalPermissions.SYSTEM_ADMIN, null);

    assertThat(result).isEqualTo(1);
  }
Esempio n. 13
0
  @Test
  public void fail_if_not_logged_in() throws Exception {
    userSessionRule.anonymous();
    expectedException.expect(UnauthorizedException.class);
    MetricDto metric =
        MetricTesting.newMetricDto().setEnabled(true).setValueType(ValueType.STRING.name());
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasureDto()
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
        .setParam(PARAM_VALUE, "1984")
        .execute();
  }
  @Test
  public void reset() throws Exception {
    QualityProfileDto profile = QProfileTesting.newXooP1();
    QualityProfileDto subProfile =
        QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY);
    db.qualityProfileDao().insert(session, profile, subProfile);

    RuleDto rule = createRule(profile.getLanguage(), "rule");
    ActiveRuleDto active1 =
        ActiveRuleDto.createFor(profile, rule).setSeverity(rule.getSeverityString());
    ActiveRuleDto active2 = ActiveRuleDto.createFor(subProfile, rule).setSeverity("MINOR");
    db.activeRuleDao().insert(session, active1);
    db.activeRuleDao().insert(session, active2);

    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. assert rule child rule is minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isEqualTo("MINOR");

    // 1. reset child rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam("profile_key", subProfile.getKey());
    request.setParam("rule_key", rule.getKey().toString());
    request.setParam("reset", "true");
    request.execute();
    session.clearCache();

    // 2. assert rule child rule is NOT minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isNotEqualTo("MINOR");
  }
  @Test
  public void set_variation() {
    // Project
    SnapshotDto period1ProjectSnapshot = createForProject(PROJECT_DTO);
    dbClient.snapshotDao().insert(session, period1ProjectSnapshot);
    dbClient
        .measureDao()
        .insert(
            session,
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period1ProjectSnapshot.getId(), 60d));

    // Directory
    ComponentDto directoryDto = ComponentTesting.newDirectory(PROJECT_DTO, "dir");
    dbClient.componentDao().insert(session, directoryDto);
    SnapshotDto period1DirectorySnapshot = createForComponent(directoryDto, period1ProjectSnapshot);
    dbClient.snapshotDao().insert(session, period1DirectorySnapshot);
    dbClient
        .measureDao()
        .insert(
            session,
            newMeasureDto(
                ISSUES_METRIC.getId(),
                directoryDto.getId(),
                period1DirectorySnapshot.getId(),
                10d));
    session.commit();

    periodsHolder.setPeriods(newPeriod(1, period1ProjectSnapshot));

    Component directory =
        ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid(directoryDto.uuid()).build();
    Component project =
        ReportComponent.builder(Component.Type.PROJECT, 1)
            .setUuid(PROJECT_DTO.uuid())
            .addChildren(directory)
            .build();
    treeRootHolder.setRoot(project);

    addRawMeasure(project, ISSUES_METRIC, Measure.newMeasureBuilder().create(80, null));
    addRawMeasure(directory, ISSUES_METRIC, Measure.newMeasureBuilder().create(20, null));

    underTest.execute();

    assertThat(
            measureRepository
                .getRawMeasure(project, ISSUES_METRIC)
                .get()
                .getVariations()
                .getVariation1())
        .isEqualTo(20d);
    assertThat(
            measureRepository
                .getRawMeasure(directory, ISSUES_METRIC)
                .get()
                .getVariations()
                .getVariation1())
        .isEqualTo(10d);
  }
Esempio n. 16
0
 private List<RuleDto> loadDtos(List<RuleKey> ruleKeys) {
   DbSession dbSession = dbClient.openSession(false);
   try {
     return dbClient.ruleDao().selectByKeys(dbSession, ruleKeys);
   } finally {
     dbClient.closeSession(dbSession);
   }
 }
Esempio n. 17
0
 /** Used in issues_controller.rb and in manual_rules_controller.rb and in SQALE */
 @CheckForNull
 public RuleDto findByKey(String ruleKey) {
   DbSession dbSession = dbClient.openSession(false);
   try {
     return dbClient.ruleDao().selectByKey(dbSession, RuleKey.parse(ruleKey)).orNull();
   } finally {
     dbClient.closeSession(dbSession);
   }
 }
  @Test
  public void set_variations_on_all_periods() {
    SnapshotDto period1ProjectSnapshot = createForProject(PROJECT_DTO).setLast(false);
    SnapshotDto period2ProjectSnapshot = createForProject(PROJECT_DTO).setLast(false);
    SnapshotDto period3ProjectSnapshot = createForProject(PROJECT_DTO).setLast(false);
    SnapshotDto period4ProjectSnapshot = createForProject(PROJECT_DTO).setLast(false);
    SnapshotDto period5ProjectSnapshot = createForProject(PROJECT_DTO).setLast(false);
    dbClient
        .snapshotDao()
        .insert(
            session,
            period1ProjectSnapshot,
            period2ProjectSnapshot,
            period3ProjectSnapshot,
            period4ProjectSnapshot,
            period5ProjectSnapshot);

    dbClient
        .measureDao()
        .insert(
            session,
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period1ProjectSnapshot.getId(), 0d),
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period2ProjectSnapshot.getId(), 20d),
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period3ProjectSnapshot.getId(), 40d),
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period4ProjectSnapshot.getId(), 80d),
            newMeasureDto(
                ISSUES_METRIC.getId(), PROJECT_DTO.getId(), period5ProjectSnapshot.getId(), 100d));
    session.commit();

    periodsHolder.setPeriods(
        newPeriod(1, period1ProjectSnapshot),
        newPeriod(2, period2ProjectSnapshot),
        newPeriod(3, period3ProjectSnapshot),
        newPeriod(4, period4ProjectSnapshot),
        newPeriod(5, period5ProjectSnapshot));

    treeRootHolder.setRoot(PROJECT);

    addRawMeasure(PROJECT, ISSUES_METRIC, Measure.newMeasureBuilder().create(80, null));

    underTest.execute();

    assertThat(measureRepository.getRawMeasures(PROJECT).keys()).hasSize(1);

    Measure measure = measureRepository.getRawMeasure(PROJECT, ISSUES_METRIC).get();
    assertThat(measure.hasVariations()).isTrue();
    assertThat(measure.getVariations().getVariation1()).isEqualTo(80d);
    assertThat(measure.getVariations().getVariation2()).isEqualTo(60d);
    assertThat(measure.getVariations().getVariation3()).isEqualTo(40d);
    assertThat(measure.getVariations().getVariation4()).isEqualTo(0d);
    assertThat(measure.getVariations().getVariation5()).isEqualTo(-20d);
  }
 @Override
 public Collection<Metric> findAll() {
   DbSession session = dbClient.openSession(false);
   try {
     List<MetricDto> dtos = dbClient.metricDao().selectEnabled(session);
     return from(dtos).transform(ToMetric.INSTANCE).toList();
   } finally {
     MyBatis.closeQuietly(session);
   }
 }
Esempio n. 20
0
 /** Uuids of all the components that have open issues on this project. */
 public Set<String> loadUuidsOfComponentsWithOpenIssues() {
   DbSession session = dbClient.openSession(false);
   try {
     return dbClient
         .issueDao()
         .selectComponentUuidsOfOpenIssuesForProjectUuid(
             session, treeRootHolder.getRoot().getUuid());
   } finally {
     MyBatis.closeQuietly(session);
   }
 }
  @Before
  public void setUp() {
    userSessionRule.login("admin").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);

    DbClient dbClient = mock(DbClient.class);
    when(dbClient.openSession(false)).thenReturn(session);
    when(dbClient.permissionTemplateDao()).thenReturn(permissionTemplateDao);
    when(dbClient.userDao()).thenReturn(userDao);
    when(dbClient.groupDao()).thenReturn(groupDao);
    underTest = new PermissionTemplateService(dbClient, userSessionRule, finder);
  }
  private List<ComponentDto> searchProjects(
      DbSession dbSession, @Nullable List<String> uuids, @Nullable List<String> keys) {
    if (uuids != null) {
      return dbClient.componentDao().selectByUuids(dbSession, uuids);
    }
    if (keys != null) {
      return dbClient.componentDao().selectByKeys(dbSession, keys);
    }

    throw new IllegalArgumentException("ids or keys must be provided");
  }
Esempio n. 23
0
 @Override
 public void execute() {
   DbSession session = dbClient.openSession(false);
   try {
     Map<String, ComponentDto> existingComponentDtosByKey = indexExistingDtosByKey(session);
     new PathAwareCrawler<>(new PersistComponentStepsVisitor(existingComponentDtosByKey, session))
         .visit(treeRootHolder.getRoot());
     session.commit();
   } finally {
     dbClient.closeSession(session);
   }
 }
  @Test
  public void return_undefined_status_if_measure_is_not_found() {
    ComponentDto project = newProjectDto("project-uuid");
    dbClient.componentDao().insert(dbSession, project);
    SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newSnapshotForProject(project));
    dbSession.commit();

    ProjectStatusWsResponse result = newRequest(snapshot.getId().toString());

    assertThat(result.getProjectStatus().getStatus()).isEqualTo(Status.NONE);
    assertThat(result.getProjectStatus().getConditionsCount()).isEqualTo(0);
  }
  @Before
  public void setUp() {
    DbClient dbClient = mock(DbClient.class);
    when(dbClient.openSession(false)).thenReturn(session);
    when(dbClient.metricDao()).thenReturn(metricDao);

    tester =
        new WsTester(
            new BatchWs(
                mock(BatchIndex.class),
                new GlobalAction(dbClient, propertiesDao, userSessionRule)));
  }
Esempio n. 26
0
 private Map<String, MeasureDto> measuresByMetricKey(ComponentDto component, DbSession session) {
   MeasureQuery query =
       MeasureQuery.builder()
           .setComponentUuid(component.uuid())
           .setMetricKeys(METRIC_KEYS)
           .build();
   List<MeasureDto> measures = dbClient.measureDao().selectByQuery(session, query);
   Set<Integer> metricIds =
       measures.stream().map(MeasureDto::getMetricId).collect(Collectors.toSet());
   List<MetricDto> metrics = dbClient.metricDao().selectByIds(session, metricIds);
   Map<Integer, MetricDto> metricsById = Maps.uniqueIndex(metrics, MetricDto::getId);
   return Maps.uniqueIndex(measures, m -> metricsById.get(m.getMetricId()).getKey());
 }
Esempio n. 27
0
  @Test
  public void should_fail_on_unmatched_template() {
    dbTester.truncateTables();

    throwable.expect(IllegalArgumentException.class);

    PermissionTemplateDao permissionTemplateDao = mock(PermissionTemplateDao.class);

    DbClient dbClient = mock(DbClient.class);
    when(dbClient.permissionTemplateDao()).thenReturn(permissionTemplateDao);
    permissionFacade = new PermissionFacade(dbClient, null);
    permissionFacade.getPermissionTemplateWithPermissions(dbTester.getSession(), "unmatched");
  }
 @Override
 public Metric findByKey(String key) {
   DbSession session = dbClient.openSession(false);
   try {
     MetricDto dto = dbClient.metricDao().selectByKey(session, key);
     if (dto != null && dto.isEnabled()) {
       return ToMetric.INSTANCE.apply(dto);
     }
     return null;
   } finally {
     MyBatis.closeQuietly(session);
   }
 }
  @Override
  public void handle(Request wsRequest, Response wsResponse) throws Exception {
    checkRequestAndPermissions(wsRequest);

    DbSession dbSession = dbClient.openSession(false);
    try {
      SearchProjectPermissionsData data = dataLoader.load(wsRequest);
      SearchProjectPermissionsResponse response = buildReponse(data);
      writeProtobuf(response, wsRequest, wsResponse);
    } finally {
      dbClient.closeSession(dbSession);
    }
  }
  ComponentTreeData load(ComponentTreeWsRequest wsRequest) {
    DbSession dbSession = dbClient.openSession(false);
    try {
      ComponentDto baseComponent =
          componentFinder.getByUuidOrKey(
              dbSession,
              wsRequest.getBaseComponentId(),
              wsRequest.getBaseComponentKey(),
              BASE_COMPONENT_ID_AND_KEY);
      checkPermissions(baseComponent);
      java.util.Optional<SnapshotDto> baseSnapshot =
          dbClient
              .snapshotDao()
              .selectLastAnalysisByRootComponentUuid(dbSession, baseComponent.projectUuid());
      if (!baseSnapshot.isPresent()) {
        return ComponentTreeData.builder().setBaseComponent(baseComponent).build();
      }
      Long developerId = searchDeveloperId(dbSession, wsRequest);

      ComponentTreeQuery dbQuery = toComponentTreeQuery(wsRequest, baseComponent);
      ComponentDtosAndTotal componentDtosAndTotal = searchComponents(dbSession, dbQuery, wsRequest);
      List<ComponentDto> components = componentDtosAndTotal.componentDtos;
      List<MetricDto> metrics = searchMetrics(dbSession, wsRequest);
      List<WsMeasures.Period> periods = snapshotToWsPeriods(baseSnapshot.get());
      Table<String, MetricDto, MeasureDto> measuresByComponentUuidAndMetric =
          searchMeasuresByComponentUuidAndMetric(
              dbSession, baseComponent, components, metrics, periods, developerId);

      components =
          filterComponents(components, measuresByComponentUuidAndMetric, metrics, wsRequest);
      components = sortComponents(components, wsRequest, metrics, measuresByComponentUuidAndMetric);
      int componentCount =
          computeComponentCount(
              componentDtosAndTotal.total, components, componentWithMeasuresOnly(wsRequest));
      components = paginateComponents(components, wsRequest);
      Map<String, ComponentDto> referenceComponentsById =
          searchReferenceComponentsById(dbSession, components);

      return ComponentTreeData.builder()
          .setBaseComponent(baseComponent)
          .setComponentsFromDb(components)
          .setComponentCount(componentCount)
          .setMeasuresByComponentUuidAndMetric(measuresByComponentUuidAndMetric)
          .setMetrics(metrics)
          .setPeriods(periods)
          .setReferenceComponentsByUuid(referenceComponentsById)
          .build();
    } finally {
      dbClient.closeSession(dbSession);
    }
  }