コード例 #1
0
    @Override
    public void define(Context context) {
      NewRepository repo = context.createRepository("fake", "java");

      // almost all the attributes of rule1 are changed
      NewRule rule1 =
          repo.createRule("rule1")
              .setName("One v2")
              .setHtmlDescription("Description of One v2")
              .setSeverity(Severity.INFO)
              .setInternalKey("config1 v2")
              // tag2 and tag3 removed, tag4 added
              .setTags("tag1", "tag4")
              .setStatus(RuleStatus.READY)
              .setDebtSubCharacteristic("MEMORY_EFFICIENCY")
              .setEffortToFixDescription("squid.S115.effortToFix.v2");
      rule1.setDebtRemediationFunction(
          rule1.debtRemediationFunctions().linearWithOffset("6d", "2h"));
      rule1.createParam("param1").setDescription("parameter one v2").setDefaultValue("default1 v2");
      rule1.createParam("param2").setDescription("parameter two v2").setDefaultValue("default2 v2");

      // rule2 is dropped, rule3 is new
      repo.createRule("rule3").setName("Three").setHtmlDescription("Rule Three");
      repo.done();
    }
コード例 #2
0
  private RuleKey createCustomRule(
      RuleKey ruleKey, NewRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
    RuleDto ruleDto =
        RuleDto.createFor(ruleKey)
            .setTemplateId(templateRuleDto.getId())
            .setConfigKey(templateRuleDto.getConfigKey())
            .setName(newRule.name())
            .setDescription(newRule.markdownDescription())
            .setDescriptionFormat(Format.MARKDOWN)
            .setSeverity(newRule.severity())
            .setStatus(newRule.status())
            .setLanguage(templateRuleDto.getLanguage())
            .setDefaultSubCharacteristicId(templateRuleDto.getDefaultSubCharacteristicId())
            .setDefaultRemediationFunction(templateRuleDto.getDefaultRemediationFunction())
            .setDefaultRemediationCoefficient(templateRuleDto.getDefaultRemediationCoefficient())
            .setDefaultRemediationOffset(templateRuleDto.getDefaultRemediationOffset())
            .setEffortToFixDescription(templateRuleDto.getEffortToFixDescription())
            .setTags(templateRuleDto.getTags())
            .setSystemTags(templateRuleDto.getSystemTags());
    dbClient.ruleDao().insert(dbSession, ruleDto);

    for (RuleParamDto templateRuleParamDto :
        dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, templateRuleDto.getKey())) {
      String customRuleParamValue =
          Strings.emptyToNull(newRule.parameter(templateRuleParamDto.getName()));
      createCustomRuleParams(customRuleParamValue, ruleDto, templateRuleParamDto, dbSession);
    }
    return ruleKey;
  }
コード例 #3
0
  private void validateCustomRule(NewRule newRule, DbSession dbSession, RuleKey templateKey) {
    Errors errors = new Errors();

    validateRuleKey(errors, newRule.ruleKey());
    validateName(errors, newRule);
    validateDescription(errors, newRule);

    String severity = newRule.severity();
    if (Strings.isNullOrEmpty(severity)) {
      errors.add(Message.of("coding_rules.validation.missing_severity"));
    } else if (!Severity.ALL.contains(severity)) {
      errors.add(Message.of("coding_rules.validation.invalid_severity", severity));
    }
    if (newRule.status() == null) {
      errors.add(Message.of("coding_rules.validation.missing_status"));
    }

    for (RuleParamDto ruleParam :
        dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, templateKey)) {
      try {
        validateParam(ruleParam, newRule.parameter(ruleParam.getName()));
      } catch (BadRequestException validationError) {
        errors.add(validationError.errors());
      }
    }

    if (!errors.isEmpty()) {
      throw new BadRequestException(errors);
    }
  }
コード例 #4
0
 private RuleKey createManualRule(RuleKey ruleKey, NewRule newRule, DbSession dbSession) {
   RuleDto ruleDto =
       RuleDto.createFor(ruleKey)
           .setName(newRule.name())
           .setDescription(newRule.markdownDescription())
           .setDescriptionFormat(Format.MARKDOWN)
           .setSeverity(newRule.severity())
           .setStatus(RuleStatus.READY);
   dbClient.ruleDao().insert(dbSession, ruleDto);
   return ruleKey;
 }
