@Test
  public void search_by_characteristics() throws InterruptedException {
    CharacteristicDto char1 = DebtTesting.newCharacteristicDto("RELIABILITY");
    db.debtCharacteristicDao().insert(char1, dbSession);

    CharacteristicDto char11 =
        DebtTesting.newCharacteristicDto("SOFT_RELIABILITY").setParentId(char1.getId());
    db.debtCharacteristicDao().insert(char11, dbSession);
    dbSession.commit();

    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001")).setSubCharacteristicId(char11.getId()));

    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S002")));

    dbSession.commit();
    dbSession.clearCache();

    RuleQuery query;
    Result<Rule> results;

    // 0. we have 2 rules in index
    results = index.search(new RuleQuery(), new QueryOptions());
    assertThat(results.getHits()).hasSize(2);

    // filter by non-subChar
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of("toto"));
    assertThat(index.search(query, new QueryOptions()).getHits()).isEmpty();

    // filter by subChar
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char11.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // filter by Char
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char1.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // filter by Char and SubChar
    query =
        new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char11.getKey(), char1.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by Char
    query = new RuleQuery().setQueryText(char1.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by SubChar
    query = new RuleQuery().setQueryText(char11.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by SubChar & Char
    query = new RuleQuery().setQueryText(char11.getKey() + " " + char1.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);
  }
 public boolean rename(String key, String newName) {
   Verifications.check(StringUtils.isNotBlank(newName), "Name must be set");
   Verifications.check(
       newName.length() < 100, String.format("Name is too long (>%d characters)", 100));
   DbSession dbSession = db.openSession(false);
   try {
     QualityProfileDto profile = db.qualityProfileDao().getNonNullByKey(dbSession, key);
     if (!StringUtils.equals(newName, profile.getName())) {
       if (db.qualityProfileDao().getByNameAndLanguage(newName, profile.getLanguage(), dbSession)
           != null) {
         throw new BadRequestException("Quality profile already exists: " + newName);
       }
       String previousName = profile.getName();
       profile.setName(newName);
       db.qualityProfileDao().update(dbSession, profile);
       db.propertiesDao()
           .updateProperties(
               PROFILE_PROPERTY_PREFIX + profile.getLanguage(), previousName, newName, dbSession);
       dbSession.commit();
       return true;
     }
     return false;
   } finally {
     dbSession.close();
   }
 }
  @Test
  public void get_search_health() {
    DbSession dbSession = tester.get(DbClient.class).openSession(false);
    tester
        .get(RuleDao.class)
        .insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S001")));
    dbSession.commit();

    SearchHealth health = tester.get(SearchHealth.class);
    Date now = new Date();

    ClusterHealth clusterHealth = health.getClusterHealth();
    assertThat(clusterHealth.isClusterAvailable()).isTrue();
    assertThat(clusterHealth.getNumberOfNodes()).isEqualTo(1);

    NodeHealth nodeHealth = health.getNodesHealth().values().iterator().next();
    assertThat(nodeHealth.isMaster()).isTrue();
    System.out.println(nodeHealth.getAddress());
    assertThat(nodeHealth.getAddress()).contains(":");
    assertThat(nodeHealth.getJvmHeapUsedPercent()).contains("%");
    assertThat(nodeHealth.getFsUsedPercent()).contains("%");
    assertThat(nodeHealth.getJvmThreads()).isGreaterThanOrEqualTo(0L);
    assertThat(nodeHealth.getProcessCpuPercent()).contains("%");
    assertThat(nodeHealth.getOpenFiles()).isGreaterThanOrEqualTo(0L);
    assertThat(nodeHealth.getJvmUpSince().before(now)).isTrue();

    Map<String, IndexHealth> indexHealth = health.getIndexHealth();
    assertThat(indexHealth).isNotEmpty();
    for (IndexHealth index : indexHealth.values()) {
      assertThat(index.getDocumentCount()).isGreaterThanOrEqualTo(0L);
      assertThat(index.getLastSynchronization().before(now)).isTrue();
      assertThat(index.isOptimized()).isIn(true, false);
    }
  }
  private ValidationMessages restoreXmlModel(String xml, @Nullable final String languageKey) {
    checkPermission();

    ValidationMessages validationMessages = ValidationMessages.create();
    Date updateDate = new Date(system2.now());
    DbSession session = dbClient.openSession(false);
    try {
      List<CharacteristicDto> allCharacteristicDtos =
          restoreCharacteristics(characteristicsXMLImporter.importXML(xml), updateDate, session);
      restoreRules(
          allCharacteristicDtos,
          rules(languageKey, session),
          rulesXMLImporter.importXML(xml, validationMessages),
          validationMessages,
          updateDate,
          session);

      session.commit();
    } catch (IllegalArgumentException e) {
      LOG.debug("Error when restoring the model", e);
      validationMessages.addErrorText(e.getMessage());
    } finally {
      MyBatis.closeQuietly(session);
    }
    return validationMessages;
  }
  public void renameProfile(int profileId, String newName, UserSession userSession) {
    checkPermission(userSession);
    DbSession session = myBatis.openSession(false);
    try {
      QualityProfileDto profileDto = findNotNull(profileId, session);
      String oldName = profileDto.getName();

      QProfile profile = QProfile.from(profileDto);
      if (!oldName.equals(newName)) {
        checkNotAlreadyExists(newName, profile.language(), session);
      }
      profileDto.setName(newName);
      dao.update(session, profileDto);

      List<QProfile> children = profileLookup.children(profile, session);
      for (QProfile child : children) {
        dao.update(session, child.setParent(newName).toDto());
      }
      propertiesDao.updateProperties(
          PROFILE_PROPERTY_PREFIX + profile.language(), oldName, newName, session);

      session.commit();
    } finally {
      MyBatis.closeQuietly(session);
    }
  }
  @Test
  public void paging() {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S003")));
    dbSession.commit();

    // from 0 to 1 included
    QueryOptions options = new QueryOptions();
    options.setOffset(0).setLimit(2);
    Result results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(2);

    // from 0 to 9 included
    options.setOffset(0).setLimit(10);
    results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(3);

    // from 2 to 11 included
    options.setOffset(2).setLimit(10);
    results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(1);
  }
  BulkChangeResult bulkActivate(
      RuleQuery ruleQuery, QualityProfileKey profileKey, @Nullable String severity) {
    BulkChangeResult result = new BulkChangeResult();
    RuleIndex ruleIndex = index.get(RuleIndex.class);
    DbSession dbSession = db.openSession(false);
    try {
      Result<Rule> ruleSearchResult =
          ruleIndex.search(ruleQuery, new QueryOptions().setScroll(true));
      Iterator<Rule> rules = ruleSearchResult.scroll();
      while (rules.hasNext()) {
        Rule rule = rules.next();
        try {
          ActiveRuleKey key = ActiveRuleKey.of(profileKey, rule.key());
          RuleActivation activation = new RuleActivation(key);
          activation.setSeverity(severity);
          List<ActiveRuleChange> changes = activate(dbSession, activation);
          result.addChanges(changes);
          result.incrementSucceeded();

        } catch (BadRequestException e) {
          // other exceptions stop the bulk activation
          result.incrementFailed();
          // TODO result.addMessage
        }
      }
      dbSession.commit();
    } finally {
      dbSession.close();
    }
    return result;
  }
  @Test
  public void reactivate_disabled_custom_rules() {
    Rule templateRule = index.getByKey(RuleKey.of("xoo", "template1"));

    // Create custom rule
    RuleKey customRuleKey =
        tester
            .get(RuleCreator.class)
            .create(
                NewRule.createForCustomRule("CUSTOM_RULE", templateRule.key())
                    .setName("My custom")
                    .setHtmlDescription("Some description")
                    .setSeverity(Severity.MAJOR)
                    .setStatus(RuleStatus.READY));
    dbSession.commit();
    dbSession.clearCache();
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.READY);

    // Restart without template rule
    rulesDefinition.includeTemplate1 = false;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();

    // Verify custom rule is removed
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.REMOVED);

    // Restart with template rule
    rulesDefinition.includeTemplate1 = true;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();

    // Verify custom rule is reactivate
    assertThat(index.getByKey(customRuleKey).status()).isEqualTo(RuleStatus.READY);
  }
  @Test
  public void search_qprofile_activity_with_user_not_found() throws InterruptedException {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("david");

    // We need an actual rule in DB to test RuleName in Activity
    db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1);

    tester
        .get(ActivityService.class)
        .write(
            dbSession,
            Activity.Type.QPROFILE,
            ActiveRuleChange.createFor(
                    ActiveRuleChange.Type.ACTIVATED,
                    ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1))
                .setSeverity(Severity.MAJOR)
                .setParameter("max", "10"));
    dbSession.commit();

    Result<QProfileActivity> activities =
        service.searchActivities(new QProfileActivityQuery(), new QueryContext());
    assertThat(activities.getHits()).hasSize(1);

    QProfileActivity activity = activities.getHits().get(0);
    assertThat(activity.login()).isEqualTo("david");
    assertThat(activity.authorName()).isNull();
  }
  @Test
  public void remove_debt_rule() throws Exception {
    verifyRulesInDb();

    // Set some default debt on x2 rule, which has no debt provided by th plugin
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X2);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(
                    db.debtCharacteristicDao()
                        .selectByKey(
                            RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY, dbSession)
                        .getId())
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been removed
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X2);
    assertThat(ruleReloaded.debtSubCharacteristicKey()).isNull();
    assertThat(ruleReloaded.debtRemediationFunction()).isNull();
  }
  @Test
  public void not_update_custom_rule_from_template_if_no_change() throws Exception {
    Rule templateRule = index.getByKey(RuleKey.of("xoo", "template1"));

    // Create custom rule
    RuleKey customRuleKey =
        tester
            .get(RuleCreator.class)
            .create(
                NewRule.createForCustomRule("CUSTOM_RULE", templateRule.key())
                    .setName("My custom")
                    .setHtmlDescription("Some description")
                    .setSeverity(Severity.MAJOR)
                    .setStatus(RuleStatus.READY)
                    .setParameters(ImmutableMap.of("format", "txt")));
    dbSession.commit();
    dbSession.clearCache();

    // Store updated at date
    Date updatedAt = index.getByKey(customRuleKey).updatedAt();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify custom rule has not been updated
    Rule customRuleReloaded = index.getByKey(customRuleKey);
    assertThat(customRuleReloaded.updatedAt()).isEqualTo(updatedAt);
  }
  @Test
  public void update_debt_rule() throws Exception {
    verifyRulesInDb();

    // Update x1 rule
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(123456)
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been reset to plugin definition
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X1);
    assertThat(ruleReloaded.debtSubCharacteristicKey())
        .isEqualTo(RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY);
    assertThat(ruleReloaded.debtRemediationFunction().type())
        .isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
    assertThat(ruleReloaded.debtRemediationFunction().coefficient()).isEqualTo("1h");
    assertThat(ruleReloaded.debtRemediationFunction().offset()).isEqualTo("30min");
  }
  @Test
  public void do_not_deactivate_removed_rules_if_repository_accidentaly_uninstalled()
      throws Exception {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("me");

    // create a profile and activate rule
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    tester.get(QProfileService.class).activate(QProfileTesting.XOO_P1_KEY, activation);
    dbSession.clearCache();

    // restart without x1, x2, template1 -> keep active rule of x1
    rulesDefinition.includeX1 = false;
    rulesDefinition.includeX2 = false;
    rulesDefinition.includeTemplate1 = false;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();
    assertThat(db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X2).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.activeRuleDao().findByProfileKey(dbSession, QProfileTesting.XOO_P1_KEY))
        .hasSize(1);
  }
  @Test
  public void deactivate_removed_rules_only_if_repository_still_exists() throws Exception {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("me");

    // create a profile and activate rule
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    tester.get(QProfileService.class).activate(QProfileTesting.XOO_P1_KEY, activation);
    dbSession.clearCache();

    // restart, x2 still exists -> deactivate x1
    rulesDefinition.includeX1 = false;
    rulesDefinition.includeX2 = true;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();
    assertThat(db.ruleDao().getByKey(dbSession, RuleKey.of("xoo", "x1")).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.ruleDao().getByKey(dbSession, RuleKey.of("xoo", "x2")).getStatus())
        .isEqualTo(RuleStatus.READY);
    assertThat(db.activeRuleDao().findByProfileKey(dbSession, QProfileTesting.XOO_P1_KEY))
        .hasSize(0);
  }
  /** Reset from provided model */
  public void reset() {
    checkPermission();

    Date updateDate = new Date(system2.now());
    DbSession session = dbClient.openSession(false);
    try {
      // Restore characteristics
      List<CharacteristicDto> allCharacteristicDtos =
          restoreCharacteristics(
              loadModelFromPlugin(DebtModelPluginRepository.DEFAULT_MODEL), updateDate, session);

      // Restore rules
      List<RuleDto> ruleDtos = dbClient.ruleDao().selectEnabledAndNonManual(session);
      if (!ruleDtos.isEmpty()) {

        // Load default rule definitions
        RulesDefinition.Context context = defLoader.load();
        List<RulesDefinition.Rule> rules = newArrayList();
        for (RulesDefinition.Repository repoDef : context.repositories()) {
          rules.addAll(repoDef.rules());
        }

        resetRules(ruleDtos, rules, allCharacteristicDtos, updateDate, session);
      }

      session.commit();
    } finally {
      MyBatis.closeQuietly(session);
    }
  }
  @Test
  public void search_qprofile_activity_with_rule_not_found() throws InterruptedException {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("me");

    RuleKey ruleKey = RuleKey.of("xoo", "deleted_rule");

    tester
        .get(ActivityService.class)
        .write(
            dbSession,
            Activity.Type.QPROFILE,
            ActiveRuleChange.createFor(
                    ActiveRuleChange.Type.ACTIVATED, ActiveRuleKey.of(XOO_P1_KEY, ruleKey))
                .setSeverity(Severity.MAJOR)
                .setParameter("max", "10"));
    dbSession.commit();

    Result<QProfileActivity> activities =
        service.searchActivities(new QProfileActivityQuery(), new QueryContext());
    assertThat(activities.getHits()).hasSize(1);

    QProfileActivity activity = activities.getHits().get(0);
    assertThat(activity.ruleKey()).isEqualTo(ruleKey);
    assertThat(activity.ruleName()).isNull();
  }
  @Test
  public void search_by_template_key_with_params() throws InterruptedException {
    RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
    RuleParamDto ruleParamDto =
        RuleParamDto.createFor(templateRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue(".*");
    dao.insert(dbSession, templateRule);
    dao.addRuleParam(dbSession, templateRule, ruleParamDto);

    RuleDto customRule =
        RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM"))
            .setTemplateId(templateRule.getId());
    RuleParamDto customRuleParam =
        RuleParamDto.createFor(customRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue("a.*");
    dao.insert(dbSession, customRule);
    dao.addRuleParam(dbSession, customRule, customRuleParam);
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(2);

    // get params
    assertThat(index.getByKey(templateRule.getKey()).params()).hasSize(1);
    assertThat(index.getByKey(customRule.getKey()).params()).hasSize(1);
  }
  @Test
  public void search_by_template_key() throws InterruptedException {
    RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
    dao.insert(dbSession, templateRule);
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM"))
            .setTemplateId(templateRule.getId()));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(2);

    // Only custom rule
    query = new RuleQuery().setTemplateKey("java:S001");
    results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule())
        .isEqualTo("S001_MY_CUSTOM");
    assertThat(Iterables.getFirst(results.getHits(), null).templateKey())
        .isEqualTo(RuleKey.of("java", "S001"));

    // null => no filter
    query = new RuleQuery().setTemplateKey(null);
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_is_template() throws InterruptedException {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(false));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setIsTemplate(true));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(2);

    // Only template
    query = new RuleQuery().setIsTemplate(true);
    results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");
    assertThat(Iterables.getFirst(results.getHits(), null).isTemplate()).isTrue();

    // Only not template
    query = new RuleQuery().setIsTemplate(false);
    results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).isTemplate()).isFalse();
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S001");

    // null => no filter
    query = new RuleQuery().setIsTemplate(null);
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_any_of_statuses() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY));
    dbSession.commit();

    RuleQuery query =
        new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED, RuleStatus.READY));
    Result<Rule> results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED));
    assertThat(index.search(query, new QueryOptions()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setStatuses(Collections.<RuleStatus>emptyList());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setStatuses(null);
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_any_of_severities() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setSeverities(Arrays.asList(Severity.INFO, Severity.MINOR));
    Result<Rule> results = index.search(query, new QueryOptions());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setSeverities(Arrays.asList(Severity.MINOR));
    assertThat(index.search(query, new QueryOptions()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setSeverities(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setSeverities(null);
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_has_debt_characteristic() throws InterruptedException {
    CharacteristicDto char1 =
        DebtTesting.newCharacteristicDto("c1").setEnabled(true).setName("char1");
    db.debtCharacteristicDao().insert(char1, dbSession);
    dbSession.commit();

    CharacteristicDto char11 =
        DebtTesting.newCharacteristicDto("c11")
            .setEnabled(true)
            .setName("char11")
            .setParentId(char1.getId());
    db.debtCharacteristicDao().insert(char11, dbSession);

    // Rule with default characteristic
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("findbugs", "S001"))
            .setSubCharacteristicId(null)
            .setRemediationFunction(null)
            .setDefaultSubCharacteristicId(char11.getId())
            .setDefaultRemediationFunction("LINEAR")
            .setDefaultRemediationCoefficient("2h"));
    // Rule with overridden characteristic
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("pmd", "S002"))
            .setSubCharacteristicId(char11.getId())
            .setRemediationFunction("LINEAR")
            .setRemediationCoefficient("2h")
            .setDefaultSubCharacteristicId(null)
            .setDefaultRemediationFunction(null));
    dbSession.commit();

    // 0. assert base case
    assertThat(index.search(new RuleQuery(), new QueryOptions()).getTotal()).isEqualTo(2);
    assertThat(db.debtCharacteristicDao().selectCharacteristics()).hasSize(2);

    // 1. assert hasSubChar filter
    assertThat(
            index
                .search(new RuleQuery().setHasDebtCharacteristic(true), new QueryOptions())
                .getTotal())
        .isEqualTo(2);
  }
  @Test
  public void load_project_id_from_db() throws Exception {
    setupData("load_project_id_from_db");
    session.commit();

    long projectId = storage.project(session, new DefaultIssue().setProjectKey("struts")).getId();

    assertThat(projectId).isEqualTo(1);
  }
 /**
  * Activate a rule on a Quality profile. Update configuration (severity/parameters) if the rule is
  * already activated.
  *
  * @throws org.sonar.server.exceptions.BadRequestException if the profile, the rule or a rule
  *     parameter does not exist
  */
 public List<ActiveRuleChange> activate(RuleActivation activation) {
   DbSession dbSession = db.openSession(false);
   try {
     return activate(dbSession, activation);
   } finally {
     dbSession.commit();
     dbSession.close();
   }
 }
 void delete(String key) {
   DbSession session = db.openSession(false);
   try {
     delete(session, key, false);
     session.commit();
   } finally {
     session.close();
   }
 }
Beispiel #26
0
  @Test
  public void update_authorization_date() {
    setupData("update_authorization_date");

    when(system2.now()).thenReturn(987654321L);
    dao.updateAuthorizationDate(1L, session);
    session.commit();

    checkTables("update_authorization_date", "projects");
  }
  void setParent(QualityProfileKey key, @Nullable QualityProfileKey parentKey) {
    DbSession dbSession = db.openSession(false);
    try {
      setParent(dbSession, key, parentKey);
      dbSession.commit();

    } finally {
      dbSession.close();
    }
  }
 /**
  * Deactivate a rule on a Quality profile. Does nothing if the rule is not activated, but fails
  * (fast) if the rule or the profile does not exist.
  */
 List<ActiveRuleChange> deactivate(ActiveRuleKey key) {
   DbSession dbSession = db.openSession(false);
   try {
     List<ActiveRuleChange> changes = deactivate(dbSession, key);
     dbSession.commit();
     return changes;
   } finally {
     dbSession.close();
   }
 }
  @Test
  public void load_component_id_from_db() throws Exception {
    setupData("load_component_id_from_db");
    session.commit();

    long componentId =
        storage.component(session, new DefaultIssue().setComponentKey("struts:Action")).getId();

    assertThat(componentId).isEqualTo(100);
  }
  @Test
  public void search_all_rules() throws InterruptedException {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")));
    dbSession.commit();

    Result results = index.search(new RuleQuery(), new QueryOptions());

    assertThat(results.getTotal()).isEqualTo(2);
    assertThat(results.getHits()).hasSize(2);
  }