@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;
  }
  @Override
  public void handle(Request request, Response response) throws Exception {
    DbSession session = dbClient.openSession(false);
    try {
      String profileKey =
          QProfileIdentificationParamUtils.getProfileKeyFromParameters(
              request, profileFactory, session);
      if (dbClient.qualityProfileDao().getByKey(session, profileKey) == null) {
        throw new NotFoundException(
            String.format("Could not find a profile with key '%s'", profileKey));
      }

      QProfileActivityQuery query = new QProfileActivityQuery().setQprofileKey(profileKey);
      Date since = request.paramAsDateTime(PARAM_SINCE);
      if (since != null) {
        query.setSince(since);
      }
      Date to = request.paramAsDateTime(PARAM_TO);
      if (to != null) {
        query.setTo(to);
      }
      SearchOptions options = new SearchOptions();

      int page = request.mandatoryParamAsInt(Param.PAGE);
      options.setPage(page, request.mandatoryParamAsInt(Param.PAGE_SIZE));

      Result<QProfileActivity> result = searchActivities(query, options);
      writeResponse(
          response.newJsonWriter(),
          result,
          Paging.create(options.getLimit(), page, (int) result.getTotal()));
    } finally {
      session.close();
    }
  }
  @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);
  }
  /** 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 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 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 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");
  }
 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 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);
  }
Example #12
0
  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;
  }
  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);
    }
  }
 void setDefault(String profileKey) {
   DbSession dbSession = db.openSession(false);
   try {
     setDefault(dbSession, profileKey);
   } finally {
     dbSession.close();
   }
 }
 QualityProfileDto getByNameAndLanguage(String name, String language) {
   DbSession dbSession = db.openSession(false);
   try {
     return getByNameAndLanguage(dbSession, name, language);
   } finally {
     dbSession.close();
   }
 }
 QualityProfileDto getByProjectAndLanguage(String projectKey, String language) {
   DbSession dbSession = db.openSession(false);
   try {
     return getByProjectAndLanguage(dbSession, projectKey, language);
   } finally {
     dbSession.close();
   }
 }
 void delete(String key) {
   DbSession session = db.openSession(false);
   try {
     delete(session, key, false);
     session.commit();
   } finally {
     session.close();
   }
 }
Example #18
0
 /**
  * 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();
   }
 }
 @CheckForNull
 QualityProfileDto getDefault(String language) {
   DbSession dbSession = db.openSession(false);
   try {
     return getDefault(dbSession, language);
   } finally {
     dbSession.close();
   }
 }
Example #20
0
 /**
  * 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();
   }
 }
Example #21
0
  void setParent(QualityProfileKey key, @Nullable QualityProfileKey parentKey) {
    DbSession dbSession = db.openSession(false);
    try {
      setParent(dbSession, key, parentKey);
      dbSession.commit();

    } finally {
      dbSession.close();
    }
  }
Example #22
0
  @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);
  }
Example #23
0
  @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);
  }
Example #24
0
  @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);
  }
Example #25
0
  @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);
  }
Example #26
0
  @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);
  }
Example #27
0
  @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);
  }
Example #28
0
  @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_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 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();
  }