You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CreateAction.java 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.rule.ws;
  21. import com.google.common.io.Resources;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.Collections;
  25. import java.util.List;
  26. import java.util.Optional;
  27. import org.sonar.api.rule.RuleKey;
  28. import org.sonar.api.rule.RuleStatus;
  29. import org.sonar.api.rule.Severity;
  30. import org.sonar.api.rules.RuleType;
  31. import org.sonar.api.server.ws.Change;
  32. import org.sonar.api.server.ws.Request;
  33. import org.sonar.api.server.ws.Response;
  34. import org.sonar.api.server.ws.WebService;
  35. import org.sonar.api.utils.KeyValueFormat;
  36. import org.sonar.db.DbClient;
  37. import org.sonar.db.DbSession;
  38. import org.sonar.db.rule.RuleDto;
  39. import org.sonar.db.rule.RuleParamDto;
  40. import org.sonar.server.rule.NewCustomRule;
  41. import org.sonar.server.rule.ReactivationException;
  42. import org.sonar.server.rule.RuleCreator;
  43. import org.sonarqube.ws.Rules;
  44. import static com.google.common.base.Strings.isNullOrEmpty;
  45. import static java.net.HttpURLConnection.HTTP_CONFLICT;
  46. import static java.util.Collections.singletonList;
  47. import static java.util.Optional.ofNullable;
  48. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  49. public class CreateAction implements RulesWsAction {
  50. public static final String PARAM_CUSTOM_KEY = "customKey";
  51. public static final String PARAM_NAME = "name";
  52. public static final String PARAM_DESCRIPTION = "markdownDescription";
  53. public static final String PARAM_SEVERITY = "severity";
  54. public static final String PARAM_STATUS = "status";
  55. public static final String PARAM_TEMPLATE_KEY = "templateKey";
  56. public static final String PARAM_TYPE = "type";
  57. public static final String PARAMS = "params";
  58. public static final String PARAM_PREVENT_REACTIVATION = "preventReactivation";
  59. static final int KEY_MAXIMUM_LENGTH = 200;
  60. static final int NAME_MAXIMUM_LENGTH = 200;
  61. private final DbClient dbClient;
  62. private final RuleCreator ruleCreator;
  63. private final RuleMapper ruleMapper;
  64. private final RuleWsSupport ruleWsSupport;
  65. public CreateAction(DbClient dbClient, RuleCreator ruleCreator, RuleMapper ruleMapper, RuleWsSupport ruleWsSupport) {
  66. this.dbClient = dbClient;
  67. this.ruleCreator = ruleCreator;
  68. this.ruleMapper = ruleMapper;
  69. this.ruleWsSupport = ruleWsSupport;
  70. }
  71. @Override
  72. public void define(WebService.NewController controller) {
  73. WebService.NewAction action = controller
  74. .createAction("create")
  75. .setPost(true)
  76. .setDescription("Create a custom rule.<br>" +
  77. "Requires the 'Administer Quality Profiles' permission")
  78. .setResponseExample(Resources.getResource(getClass(), "create-example.json"))
  79. .setSince("4.4")
  80. .setChangelog(
  81. new Change("5.5", "Creating manual rule is not more possible"),
  82. new Change("10.0","Drop deprecated keys: 'custom_key', 'template_key', 'markdown_description', 'prevent_reactivation'"),
  83. new Change("10.2", "Add 'impacts', 'cleanCodeAttribute', 'cleanCodeAttributeCategory' fields to the response")
  84. )
  85. .setHandler(this);
  86. action
  87. .createParam(PARAM_CUSTOM_KEY)
  88. .setRequired(true)
  89. .setMaximumLength(KEY_MAXIMUM_LENGTH)
  90. .setDescription("Key of the custom rule")
  91. .setExampleValue("Todo_should_not_be_used");
  92. action
  93. .createParam(PARAM_TEMPLATE_KEY)
  94. .setRequired(true)
  95. .setDescription("Key of the template rule in order to create a custom rule (mandatory for custom rule)")
  96. .setExampleValue("java:XPath");
  97. action
  98. .createParam(PARAM_NAME)
  99. .setRequired(true)
  100. .setMaximumLength(NAME_MAXIMUM_LENGTH)
  101. .setDescription("Rule name")
  102. .setExampleValue("My custom rule");
  103. action
  104. .createParam(PARAM_DESCRIPTION)
  105. .setRequired(true)
  106. .setDescription("Rule description in <a href='/formatting/help'>markdown format</a>")
  107. .setExampleValue("Description of my custom rule");
  108. action
  109. .createParam(PARAM_SEVERITY)
  110. .setPossibleValues(Severity.ALL)
  111. .setDefaultValue(Severity.MAJOR)
  112. .setDescription("Rule severity");
  113. action
  114. .createParam(PARAM_STATUS)
  115. .setPossibleValues(
  116. Arrays.stream(RuleStatus.values())
  117. .filter(status -> !RuleStatus.REMOVED.equals(status))
  118. .toList())
  119. .setDefaultValue(RuleStatus.READY)
  120. .setDescription("Rule status");
  121. action.createParam(PARAMS)
  122. .setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only for custom rule)");
  123. action
  124. .createParam(PARAM_PREVENT_REACTIVATION)
  125. .setBooleanPossibleValues()
  126. .setDefaultValue(false)
  127. .setDescription("If set to true and if the rule has been deactivated (status 'REMOVED'), a status 409 will be returned");
  128. action.createParam(PARAM_TYPE)
  129. .setPossibleValues(RuleType.names())
  130. .setDescription("Rule type")
  131. .setSince("6.7");
  132. }
  133. @Override
  134. public void handle(Request request, Response response) throws Exception {
  135. ruleWsSupport.checkQProfileAdminPermission();
  136. String customKey = request.mandatoryParam(PARAM_CUSTOM_KEY);
  137. try (DbSession dbSession = dbClient.openSession(false)) {
  138. try {
  139. NewCustomRule newRule = NewCustomRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
  140. .setName(request.mandatoryParam(PARAM_NAME))
  141. .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
  142. .setSeverity(request.mandatoryParam(PARAM_SEVERITY))
  143. .setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS)))
  144. .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
  145. String params = request.param(PARAMS);
  146. if (!isNullOrEmpty(params)) {
  147. newRule.setParameters(KeyValueFormat.parse(params));
  148. }
  149. ofNullable(request.param(PARAM_TYPE)).ifPresent(t -> newRule.setType(RuleType.valueOf(t)));
  150. writeResponse(dbSession, request, response, ruleCreator.create(dbSession, newRule));
  151. } catch (ReactivationException e) {
  152. response.stream().setStatus(HTTP_CONFLICT);
  153. writeResponse(dbSession, request, response, e.ruleKey());
  154. }
  155. }
  156. }
  157. private void writeResponse(DbSession dbSession, Request request, Response response, RuleKey ruleKey) {
  158. writeProtobuf(createResponse(dbSession, ruleKey), request, response);
  159. }
  160. private Rules.CreateResponse createResponse(DbSession dbSession, RuleKey ruleKey) {
  161. RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, ruleKey)
  162. .orElseThrow(() -> new IllegalStateException(String.format("Cannot load rule, that has just been created '%s'", ruleKey)));
  163. List<RuleDto> templateRules = new ArrayList<>();
  164. if (rule.isCustomRule()) {
  165. Optional<RuleDto> templateRule = dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession);
  166. templateRule.ifPresent(templateRules::add);
  167. }
  168. List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid()));
  169. SearchAction.SearchResult searchResult = new SearchAction.SearchResult()
  170. .setRuleParameters(ruleParameters)
  171. .setTemplateRules(templateRules)
  172. .setTotal(1L);
  173. return Rules.CreateResponse.newBuilder()
  174. .setRule(ruleMapper.toWsRule(rule, searchResult, Collections.emptySet()))
  175. .build();
  176. }
  177. }