@Test
  public void create_target_profile_with_same_parent_than_source() {
    // two profiles : parent and its child
    db.qualityProfileDao()
        .insert(dbSession, QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY));

    // parent and child with x1 activated
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    activation.setSeverity(Severity.BLOCKER);
    activation.setParameter("max", "7");
    ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
    dbSession.commit();
    dbSession.clearCache();

    // copy child -> profile2 is created with parent P1
    copier.copyToName(QProfileTesting.XOO_P1_KEY, QProfileTesting.XOO_P2_NAME.getName());

    verifyOneActiveRule(
        QProfileTesting.XOO_P2_KEY,
        Severity.BLOCKER,
        ActiveRuleDto.INHERITED,
        ImmutableMap.of("max", "7"));
    QualityProfileDto profile2Dto =
        db.qualityProfileDao().selectByKey(dbSession, QProfileTesting.XOO_P2_KEY);
    assertThat(profile2Dto.getParentKee()).isEqualTo(QProfileTesting.XOO_P1_KEY);
  }
  @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());
  }
  @Test
  public void get_profile_by_project_and_language() {
    ComponentDto project =
        new ComponentDto()
            .setId(1L)
            .setUuid("ABCD")
            .setKey("org.codehaus.sonar:sonar")
            .setName("SonarQube")
            .setLongName("SonarQube")
            .setQualifier("TRK")
            .setScope("TRK")
            .setEnabled(true);
    db.componentDao().insert(dbSession, project);

    QualityProfileDto profileDto = QProfileTesting.newXooP1();
    db.qualityProfileDao().insert(dbSession, profileDto);
    dbSession.commit();
    dbSession.clearCache();
    assertThat(factory.getByProjectAndLanguage("org.codehaus.sonar:sonar", "xoo")).isNull();

    tester
        .get(QProfileProjectOperations.class)
        .addProject(
            profileDto.getKey(),
            project.uuid(),
            new MockUserSession("me").setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN),
            dbSession);
    dbSession.commit();
    dbSession.clearCache();
    assertThat(factory.getByProjectAndLanguage("org.codehaus.sonar:sonar", "xoo").getKey())
        .isEqualTo(XOO_P1_KEY);
  }
  @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");
  }
  @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);
  }
  @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");
  }
 private void verifyOneActiveRule(
     QProfileName profileName,
     String expectedSeverity,
     @Nullable String expectedInheritance,
     Map<String, String> expectedParams) {
   QualityProfileDto dto =
       db.qualityProfileDao()
           .selectByNameAndLanguage(profileName.getName(), profileName.getLanguage(), dbSession);
   verifyOneActiveRule(dto.getKey(), expectedSeverity, expectedInheritance, expectedParams);
 }
  @Test
  public void fail_if_blank_renaming() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    String key = dto.getKey();

    try {
      factory.rename(key, " ");
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("Name must be set");
    }
  }
  @Test
  public void fail_renaming_if_name_already_exists() {
    QualityProfileDto p1 = factory.create(dbSession, new QProfileName("xoo", "P1"));
    QualityProfileDto p2 = factory.create(dbSession, new QProfileName("xoo", "P2"));
    dbSession.commit();
    dbSession.clearCache();

    try {
      factory.rename(p1.getKey(), "P2");
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("Quality profile already exists: P2");
    }
  }
  @Test
  public void bulk_activate_rule_by_query_with_severity() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule0 = createRule(profile.getLanguage(), "toto");
    RuleDto rule1 = createRule(profile.getLanguage(), "tata");
    session.commit();
    ruIndexer.index();

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

    // 2. Assert ActiveRule with BLOCKER severity
    assertThat(
            tester
                .get(RuleIndex.class)
                .search(
                    new RuleQuery().setSeverities(ImmutableSet.of("BLOCKER")), new SearchOptions())
                .getIds())
        .hasSize(2);

    // 1. Activate Rule with query returning 2 hits
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(BulkRuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(BulkRuleActivationActions.SEVERITY, "MINOR");
    request.execute();
    session.commit();

    // 2. Assert ActiveRule with MINOR severity
    assertThat(
            tester
                .get(ActiveRuleDao.class)
                .selectByRuleId(session, rule0.getId())
                .get(0)
                .getSeverityString())
        .isEqualTo("MINOR");
    assertThat(
            tester
                .get(RuleIndex.class)
                .searchAll(
                    new RuleQuery()
                        .setQProfileKey(profile.getKey())
                        .setKey(rule0.getKey().toString())
                        .setActiveSeverities(Collections.singleton("MINOR"))
                        .setActivation(true)))
        .hasSize(1);
  }
 private void createProfiles() {
   qualityProfileDao.insert(
       session,
       QualityProfileDto.createFor("sonar-way-xoo1-12345")
           .setLanguage(xoo1Key)
           .setName("Sonar way")
           .setDefault(true),
       QualityProfileDto.createFor("sonar-way-xoo2-23456")
           .setLanguage(xoo2Key)
           .setName("Sonar way"),
       QualityProfileDto.createFor("my-sonar-way-xoo2-34567")
           .setLanguage(xoo2Key)
           .setName("My Sonar way")
           .setParentKee("sonar-way-xoo2-23456")
           .setDefault(true));
   session.commit();
 }
  @Test
  public void
      does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile()
          throws Exception {
    QualityProfileDto javaProfile = createProfile("java");
    createRule(javaProfile.getLanguage(), "toto");
    createRule(javaProfile.getLanguage(), "tata");
    QualityProfileDto phpProfile = createProfile("php");
    createRule(phpProfile.getLanguage(), "hello");
    createRule(phpProfile.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, javaProfile.getKey());
    request.setParam(PARAM_QPROFILE, javaProfile.getKey());
    request.setParam("activation", "false");
    request
        .execute()
        .assertJson(
            getClass(),
            "does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, javaProfile.getKey())).hasSize(2);
  }
  @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);
  }
 void verifyForActivation() {
   if (RuleStatus.REMOVED == rule.getStatus()) {
     throw new BadRequestException("Rule was removed: " + rule.getKey());
   }
   if (rule.isTemplate()) {
     throw new BadRequestException(
         "Rule template can't be activated on a Quality profile: " + rule.getKey());
   }
   if (rule.getKey().isManual()) {
     throw new BadRequestException(
         "Manual rule can't be activated on a Quality profile: " + rule.getKey());
   }
   if (!profile.getLanguage().equals(rule.getLanguage())) {
     throw new BadRequestException(
         String.format(
             "Rule %s and profile %s have different languages", rule.getKey(), profile.getKey()));
   }
 }
  @Test
  public void create() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    assertThat(dto.getKey()).startsWith("xoo-p1-");
    assertThat(dto.getName()).isEqualTo("P1");
    assertThat(dto.getLanguage()).isEqualTo("xoo");
    assertThat(dto.getId()).isNotNull();

    // reload the dto
    dto = db.qualityProfileDao().selectByNameAndLanguage("P1", "xoo", dbSession);
    assertThat(dto.getLanguage()).isEqualTo("xoo");
    assertThat(dto.getName()).isEqualTo("P1");
    assertThat(dto.getKey()).startsWith("xoo-p1");
    assertThat(dto.getId()).isNotNull();
    assertThat(dto.getParentKee()).isNull();

    assertThat(db.qualityProfileDao().selectAll(dbSession)).hasSize(1);
  }
  @Test
  public void add_project_with_name_language_and_key() throws Exception {
    ComponentDto project = ComponentTesting.newProjectDto("ABCD").setId(1L);
    db.componentDao().insert(session, project);
    QualityProfileDto profile = QProfileTesting.newXooP1();
    db.qualityProfileDao().insert(session, profile);

    session.commit();

    wsTester
        .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
        .setParam("language", "xoo")
        .setParam("profileName", profile.getName())
        .setParam("projectKey", project.getKey())
        .execute()
        .assertNoContent();
    assertThat(
            tester
                .get(QProfileFactory.class)
                .getByProjectAndLanguage(session, project.getKey(), "xoo")
                .getKee())
        .isEqualTo(profile.getKee());
  }
  @Test
  public void deactivate_rule() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule = createRule(profile.getLanguage(), "toto");
    createActiveRule(rule, profile);
    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

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

    // 1. Deactivate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.DEACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(RuleActivationActions.RULE_KEY, rule.getKey().toString());
    request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).isEmpty();
  }
  @Test
  public void activate_rule_diff_languages() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule = createRule("php", "toto");
    session.commit();
    ruIndexer.index();

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

    try {
      // 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.execute();
      session.clearCache();
      fail();
    } catch (BadRequestException e) {
      assertThat(e.getMessage())
          .isEqualTo("Rule blah:toto and profile pjava have different languages");
    }
  }
  @Test
  public void ignore_renaming_if_same_name() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    String key = dto.getKey();

    assertThat(factory.rename(key, "P1")).isFalse();
    dbSession.clearCache();

    QualityProfileDto reloaded = db.qualityProfileDao().selectByKey(dbSession, dto.getKee());
    assertThat(reloaded.getKey()).isEqualTo(key);
    assertThat(reloaded.getName()).isEqualTo("P1");
  }
  @Test
  public void bulk_activate_rule_by_query() throws Exception {
    QualityProfileDto profile = createProfile("java");
    createRule(profile.getLanguage(), "toto");
    createRule(profile.getLanguage(), "tata");
    createRule(profile.getLanguage(), "hello");
    createRule(profile.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

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

    // 1. Activate Rule with query returning 0 hits
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(WebService.Param.TEXT_QUERY, "php");
    request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(0);

    // 1. Activate Rule with query returning 1 hits
    request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(WebService.Param.TEXT_QUERY, "world");
    request.execute();
    session.commit();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(1);
  }
  @Test
  public void update_active_rule_parameters_when_updating_custom_rule() {
    // Create template rule with 3 parameters
    RuleDto templateRule =
        RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo");
    ruleDao.insert(dbSession, templateRule);
    RuleParamDto templateRuleParam1 =
        RuleParamDto.createFor(templateRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue(".*");
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam1);
    RuleParamDto templateRuleParam2 =
        RuleParamDto.createFor(templateRule)
            .setName("format")
            .setType("STRING")
            .setDescription("format")
            .setDefaultValue("csv");
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam2);
    RuleParamDto templateRuleParam3 =
        RuleParamDto.createFor(templateRule)
            .setName("message")
            .setType("STRING")
            .setDescription("message");
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam3);

    // Create custom rule
    RuleDto customRule =
        RuleTesting.newCustomRule(templateRule).setSeverity(Severity.MAJOR).setLanguage("xoo");
    ruleDao.insert(dbSession, customRule);
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam1.setDefaultValue("a.*"));
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam2.setDefaultValue("txt"));
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam3);

    // Create a quality profile
    QualityProfileDto profileDto = QProfileTesting.newXooP1();
    db.qualityProfileDao().insert(dbSession, profileDto);
    dbSession.commit();

    // Activate the custom rule
    RuleActivation activation =
        new RuleActivation(customRule.getKey()).setSeverity(Severity.BLOCKER);
    tester.get(RuleActivator.class).activate(dbSession, activation, QProfileTesting.XOO_P1_NAME);
    dbSession.commit();
    dbSession.clearCache();

    // Update custom rule parameter 'regex', add 'message' and remove 'format'
    RuleUpdate update =
        RuleUpdate.createForCustomRule(customRule.getKey())
            .setParameters(ImmutableMap.of("regex", "b.*", "message", "a message"));
    updater.update(update, userSessionRule);

    dbSession.clearCache();

    // Verify custom rule parameters has been updated
    Rule customRuleReloaded = ruleIndex.getByKey(customRule.getKey());
    assertThat(customRuleReloaded.params()).hasSize(3);
    assertThat(customRuleReloaded.param("regex")).isNotNull();
    assertThat(customRuleReloaded.param("regex").defaultValue()).isEqualTo("b.*");
    assertThat(customRuleReloaded.param("message")).isNotNull();
    assertThat(customRuleReloaded.param("message").defaultValue()).isEqualTo("a message");
    assertThat(customRuleReloaded.param("format")).isNotNull();
    assertThat(customRuleReloaded.param("format").defaultValue()).isNull();

    RuleParam param = customRuleReloaded.params().get(0);
    assertThat(param.defaultValue()).isEqualTo("b.*");

    // Verify active rule parameters has been updated
    ActiveRule activeRule =
        tester
            .get(ActiveRuleIndex.class)
            .getByKey(ActiveRuleKey.of(profileDto.getKey(), customRule.getKey()));
    assertThat(activeRule.params()).hasSize(2);
    assertThat(activeRule.params().get("regex")).isEqualTo("b.*");
    assertThat(activeRule.params().get("message")).isEqualTo("a message");
    assertThat(activeRule.params().get("format")).isNull();

    // Verify that severity has not changed
    assertThat(activeRule.severity()).isEqualTo(Severity.BLOCKER);
  }
 ActiveRuleKey activeRuleKey() {
   return ActiveRuleKey.of(profile.getKee(), rule.getKey());
 }