--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.rule;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rule.RuleStatus;
+
+public class NewCustomRule {
+
+ private String ruleKey;
+ private RuleKey templateKey;
+ private String name;
+ private String htmlDescription;
+ private String markdownDescription;
+ private String severity;
+ private RuleStatus status;
+ private final Map<String, String> parameters = Maps.newHashMap();
+
+ private boolean preventReactivation = false;
+
+ private NewCustomRule() {
+ // No direct call to constructor
+ }
+
+ public String ruleKey() {
+ return ruleKey;
+ }
+
+ @CheckForNull
+ public RuleKey templateKey() {
+ return templateKey;
+ }
+
+ @CheckForNull
+ public String name() {
+ return name;
+ }
+
+ public NewCustomRule setName(@Nullable String name) {
+ this.name = name;
+ return this;
+ }
+
+ @CheckForNull
+ public String htmlDescription() {
+ return htmlDescription;
+ }
+
+ public NewCustomRule setHtmlDescription(@Nullable String htmlDescription) {
+ this.htmlDescription = htmlDescription;
+ return this;
+ }
+
+ @CheckForNull
+ public String markdownDescription() {
+ return markdownDescription;
+ }
+
+ public NewCustomRule setMarkdownDescription(@Nullable String markdownDescription) {
+ this.markdownDescription = markdownDescription;
+ return this;
+ }
+
+ @CheckForNull
+ public String severity() {
+ return severity;
+ }
+
+ public NewCustomRule setSeverity(@Nullable String severity) {
+ this.severity = severity;
+ return this;
+ }
+
+ @CheckForNull
+ public RuleStatus status() {
+ return status;
+ }
+
+ public NewCustomRule setStatus(@Nullable RuleStatus status) {
+ this.status = status;
+ return this;
+ }
+
+ public Map<String, String> parameters() {
+ return parameters;
+ }
+
+ @CheckForNull
+ public String parameter(final String paramKey) {
+ return parameters.get(paramKey);
+ }
+
+ public NewCustomRule setParameters(Map<String, String> params) {
+ this.parameters.clear();
+ this.parameters.putAll(params);
+ return this;
+ }
+
+ public boolean isPreventReactivation() {
+ return preventReactivation;
+ }
+
+ /**
+ * When true, if the rule already exists in status REMOVED, an {@link ReactivationException} will be thrown
+ */
+ public NewCustomRule setPreventReactivation(boolean preventReactivation) {
+ this.preventReactivation = preventReactivation;
+ return this;
+ }
+
+ public static NewCustomRule createForCustomRule(String customKey, RuleKey templateKey) {
+ Preconditions.checkArgument(!Strings.isNullOrEmpty(customKey), "Custom key should be set");
+ Preconditions.checkArgument(templateKey != null, "Template key should be set");
+ NewCustomRule newRule = new NewCustomRule();
+ newRule.ruleKey = customKey;
+ newRule.templateKey = templateKey;
+ return newRule;
+ }
+
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.rule;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.Maps;
-import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rule.RuleStatus;
-
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-
-import java.util.Map;
-
-public class NewRule {
-
- private String ruleKey;
- private RuleKey templateKey;
- private String name;
- private String htmlDescription;
- private String markdownDescription;
- private String severity;
- private RuleStatus status;
- private final Map<String, String> parameters = Maps.newHashMap();
-
- private boolean isCustom;
- private boolean isManual;
- private boolean preventReactivation = false;
-
- private NewRule() {
- // No direct call to constructor
- }
-
- public String ruleKey() {
- return ruleKey;
- }
-
- @CheckForNull
- public RuleKey templateKey() {
- return templateKey;
- }
-
- @CheckForNull
- public String name() {
- return name;
- }
-
- public NewRule setName(@Nullable String name) {
- this.name = name;
- return this;
- }
-
- @CheckForNull
- public String htmlDescription() {
- return htmlDescription;
- }
-
- public NewRule setHtmlDescription(@Nullable String htmlDescription) {
- this.htmlDescription = htmlDescription;
- return this;
- }
-
- @CheckForNull
- public String markdownDescription() {
- return markdownDescription;
- }
-
- public NewRule setMarkdownDescription(@Nullable String markdownDescription) {
- this.markdownDescription = markdownDescription;
- return this;
- }
-
- @CheckForNull
- public String severity() {
- return severity;
- }
-
- public NewRule setSeverity(@Nullable String severity) {
- this.severity = severity;
- return this;
- }
-
- @CheckForNull
- public RuleStatus status() {
- return status;
- }
-
- public NewRule setStatus(@Nullable RuleStatus status) {
- checkCustomRule();
- this.status = status;
- return this;
- }
-
- public Map<String, String> parameters() {
- return parameters;
- }
-
- @CheckForNull
- public String parameter(final String paramKey) {
- return parameters.get(paramKey);
- }
-
- public NewRule setParameters(Map<String, String> params) {
- checkCustomRule();
- this.parameters.clear();
- this.parameters.putAll(params);
- return this;
- }
-
- public boolean isPreventReactivation() {
- return preventReactivation;
- }
-
- /**
- * When true, if the rule already exists in status REMOVED, an {@link ReactivationException} will be thrown
- */
- public NewRule setPreventReactivation(boolean preventReactivation) {
- this.preventReactivation = preventReactivation;
- return this;
- }
-
- private void checkCustomRule(){
- if (!isCustom) {
- throw new IllegalStateException("Not a custom rule");
- }
- }
-
- public boolean isCustom() {
- return isCustom;
- }
-
- public boolean isManual() {
- return isManual;
- }
-
- public static NewRule createForCustomRule(String customKey, RuleKey templateKey) {
- Preconditions.checkArgument(!Strings.isNullOrEmpty(customKey), "Custom key should be set");
- Preconditions.checkArgument(templateKey != null, "Template key should be set");
- NewRule newRule = new NewRule();
- newRule.ruleKey = customKey;
- newRule.templateKey = templateKey;
- newRule.isCustom = true;
- return newRule;
- }
-
- public static NewRule createForManualRule(String manualKey) {
- Preconditions.checkArgument(!Strings.isNullOrEmpty(manualKey), "Manual key should be set");
- NewRule newRule = new NewRule();
- newRule.ruleKey = manualKey;
- newRule.isManual = true;
- return newRule;
- }
-
-}
update.setDebtRemediationFunction(new DefaultDebtRemediationFunction(
DebtRemediationFunction.Type.valueOf(fn),
Strings.emptyToNull((String) params.get("debtRemediationCoefficient")),
- Strings.emptyToNull((String) params.get("debtRemediationOffset")))
- );
+ Strings.emptyToNull((String) params.get("debtRemediationOffset"))));
}
updater.update(update, userSession);
}
- /**
- * Used in manual_rules_controller.rb
- */
- public void createManualRule(Map<String, Object> params) {
- NewRule newRule = NewRule.createForManualRule((String) params.get("manualKey"))
- .setName((String) params.get("name"))
- .setMarkdownDescription((String) params.get("markdownDescription"));
- service.create(newRule);
- }
-
- /**
- * Used in manual_rules_controller.rb
- */
- public void updateManualRule(Map<String, Object> params) {
- RuleUpdate update = RuleUpdate.createForManualRule(RuleKey.parse((String) params.get("ruleKey")))
- .setName((String) params.get("name"))
- .setMarkdownDescription((String) params.get("markdownDescription"));
- service.update(update);
- }
-
- /**
- * Used in manual_rules_controller.rb
- */
- public void deleteManualRule(String ruleKey) {
- service.delete(RuleKey.parse(ruleKey));
- }
-
private List<RuleDto> loadDtos(List<RuleKey> ruleKeys) {
DbSession dbSession = dbClient.openSession(false);
try {
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
-import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.utils.System2;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.Errors;
import org.sonar.server.exceptions.Message;
-import org.sonar.server.rule.index.RuleDoc;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.util.TypeValidations;
this.typeValidations = typeValidations;
}
- public RuleKey create(NewRule newRule) {
+ public RuleKey create(NewCustomRule 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");
+ return createCustomRule(newRule, dbSession);
} finally {
dbSession.close();
}
}
- private RuleKey createCustomRule(NewRule newRule, DbSession dbSession) {
+ private RuleKey createCustomRule(NewCustomRule newRule, DbSession dbSession) {
RuleKey templateKey = newRule.templateKey();
if (templateKey == null) {
throw new IllegalArgumentException("Rule template key should not be null");
return customRuleKey;
}
- private RuleKey createManualRule(NewRule newRule, DbSession dbSession) {
- validateManualRule(newRule);
-
- RuleKey customRuleKey = RuleKey.of(RuleDoc.MANUAL_REPOSITORY, newRule.ruleKey());
- Optional<RuleDto> existingRule = loadRule(customRuleKey, dbSession);
- if (existingRule.isPresent()) {
- updateExistingRule(existingRule.get(), newRule, dbSession);
- } else {
- createManualRule(customRuleKey, newRule, dbSession);
- }
-
- dbSession.commit();
- ruleIndexer.setEnabled(true).index();
- return customRuleKey;
- }
-
- private void validateCustomRule(NewRule newRule, DbSession dbSession, RuleKey templateKey) {
+ private void validateCustomRule(NewCustomRule newRule, DbSession dbSession, RuleKey templateKey) {
Errors errors = new Errors();
validateRuleKey(errors, newRule.ruleKey());
}
}
- 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);
- }
- }
-
- private static void validateName(Errors errors, NewRule newRule) {
+ private static void validateName(Errors errors, NewCustomRule newRule) {
if (Strings.isNullOrEmpty(newRule.name())) {
errors.add(Message.of("coding_rules.validation.missing_name"));
}
}
- private static void validateDescription(Errors errors, NewRule newRule) {
+ private static void validateDescription(Errors errors, NewCustomRule newRule) {
if (Strings.isNullOrEmpty(newRule.htmlDescription()) && Strings.isNullOrEmpty(newRule.markdownDescription())) {
errors.add(Message.of("coding_rules.validation.missing_description"));
}
return dbClient.ruleDao().selectByKey(dbSession, ruleKey);
}
- private RuleKey createCustomRule(RuleKey ruleKey, NewRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
+ private RuleKey createCustomRule(RuleKey ruleKey, NewCustomRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
RuleDto ruleDto = RuleDto.createFor(ruleKey)
.setTemplateId(templateRuleDto.getId())
.setConfigKey(templateRuleDto.getConfigKey())
dbClient.ruleDao().insertRuleParam(dbSession, ruleDto, ruleParamDto);
}
- 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)
- // It's not possible to update type of manual rule for the moment
- .setType(RuleType.CODE_SMELL)
- .setCreatedAt(system2.now())
- .setUpdatedAt(system2.now());
- dbClient.ruleDao().insert(dbSession, ruleDto);
- return ruleKey;
- }
-
- private void updateExistingRule(RuleDto ruleDto, NewRule newRule, DbSession dbSession) {
+ private void updateExistingRule(RuleDto ruleDto, NewCustomRule 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());
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.RuleActivator;
-import org.sonar.server.rule.index.RuleDoc;
import org.sonar.server.rule.index.RuleIndexer;
@ServerSide
DbSession dbSession = dbClient.openSession(false);
try {
RuleDto rule = dbClient.ruleDao().selectOrFailByKey(dbSession, ruleKey);
- if (rule.getTemplateId() == null && !rule.getRepositoryKey().equals(RuleDoc.MANUAL_REPOSITORY)) {
- throw new IllegalStateException("Only custom rules and manual rules can be deleted");
+ if (rule.getTemplateId() == null) {
+ throw new IllegalStateException("Only custom rules can be deleted");
}
// For custom rule, first deactivate the rule on all profiles
@ServerSide
public class RuleService {
- private final RuleUpdater ruleUpdater;
private final RuleIndex index;
- private final RuleCreator ruleCreator;
private final RuleDeleter ruleDeleter;
private final UserSession userSession;
- public RuleService(RuleUpdater ruleUpdater, RuleIndex index, RuleCreator ruleCreator, RuleDeleter ruleDeleter, UserSession userSession) {
- this.ruleUpdater = ruleUpdater;
+ public RuleService(RuleIndex index, RuleDeleter ruleDeleter, UserSession userSession) {
this.index = index;
- this.ruleCreator = ruleCreator;
this.ruleDeleter = ruleDeleter;
this.userSession = userSession;
}
return index.search(query, options);
}
- public RuleKey create(NewRule newRule) {
- checkPermission();
- return ruleCreator.create(newRule);
- }
-
- public void update(RuleUpdate update) {
- checkPermission();
- ruleUpdater.update(update, userSession);
- }
-
public void delete(RuleKey ruleKey) {
checkPermission();
ruleDeleter.delete(ruleKey);
private boolean changeStatus = false;
private boolean changeParameters = false;
private boolean isCustomRule;
- private boolean isManual;
private Set<String> tags;
private String markdownNote;
private DebtRemediationFunction debtRemediationFunction;
}
public RuleUpdate setName(@Nullable String name) {
- checkCustomOrManualRule();
+ checkCustomRule();
this.name = name;
this.changeName = true;
return this;
}
public RuleUpdate setMarkdownDescription(@Nullable String markdownDescription) {
- checkCustomOrManualRule();
+ checkCustomRule();
this.markdownDescription = markdownDescription;
this.changeDescription = true;
return this;
}
public RuleUpdate setSeverity(@Nullable String severity) {
- checkCustomOrManualRule();
+ checkCustomRule();
this.severity = severity;
this.changeSeverity = true;
return this;
}
}
- private void checkCustomOrManualRule() {
- if (!isCustomRule && !isManual) {
- throw new IllegalStateException("Not a custom or a manual rule");
- }
- }
-
/**
* Use to update a rule provided by a plugin (name, description, severity, status and parameters cannot by changed)
*/
public static RuleUpdate createForPluginRule(RuleKey ruleKey) {
RuleUpdate ruleUpdate = new RuleUpdate(ruleKey);
ruleUpdate.isCustomRule = false;
- ruleUpdate.isManual = false;
return ruleUpdate;
}
public static RuleUpdate createForCustomRule(RuleKey ruleKey) {
RuleUpdate ruleUpdate = new RuleUpdate(ruleKey);
ruleUpdate.isCustomRule = true;
- ruleUpdate.isManual = false;
- return ruleUpdate;
- }
-
- /**
- * Use to update a manual rule (status and parameters cannot by changed)
- */
- public static RuleUpdate createForManualRule(RuleKey ruleKey) {
- RuleUpdate ruleUpdate = new RuleUpdate(ruleKey);
- ruleUpdate.isManual = true;
- ruleUpdate.isCustomRule = false;
return ruleUpdate;
}
*/
public class RuleDoc extends BaseDoc {
- public static final String MANUAL_REPOSITORY = "manual";
-
public RuleDoc(Map<String, Object> fields) {
super(fields);
}
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
-import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.rule.NewRule;
+import org.sonar.server.rule.NewCustomRule;
import org.sonar.server.rule.ReactivationException;
import org.sonar.server.rule.RuleCreator;
import org.sonarqube.ws.Rules;
public class CreateAction implements RulesWsAction {
public static final String PARAM_CUSTOM_KEY = "custom_key";
- public static final String PARAM_MANUAL_KEY = "manual_key";
public static final String PARAM_NAME = "name";
public static final String PARAM_DESCRIPTION = "markdown_description";
public static final String PARAM_SEVERITY = "severity";
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("create")
- .setDescription("Create a custom rule or a manual rule")
+ .setDescription("Create a custom rule. <br/>" +
+ "Since 5.5, it's no more possible to create manual rule.")
.setSince("4.4")
.setPost(true)
.setHandler(this);
action
.createParam(PARAM_CUSTOM_KEY)
.setDescription("Key of the custom rule")
- .setExampleValue("Todo_should_not_be_used");
+ .setExampleValue("Todo_should_not_be_used")
+ .setRequired(true);
action
- .createParam(PARAM_MANUAL_KEY)
- .setDescription("Key of the manual rule")
- .setExampleValue("Error_handling");
+ .createParam("manual_key")
+ .setDescription("Manual rules are no more supported. This parameter is ignored")
+ .setExampleValue("Error_handling")
+ .setDeprecatedSince("5.5");
action
.createParam(PARAM_TEMPLATE_KEY)
action
.createParam(PARAM_SEVERITY)
- .setDescription("Rule severity (Only for custom rule)")
+ .setDescription("Rule severity")
.setPossibleValues(Severity.ALL);
action
.createParam(PARAM_STATUS)
- .setDescription("Rule status (Only for custom rule)")
+ .setDescription("Rule status")
.setDefaultValue(RuleStatus.READY)
.setPossibleValues(RuleStatus.values());
@Override
public void handle(Request request, Response response) throws Exception {
- String customKey = request.param(PARAM_CUSTOM_KEY);
- String manualKey = request.param(PARAM_MANUAL_KEY);
- if (isNullOrEmpty(customKey) && isNullOrEmpty(manualKey)) {
- throw new BadRequestException(String.format("Either '%s' or '%s' parameters should be set", PARAM_CUSTOM_KEY, PARAM_MANUAL_KEY));
- }
+ String customKey = request.mandatoryParam(PARAM_CUSTOM_KEY);
DbSession dbSession = dbClient.openSession(false);
try {
try {
- if (!isNullOrEmpty(customKey)) {
- NewRule newRule = NewRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
- .setName(request.mandatoryParam(PARAM_NAME))
- .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
- .setSeverity(request.mandatoryParam(PARAM_SEVERITY))
- .setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS)))
- .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
- String params = request.param(PARAMS);
- if (!isNullOrEmpty(params)) {
- newRule.setParameters(KeyValueFormat.parse(params));
- }
- writeResponse(dbSession, request, response, ruleCreator.create(newRule));
- }
-
- if (!isNullOrEmpty(manualKey)) {
- NewRule newRule = NewRule.createForManualRule(manualKey)
- .setName(request.mandatoryParam(PARAM_NAME))
- .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
- .setSeverity(request.param(PARAM_SEVERITY))
- .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
- writeResponse(dbSession, request, response, ruleCreator.create(newRule));
+ NewCustomRule newRule = NewCustomRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
+ .setName(request.mandatoryParam(PARAM_NAME))
+ .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
+ .setSeverity(request.mandatoryParam(PARAM_SEVERITY))
+ .setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS)))
+ .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
+ String params = request.param(PARAMS);
+ if (!isNullOrEmpty(params)) {
+ newRule.setParameters(KeyValueFormat.parse(params));
}
+ writeResponse(dbSession, request, response, ruleCreator.create(newRule));
} catch (ReactivationException e) {
write409(dbSession, request, response, e.ruleKey());
}
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("delete")
- .setDescription("Delete custom rule or manual rule")
+ .setDescription("Delete custom rule")
.setSince("4.4")
.setPost(true)
.setHandler(this);
.setDeprecatedSince("5.5");
action.createParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER)
- .setDeprecatedSince("Gap multiplier of the remediation function of the rule")
+ .setDescription("Gap multiplier of the remediation function of the rule")
.setExampleValue("3min")
.setSince("5.5");
action
.createParam(PARAM_NAME)
- .setDescription("Rule name (mandatory for custom rule and manual rule)")
+ .setDescription("Rule name (mandatory for custom rule)")
.setExampleValue("My custom rule");
action
RuleDto rule = optionalRule.get();
if (rule.getTemplateId() != null) {
return RuleUpdate.createForCustomRule(key);
- } else if (RuleKey.MANUAL_REPOSITORY_KEY.equals(rule.getRepositoryKey())) {
- return RuleUpdate.createForManualRule(key);
} else {
return RuleUpdate.createForPluginRule(key);
}
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
-import org.sonar.db.rule.RuleTesting;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
.setSeverity(2)
.setStatus(RuleStatus.READY);
- RuleDto manualRule = RuleTesting.newManualRule("Manual_Rule").setName("Manual Rule");
-
DefaultRuleFinder underTest = new DefaultRuleFinder(dbClient);
@Before
dbClient.ruleDao().insert(session, rule2);
dbClient.ruleDao().insert(session, rule3);
dbClient.ruleDao().insert(session, rule4);
- dbClient.ruleDao().insert(session, manualRule);
session.commit();
}
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey("checkstyle"))).hasSize(2);
// find_all_enabled
- assertThat(underTest.findAll(RuleQuery.create())).extracting("id").containsOnly(rule1.getId(), rule3.getId(), rule4.getId(), manualRule.getId());
- assertThat(underTest.findAll(RuleQuery.create())).hasSize(4);
+ assertThat(underTest.findAll(RuleQuery.create())).extracting("id").containsOnly(rule1.getId(), rule3.getId(), rule4.getId());
+ assertThat(underTest.findAll(RuleQuery.create())).hasSize(3);
// do_not_find_disabled_rules
assertThat(underTest.findByKey("checkstyle", "DisabledCheck")).isNull();
@Test
public void find_all_not_include_removed_rule() {
// find rule with id 2 is REMOVED
- assertThat(underTest.findAll(RuleQuery.create())).extracting("id").containsOnly(rule1.getId(), rule3.getId(), rule4.getId(), manualRule.getId());
- }
-
- @Test
- public void find_manual_rule() {
- // find by id
- assertThat(underTest.findById(manualRule.getId())).isNotNull();
-
- // find by key
- Rule rule = underTest.findByKey("manual", "Manual_Rule");
- assertThat(rule).isNotNull();
- assertThat(rule.isEnabled()).isTrue();
+ assertThat(underTest.findAll(RuleQuery.create())).extracting("id").containsOnly(rule1.getId(), rule3.getId(), rule4.getId());
}
}
RuleDto template = ruleDao.selectOrFailByKey(dbSession, RuleKey.of("xoo", "T1"));
// Create custom rule
- RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewRule.createForCustomRule("CUSTOM_RULE", template.getKey())
+ RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewCustomRule.createForCustomRule("CUSTOM_RULE", template.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto template = ruleDao.selectOrFailByKey(dbSession, RuleKey.of("xoo", "T1"));
// Create custom rule
- RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewRule.createForCustomRule("CUSTOM_RULE", template.getKey())
+ RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewCustomRule.createForCustomRule("CUSTOM_RULE", template.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto templateRule = ruleDao.selectOrFailByKey(dbSession, RuleKey.of("xoo", "T1"));
// Create custom rule
- RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto templateRule = ruleDao.selectOrFailByKey(dbSession, RuleKey.of("xoo", "T1"));
// Create custom rule
- RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
assertThat(ruleDao.selectOrFailByKey(dbSession, customRuleKey).getStatus()).isEqualTo(RuleStatus.READY);
}
- @Test
- public void do_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(ruleDao.selectOrFailByKey(dbSession, manualRuleKey).getStatus()).isEqualTo(RuleStatus.READY);
-
- // Restart
- register(null);
-
- // Verify manual rule is still ready
- assertThat(ruleDao.selectOrFailByKey(dbSession, manualRuleKey).getStatus()).isEqualTo(RuleStatus.READY);
- }
-
interface Rules {
void init(RulesDefinition.NewRepository repository);
}
verify(updater).update(any(RuleUpdate.class), any(ThreadLocalUserSession.class));
}
-
- @Test
- public void create_manual_rules() {
- service.createManualRule(ImmutableMap.<String, Object>of("manualKey", "MY_MANUAL"));
-
- verify(ruleService).create(any(NewRule.class));
- }
-
- @Test
- public void update_manual_rules() {
- service.updateManualRule(ImmutableMap.<String, Object>of("ruleKey", "manual:MY_MANUAL"));
-
- verify(ruleService).update(any(RuleUpdate.class));
- }
-
- @Test
- public void delete_manual_rules() {
- service.deleteManualRule("manual:MY_MANUAL");
-
- verify(ruleService).delete(RuleKey.of("manual", "MY_MANUAL"));
- }
}
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
-import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
RuleDto templateRule = createTemplateRule();
// Create custom rule
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
// Create custom rule
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto templateRule = createTemplateRuleWithTwoIntParams();
// Create custom rule
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
dbSession.clearCache();
// Create custom rule with same key, but with different values
- NewRule newRule = NewRule.createForCustomRule(key, templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey())
.setName("New name")
.setMarkdownDescription("New description")
.setSeverity(Severity.MAJOR)
dbSession.clearCache();
// Create custom rule with same key, but with different values
- NewRule newRule = NewRule.createForCustomRule(key, templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey())
.setName("New name")
.setHtmlDescription("New description")
.setSeverity(Severity.MAJOR)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("*INVALID*", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
RuleDto templateRule = createTemplateRule();
// Create a custom rule
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
try {
// Create another custom rule having same key
- newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My another custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setStatus(RuleStatus.READY)
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity("INVALID")
// insert template rule
RuleDto templateRule = createTemplateRule();
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
dbSession.commit();
// Create custom rule with unknown template rule
- NewRule newRule = NewRule.createForCustomRule("CUSTOM_RULE", rule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey())
.setName("My custom")
.setHtmlDescription("Some description")
.setSeverity(Severity.MAJOR)
}
}
- @Test
- public void create_manual_rule() {
- NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual")
- .setMarkdownDescription("Some description");
- RuleKey ruleKey = creator.create(newRule);
-
- dbSession.clearCache();
-
- RuleDto rule = db.ruleDao().selectOrFailByKey(dbSession, ruleKey);
- assertThat(rule).isNotNull();
- assertThat(rule.getKey()).isEqualTo(RuleKey.of("manual", "MANUAL_RULE"));
- assertThat(rule.getName()).isEqualTo("My manual");
- assertThat(rule.getDescription()).isEqualTo("Some description");
- assertThat(rule.getSeverityString()).isNull();
- assertThat(rule.getStatus()).isEqualTo(RuleStatus.READY);
- assertThat(rule.getLanguage()).isNull();
- assertThat(rule.getConfigKey()).isNull();
- assertThat(rule.getDefaultRemediationBaseEffort()).isNull();
- assertThat(rule.getTags()).isEmpty();
- assertThat(rule.getSystemTags()).isEmpty();
-
- assertThat(db.ruleDao().selectRuleParamsByRuleKey(dbSession, ruleKey)).isEmpty();
-
- assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getIds()).containsOnly(ruleKey);
- }
-
- @Test
- public void create_manual_rule_with_severity() {
- NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual")
- .setMarkdownDescription("Some description")
- .setSeverity(Severity.BLOCKER);
- RuleKey ruleKey = creator.create(newRule);
-
- dbSession.clearCache();
-
- RuleDto rule = db.ruleDao().selectOrFailByKey(dbSession, ruleKey);
- assertThat(rule).isNotNull();
- assertThat(rule.getKey()).isEqualTo(RuleKey.of("manual", "MANUAL_RULE"));
- assertThat(rule.getName()).isEqualTo("My manual");
- assertThat(rule.getDescription()).isEqualTo("Some description");
- assertThat(rule.getSeverityString()).isEqualTo(Severity.BLOCKER);
- assertThat(rule.getStatus()).isEqualTo(RuleStatus.READY);
- assertThat(rule.getLanguage()).isNull();
- assertThat(rule.getConfigKey()).isNull();
- assertThat(rule.getDefaultRemediationFunction()).isNull();
- assertThat(rule.getTags()).isEmpty();
- assertThat(rule.getSystemTags()).isEmpty();
-
- assertThat(db.ruleDao().selectRuleParamsByRuleKey(dbSession, ruleKey)).isEmpty();
- }
-
- @Test
- public void reactivate_manual_rule_if_already_exists_in_removed_status() {
- String key = "MANUAL_RULE";
-
- // insert a removed rule
- RuleDto rule = RuleTesting.newManualRule(key)
- .setStatus(RuleStatus.REMOVED)
- .setName("Old name")
- .setDescription("Old description")
- .setSeverity(Severity.INFO)
- .setType(RuleType.CODE_SMELL);
- dao.insert(dbSession, rule);
- dbSession.commit();
- dbSession.clearCache();
-
- // Create a rule with the same key and with another name, description and severity
- NewRule newRule = NewRule.createForManualRule(key)
- .setName("New name")
- .setMarkdownDescription("New description");
- RuleKey ruleKey = creator.create(newRule);
-
- dbSession.clearCache();
-
- RuleDto result = db.ruleDao().selectOrFailByKey(dbSession, ruleKey);
- assertThat(result.getKey()).isEqualTo(RuleKey.of("manual", key));
- assertThat(result.getStatus()).isEqualTo(RuleStatus.READY);
-
- // Name, description and severity should be the same than before
- assertThat(result.getName()).isEqualTo("Old name");
- assertThat(result.getDescription()).isEqualTo("Old description");
- assertThat(result.getSeverityString()).isEqualTo(Severity.INFO);
- }
-
- @Test
- public void fail_to_create_manual_rule_when_missing_key() {
- try {
- NewRule.createForManualRule("")
- .setName("My manual")
- .setHtmlDescription("Some description");
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Manual key should be set");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_when_invalid_key() {
- NewRule newRule = NewRule.createForManualRule("*INVALID*")
- .setName("My custom")
- .setHtmlDescription("Some description");
-
- try {
- creator.create(newRule);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("coding_rules.validation.invalid_rule_key");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_when_rule_key_already_exists() {
- NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual")
- .setHtmlDescription("Some description");
- creator.create(newRule);
-
- try {
- // Create another rule having same key
- newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setName("My other manual")
- .setHtmlDescription("Some description");
- creator.create(newRule);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("A rule with the key 'MANUAL_RULE' already exists");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_when_missing_name() {
- NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setHtmlDescription("Some description");
-
- try {
- creator.create(newRule);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("coding_rules.validation.missing_name");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_when_missing_description() {
- NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual");
-
- try {
- creator.create(newRule);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("coding_rules.validation.missing_description");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_with_status() {
- try {
- NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual")
- .setHtmlDescription("Some description")
- .setStatus(RuleStatus.BETA);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
- }
- }
-
- @Test
- public void fail_to_create_manual_rule_with_parameters() {
- try {
- NewRule.createForManualRule("MANUAL_RULE")
- .setName("My manual")
- .setHtmlDescription("Some description")
- .setParameters(ImmutableMap.of("regex", "a.*"));
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
- }
- }
-
private RuleDto createTemplateRule() {
RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001"))
.setIsTemplate(true)
}
@Test
- public void delete_manual_rule() {
- // Create manual rule
- RuleDto manualRule = RuleTesting.newManualRule("Manual_Rule")
- .setCreatedAt(PAST)
- .setUpdatedAt(PAST);
- dao.insert(dbSession, manualRule);
- dbSession.commit();
- ruleIndexer.index();
-
- // Delete manual rule
- deleter.delete(manualRule.getKey());
-
- // Verify custom rule have status REMOVED
- RuleDto result = dao.selectOrFailByKey(dbSession, manualRule.getKey());
- assertThat(result).isNotNull();
- assertThat(result.getStatus()).isEqualTo(RuleStatus.REMOVED);
- assertThat(result.getUpdatedAt()).isNotEqualTo(PAST);
-
- // Verify in index
- assertThat(index.search(new RuleQuery(), new SearchOptions()).getIds()).isEmpty();
- }
-
- @Test
- public void fail_to_delete_if_not_custom_or_not_manual() {
+ public void fail_to_delete_if_not_custom() {
// Create rule
RuleKey ruleKey = RuleKey.of("java", "S001");
dao.insert(dbSession, RuleTesting.newDto(ruleKey));
// Delete rule
deleter.delete(ruleKey);
} catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Only custom rules and manual rules can be deleted");
+ assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Only custom rules can be deleted");
}
}
*/
package org.sonar.server.rule;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.Set;
import org.junit.ClassRule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rule.RuleStatus;
-import org.sonar.api.rule.Severity;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.rule.index.RuleIndex;
assertThat(tags).containsOnly("tag1", "tag2", "sys1", "sys2");
}
- @Test
- public void create_rule() {
- userSessionRule.login().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
-
- // Create template rule
- RuleKey templateRuleKey = RuleKey.of("java", "S001");
- dao.insert(dbSession, RuleTesting.newTemplateRule(templateRuleKey));
- dbSession.commit();
-
- // Create custom rule
- NewRule newRule = NewRule.createForCustomRule("MY_CUSTOM", templateRuleKey)
- .setName("My custom")
- .setHtmlDescription("Some description")
- .setSeverity(Severity.MAJOR)
- .setStatus(RuleStatus.READY)
- .setParameters(ImmutableMap.of("regex", "a.*"));
- RuleKey customRuleKey = service.create(newRule);
-
- dbSession.clearCache();
-
- RuleDto rule = dao.selectOrFailByKey(dbSession, customRuleKey);
- assertThat(rule).isNotNull();
- }
-
- @Test(expected = UnauthorizedException.class)
- public void do_not_create_if_not_granted() {
- userSessionRule.setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
-
- service.create(NewRule.createForCustomRule("MY_CUSTOM", RuleKey.of("java", "S001")));
- }
-
- @Test
- public void delete_rule() {
- userSessionRule.login().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
-
- // Create template rule
- RuleKey templateRuleKey = RuleKey.of("java", "S001");
- dao.insert(dbSession, RuleTesting.newTemplateRule(templateRuleKey));
- dbSession.commit();
-
- // Create custom rule
- NewRule newRule = NewRule.createForCustomRule("MY_CUSTOM", templateRuleKey)
- .setName("My custom")
- .setHtmlDescription("Some description")
- .setSeverity(Severity.MAJOR)
- .setStatus(RuleStatus.READY)
- .setParameters(ImmutableMap.of("regex", "a.*"));
- RuleKey customRuleKey = service.create(newRule);
-
- // Delete custom rule
- service.delete(customRuleKey);
- }
-
@Test(expected = UnauthorizedException.class)
public void do_not_delete_if_not_granted() {
userSessionRule.setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
-import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.db.DbClient;
List<ActiveRuleParamDto> activeRuleParams = db.activeRuleDao().selectParamsByActiveRuleId(dbSession, activeRuleDto.getId());
// FIXME why 4 parameters are returned ??? (This issue already exists in 5.4)
- //assertThat(activeRuleParams).hasSize(2);
+ // assertThat(activeRuleParams).hasSize(2);
Map<String, ActiveRuleParamDto> activeRuleParamsByKey = ActiveRuleParamDto.groupByKey(activeRuleParams);
assertThat(activeRuleParamsByKey.get("regex").getValue()).isEqualTo("b.*");
assertThat(activeRuleParamsByKey.get("message").getValue()).isEqualTo("a message");
}
}
- @Test
- public void update_manual_rule() {
- // Create manual rule
- RuleDto manualRule = RuleTesting.newManualRule("My manual")
- .setName("Old name")
- .setDescription("Old description")
- .setSeverity(Severity.INFO)
- .setType(RuleType.CODE_SMELL);
- ruleDao.insert(dbSession, manualRule);
-
- dbSession.commit();
-
- // Update manual rule
- RuleUpdate update = RuleUpdate.createForManualRule(manualRule.getKey())
- .setName("New name")
- .setMarkdownDescription("New description")
- .setSeverity(Severity.CRITICAL);
- underTest.update(update, userSessionRule);
-
- dbSession.clearCache();
-
- // Verify manual rule is updated
- RuleDto manualRuleReloaded = ruleDao.selectOrFailByKey(dbSession, manualRule.getKey());
- assertThat(manualRuleReloaded).isNotNull();
- assertThat(manualRuleReloaded.getName()).isEqualTo("New name");
- assertThat(manualRuleReloaded.getDescription()).isEqualTo("New description");
- assertThat(manualRuleReloaded.getSeverityString()).isEqualTo(Severity.CRITICAL);
-
- // Verify in index
- assertThat(ruleIndex.search(new RuleQuery().setQueryText("New name"), new SearchOptions()).getIds()).containsOnly(manualRule.getKey());
- assertThat(ruleIndex.search(new RuleQuery().setQueryText("New description"), new SearchOptions()).getIds()).containsOnly(manualRule.getKey());
-
- assertThat(ruleIndex.search(new RuleQuery().setQueryText("Old name"), new SearchOptions()).getTotal()).isZero();
- assertThat(ruleIndex.search(new RuleQuery().setQueryText("Old description"), new SearchOptions()).getTotal()).isZero();
- }
-
- @Test
- public void fail_to_update_manual_rule_if_status_is_set() {
- // Create manual rule
- RuleDto manualRule = RuleTesting.newManualRule("My manual");
- ruleDao.insert(dbSession, manualRule);
-
- dbSession.commit();
-
- try {
- // Update manual rule
- RuleUpdate.createForManualRule(manualRule.getKey())
- .setStatus(RuleStatus.BETA);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
- }
- }
-
- @Test
- public void fail_to_update_manual_rule_if_parameters_are_set() {
- // Create manual rule
- RuleDto manualRule = RuleTesting.newManualRule("My manual");
- ruleDao.insert(dbSession, manualRule);
-
- dbSession.commit();
-
- try {
- // Update manual rule
- RuleUpdate.createForManualRule(manualRule.getKey())
- .setStatus(RuleStatus.BETA)
- .setParameters(ImmutableMap.of("regex", "b.*", "message", "a message"));
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
- }
- }
-
@Test
public void fail_to_update_plugin_rule_if_name_is_set() {
// Create rule rule
.setName("New name");
fail();
} catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom or a manual rule");
+ assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
}
}
.setMarkdownDescription("New description");
fail();
} catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom or a manual rule");
+ assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
}
}
.setSeverity(Severity.CRITICAL);
fail();
} catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom or a manual rule");
+ assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not a custom rule");
}
}
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
-import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.tester.ServerTester;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsTester;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
-
@RunWith(MockitoJUnitRunner.class)
public class CreateActionMediumTest {
}
@Test
- public void create_manual_rule() throws Exception {
- WsTester.TestRequest request = wsTester.newPostRequest("api/rules", "create")
- .setParam("manual_key", "MY_MANUAL")
- .setParam("name", "My manual rule")
- .setParam("markdown_description", "Description")
- .setParam("severity", "MAJOR");
- request.execute().assertJson(getClass(), "create_manual_rule.json");
- }
-
- @Test
- public void create_manual_rule_without_severity() throws Exception {
- WsTester.TestRequest request = wsTester.newPostRequest("api/rules", "create")
- .setParam("manual_key", "MY_MANUAL")
- .setParam("name", "My manual rule")
- .setParam("markdown_description", "Description");
- request.execute().assertJson(getClass(), "create_manual_rule_without_severity.json");
- }
-
- @Test
- public void fail_if_custom_key_and_manual_key_parameters_are_not_set() {
- WsTester.TestRequest request = wsTester.newPostRequest("api/rules", "create")
- .setParam("key", "MY_MANUAL")
- .setParam("name", "My manual rule")
- .setParam("markdown_description", "Description")
- .setParam("severity", "MAJOR");
-
- try {
- request.execute();
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("Either 'custom_key' or 'manual_key' parameters should be set");
- }
- }
-
- @Test
- public void create_manual_rule_with_prevent_reactivation_param_to_true() throws Exception {
- String key = "MY_MANUAL";
+ public void create_custom_rule_with_prevent_reactivation_param_to_true() throws Exception {
+ RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
+ ruleDao.insert(session, templateRule);
// insert a removed rule
- tester.get(RuleDao.class).insert(session, RuleTesting.newManualRule(key)
+ RuleDto customRule = RuleTesting.newCustomRule(templateRule)
+ .setRuleKey("MY_CUSTOM")
.setStatus(RuleStatus.REMOVED)
- .setName("My manual rule")
+ .setName("My custom rule")
.setDescription("Description")
.setDescriptionFormat(RuleDto.Format.MARKDOWN)
- .setSeverity(Severity.MAJOR));
+ .setSeverity(Severity.MAJOR);
+ tester.get(RuleDao.class).insert(session, customRule);
session.commit();
- session.clearCache();
WsTester.TestRequest request = wsTester.newPostRequest("api/rules", "create")
- .setParam("manual_key", key)
- .setParam("name", "My manual rule")
+ .setParam("custom_key", "MY_CUSTOM")
+ .setParam("template_key", templateRule.getKey().toString())
+ .setParam("name", "My custom rule")
.setParam("markdown_description", "Description")
.setParam("severity", "MAJOR")
.setParam("prevent_reactivation", "true");
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
-import org.sonar.server.rule.NewRule;
+import org.sonar.server.rule.NewCustomRule;
+import org.sonar.server.rule.RuleCreator;
import org.sonar.server.rule.RuleService;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.ServerTester;
session.commit();
// Custom rule
- NewRule customRule = NewRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
+ NewCustomRule customRule = NewCustomRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
.setName("My custom")
.setSeverity(MINOR)
.setStatus(RuleStatus.READY)
.setMarkdownDescription("<div>line1\nline2</div>");
- RuleKey customRuleKey = ruleService.create(customRule);
+ RuleKey customRuleKey = tester.get(RuleCreator.class).create(customRule);
session.clearCache();
WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
request.execute().assertJson(getClass(), "encode_html_description_of_custom_rule.json");
}
- @Test
- public void encode_html_description_of_manual_rule() throws Exception {
- // Manual rule
- NewRule manualRule = NewRule.createForManualRule("MY_MANUAL")
- .setName("My manual")
- .setSeverity(MINOR)
- .setMarkdownDescription("<div>line1\nline2</div>");
- RuleKey customRuleKey = ruleService.create(manualRule);
- session.clearCache();
-
- WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
- .setParam("key", customRuleKey.toString());
- request.execute().assertJson(getClass(), "encode_html_description_of_manual_rule.json");
- }
-
@Test
public void show_deprecated_rule_rem_function_fields() throws Exception {
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"))
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
-import org.sonar.server.rule.NewRule;
+import org.sonar.server.rule.NewCustomRule;
+import org.sonar.server.rule.RuleCreator;
import org.sonar.server.rule.RuleService;
import org.sonar.server.tester.ServerTester;
import org.sonar.server.tester.UserSessionRule;
public static ServerTester tester = new ServerTester().withEsIndexes();
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).
- login().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
+ public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).login().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
WsTester wsTester;
.setParam("key", rule.getKey().toString())
.setParam(PARAM_REMEDIATION_FN_TYPE, LINEAR_OFFSET.toString())
.setParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER, "15d")
- .setParam(PARAM_REMEDIATION_FN_BASE_EFFORT, "5min")
- ;
+ .setParam(PARAM_REMEDIATION_FN_BASE_EFFORT, "5min");
request.execute().assertJson(getClass(), "update_rule_remediation_function.json");
}
session.commit();
// Custom rule
- NewRule newRule = NewRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
+ NewCustomRule newRule = NewCustomRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
.setName("Old custom")
.setHtmlDescription("Old description")
.setSeverity(Severity.MINOR)
.setStatus(RuleStatus.BETA)
.setParameters(ImmutableMap.of("regex", "a"));
- RuleKey customRuleKey = ruleService.create(newRule);
+
+ RuleKey customRuleKey = tester.get(RuleCreator.class).create(newRule);
session.clearCache();
WsTester.TestRequest request = wsTester.newPostRequest("api/rules", "update")
+++ /dev/null
-{
- "rule": {
- "key": "manual:MY_MANUAL",
- "repo": "manual",
- "name": "My manual rule",
- "htmlDesc": "Description",
- "severity": "MAJOR",
- "status": "READY",
- "isTemplate": false,
- "tags": [],
- "sysTags": [],
- "params": []
- }
-}
+++ /dev/null
-{
- "rule": {
- "key": "manual:MY_MANUAL",
- "repo": "manual",
- "name": "My manual rule",
- "htmlDesc": "Description",
- "status": "READY",
- "isTemplate": false,
- "tags": [],
- "sysTags": [],
- "params": []
- }
-}
{
"rule": {
- "key": "manual:MY_MANUAL",
- "repo": "manual",
- "name": "My manual rule",
+ "key": "java:MY_CUSTOM",
+ "repo": "java",
+ "name": "My custom rule",
"htmlDesc": "Description",
"severity": "MAJOR",
"status": "REMOVED",
- "isTemplate": false,
- "tags": [],
- "sysTags": [],
- "params": []
+ "isTemplate": false
}
}
+++ /dev/null
-{
- "rule": {
- "key": "manual:MY_MANUAL",
- "htmlDesc": "<div>line1<br/>line2</div>"
- }
-}
.setType(templateRule.getType());
}
- public static RuleDto newManualRule(String manualKey) {
- return new RuleDto().setRuleKey(manualKey)
- .setName("Name " + manualKey)
- .setRepositoryKey(RuleKey.MANUAL_REPOSITORY_KEY)
- .setDescription("Description " + manualKey)
- .setStatus(RuleStatus.READY)
- .setType(RuleType.CODE_SMELL);
- }
-
}