コード例 #5
0
  private static void validateManualRule(NewRule newRule) {
    Errors errors = new Errors();
    validateRuleKey(errors, newRule.ruleKey());
    validateName(errors, newRule);
    validateDescription(errors, newRule);

    if (!newRule.parameters().isEmpty()) {
      errors.add(Message.of("coding_rules.validation.manual_rule_params"));
    }

    if (!errors.isEmpty()) {
      throw new BadRequestException(errors);
    }
  }
コード例 #6
0
 @Override
 public void define(Context context) {
   NewRepository repo = context.createRepository("big", "java");
   for (int i = 0; i < SIZE; i++) {
     NewRule rule =
         repo.createRule("rule" + i)
             .setName("name of " + i)
             .setHtmlDescription("description of " + i);
     for (int j = 0; j < 20; j++) {
       rule.createParam("param" + j);
     }
   }
   repo.done();
 }
コード例 #7
0
  @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);
  }
コード例 #8
0
  @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);
  }
コード例 #9
0
ファイル: CxxRuleRepository.java プロジェクト: kocz/sonar-cxx
  @Override
  public void define(Context context) {
    NewRepository repository =
        context
            .createRepository(CheckList.REPOSITORY_KEY, CxxLanguage.KEY)
            .setName(REPOSITORY_NAME);
    AnnotationBasedRulesDefinition.load(repository, CxxLanguage.KEY, CheckList.getChecks());
    for (NewRule rule : repository.rules()) {
      // FIXME: set internal key to key to ensure rule templates works properly : should be removed
      // when SONAR-6162 is fixed.
      rule.setInternalKey(rule.key());
    }

    SqaleXmlLoader.load(repository, "/com/sonar/sqale/cxx-model.xml");
    repository.done();
  }
コード例 #10
0
  public RuleKey create(NewRule newRule) {
    DbSession dbSession = dbClient.openSession(false);
    try {

      if (newRule.isCustom()) {
        return createCustomRule(newRule, dbSession);
      }

      if (newRule.isManual()) {
        return createManualRule(newRule, dbSession);
      }

      throw new IllegalStateException("Only custom rule and manual rule can be created");
    } finally {
      dbSession.close();
    }
  }
コード例 #11
0
    @Override
    public void define(Context context) {
      NewRepository repo = context.createRepository("fake", "java");
      NewRule rule1 =
          repo.createRule("rule1")
              .setName("One")
              .setHtmlDescription("Description of One")
              .setSeverity(Severity.BLOCKER)
              .setInternalKey("config1")
              .setTags("tag1", "tag2", "tag3")
              .setStatus(RuleStatus.BETA)
              .setDebtSubCharacteristic("MEMORY_EFFICIENCY")
              .setEffortToFixDescription("squid.S115.effortToFix");
      rule1.setDebtRemediationFunction(
          rule1.debtRemediationFunctions().linearWithOffset("5d", "10h"));

      rule1.createParam("param1").setDescription("parameter one").setDefaultValue("default1");
      rule1.createParam("param2").setDescription("parameter two").setDefaultValue("default2");

      repo.createRule("rule2").setName("Two").setHtmlDescription("Minimal rule");
      repo.done();
    }
コード例 #12
0
  private RuleKey createManualRule(NewRule newRule, DbSession dbSession) {
    validateManualRule(newRule);

    RuleKey customRuleKey = RuleKey.of(RuleDoc.MANUAL_REPOSITORY, newRule.ruleKey());
    RuleDto existingRule = loadRule(customRuleKey, dbSession);
    if (existingRule != null) {
      updateExistingRule(existingRule, newRule, dbSession);
    } else {
      createManualRule(customRuleKey, newRule, dbSession);
    }

    dbSession.commit();
    return customRuleKey;
  }
コード例 #13
0
  private RuleKey createCustomRule(NewRule newRule, DbSession dbSession) {
    RuleKey templateKey = newRule.templateKey();
    if (templateKey == null) {
      throw new IllegalArgumentException("Rule template key should not be null");
    }
    RuleDto templateRule = dbClient.ruleDao().getByKey(dbSession, templateKey);
    if (!templateRule.isTemplate()) {
      throw new IllegalArgumentException(
          "This rule is not a template rule: " + templateKey.toString());
    }
    validateCustomRule(newRule, dbSession, templateKey);

    RuleKey customRuleKey = RuleKey.of(templateRule.getRepositoryKey(), newRule.ruleKey());

    RuleDto existingRule = loadRule(customRuleKey, dbSession);
    if (existingRule != null) {
      updateExistingRule(existingRule, newRule, dbSession);
    } else {
      createCustomRule(customRuleKey, newRule, templateRule, dbSession);
    }

    dbSession.commit();
    return customRuleKey;
  }
コード例 #14
0
 private void updateExistingRule(RuleDto ruleDto, NewRule newRule, DbSession dbSession) {
   if (ruleDto.getStatus().equals(RuleStatus.REMOVED)) {
     if (newRule.isPreventReactivation()) {
       throw new ReactivationException(
           String.format(
               "A removed rule with the key '%s' already exists", ruleDto.getKey().rule()),
           ruleDto.getKey());
     } else {
       ruleDto.setStatus(RuleStatus.READY);
       dbClient.ruleDao().update(dbSession, ruleDto);
     }
   } else {
     throw new IllegalArgumentException(
         String.format("A rule with the key '%s' already exists", ruleDto.getKey().rule()));
   }
 }
コード例 #15
0
  @Test
  public void update_custom_rule_from_template() 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")));

    // Update custom rule
    RuleDto customRuleDto = db.ruleDao().getByKey(dbSession, customRuleKey);
    db.ruleDao()
        .update(
            dbSession,
            customRuleDto
                .setLanguage("other language")
                .setConfigKey("other config key")
                .setDefaultSubCharacteristicId(45)
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("1h")
                .setDefaultRemediationOffset("5min")
                .setEffortToFixDescription("effort to fix desc"));
    dbSession.commit();
    dbSession.clearCache();

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

    // Verify custom rule has been restore from the template
    Rule customRule = index.getByKey(customRuleKey);
    assertThat(customRule.language()).isEqualTo("xoo");
    assertThat(customRule.internalKey()).isNull();
    assertThat(customRule.debtSubCharacteristicKey()).isNull();
    assertThat(customRule.debtRemediationFunction()).isNull();
  }
コード例 #16
0
  @Test
  public void not_disable_manual_rules() {
    // Create manual rule
    RuleKey manualRuleKey =
        tester
            .get(RuleCreator.class)
            .create(
                NewRule.createForManualRule("MANUAL_RULE")
                    .setName("My manual")
                    .setHtmlDescription("Some description"));
    dbSession.commit();
    dbSession.clearCache();
    assertThat(index.getByKey(manualRuleKey).status()).isEqualTo(RuleStatus.READY);

    // Restart
    tester.get(Platform.class).executeStartupTasks();

    // Verify manual rule is still ready
    assertThat(index.getByKey(manualRuleKey).status()).isEqualTo(RuleStatus.READY);
  }
コード例 #17
0
  @Test
  public void not_update_custom_rule_params_from_template() 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();

    // Update custom rule param name
    RuleDto customRuleDto = db.ruleDao().getByKey(dbSession, customRuleKey);
    RuleParamDto customRuleParamDto =
        db.ruleDao().findRuleParamsByRuleKey(dbSession, customRuleKey).get(0);
    db.ruleDao().removeRuleParam(dbSession, customRuleDto, customRuleParamDto);
    db.ruleDao().addRuleParam(dbSession, customRuleDto, customRuleParamDto.setName("format2"));
    dbSession.commit();
    dbSession.clearCache();

    // Verify param has been updated
    Rule customRule = index.getByKey(customRuleKey);
    assertThat(customRule.params()).hasSize(1);
    assertThat(customRule.params().get(0).key()).isEqualTo("format2");

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

    // Verify custom rule param has not been changed!
    Rule customRuleReloaded = index.getByKey(customRuleKey);
    assertThat(customRuleReloaded.params().get(0).key()).isEqualTo("format2");
  }
コード例 #18
0
 private static void validateName(Errors errors, NewRule newRule) {
   if (Strings.isNullOrEmpty(newRule.name())) {
     errors.add(Message.of("coding_rules.validation.missing_name"));
   }
 }
コード例 #19
0
    @Override
    public void define(Context context) {
      if (includeX1
          || includeX1bis
          || includeX2
          || includeTemplate1
          || includeRuleLinkedToRootCharacteristic) {
        NewRepository repository = context.createRepository("xoo", "xoo").setName("Xoo Repo");
        if (includeX1) {
          NewRule x1Rule =
              repository
                  .createRule(RuleTesting.XOO_X1.rule())
                  .setName("x1 name")
                  .setHtmlDescription("x1 desc")
                  .setSeverity(Severity.MINOR)
                  .setEffortToFixDescription("x1 effort to fix")
                  .setTags("tag1");
          x1Rule
              .createParam("acceptWhitespace")
              .setType(RuleParamType.BOOLEAN)
              .setDefaultValue("false")
              .setDescription("Accept whitespaces on the line");
          x1Rule
              .setDebtSubCharacteristic(SubCharacteristics.INTEGRATION_TESTABILITY)
              .setDebtRemediationFunction(
                  x1Rule.debtRemediationFunctions().linearWithOffset("1h", "30min"));
        }

        // X1 having fields updated to simulate an update from the plugin
        if (includeX1bis) {
          NewRule x1Rule =
              repository
                  .createRule(RuleTesting.XOO_X1.rule())
                  .setName("x1 name updated")
                  .setHtmlDescription("x1 desc updated")
                  .setSeverity(Severity.INFO)
                  .setEffortToFixDescription("x1 effort to fix updated")
                  .setTags("tag1", "tag2", "user-tag");
          x1Rule
              .createParam("acceptWhitespace")
              .setType(RuleParamType.BOOLEAN)
              .setDefaultValue("true")
              .setDescription("Accept whitespaces on the line updated");
          // New param
          x1Rule
              .createParam("format")
              .setType(RuleParamType.TEXT)
              .setDefaultValue("txt")
              .setDescription("Format");
          x1Rule
              .setDebtSubCharacteristic(SubCharacteristics.INSTRUCTION_RELIABILITY)
              .setDebtRemediationFunction(x1Rule.debtRemediationFunctions().linear("2h"));
        }

        if (includeX2) {
          repository
              .createRule(RuleTesting.XOO_X2.rule())
              .setName("x2 name")
              .setHtmlDescription("x2 desc")
              .setSeverity(Severity.MAJOR);
        }

        if (includeRuleLinkedToRootCharacteristic) {
          NewRule x1Rule =
              repository
                  .createRule("RuleLinkedToRootCharacteristic")
                  .setName("RuleLinkedToRootCharacteristic name")
                  .setHtmlDescription("RuleLinkedToRootCharacteristic desc")
                  .setSeverity(Severity.MINOR);
          x1Rule
              // Link to a root characteristic -> fail
              .setDebtSubCharacteristic("REUSABILITY")
              .setDebtRemediationFunction(
                  x1Rule.debtRemediationFunctions().linearWithOffset("1h", "30min"));
        }

        if (includeTemplate1) {
          repository
              .createRule("template1")
              .setName("template1 name")
              .setHtmlDescription("template1 desc")
              .setSeverity(Severity.MAJOR)
              .setTemplate(true)
              .createParam("format")
              .setDefaultValue("csv")
              .setType(RuleParamType.STRING)
              .setDescription("format parameter");
        }

        repository.done();
      }
    }
コード例 #20
0
 private static void validateDescription(Errors errors, NewRule newRule) {
   if (Strings.isNullOrEmpty(newRule.htmlDescription())
       && Strings.isNullOrEmpty(newRule.markdownDescription())) {
     errors.add(Message.of("coding_rules.validation.missing_description"));
   }
 }