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 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 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.Collections;
  24. import java.util.List;
  25. import java.util.Optional;
  26. import org.sonar.api.rule.RuleKey;
  27. import org.sonar.api.rule.RuleStatus;
  28. import org.sonar.api.rule.Severity;
  29. import org.sonar.api.rules.RuleType;
  30. import org.sonar.api.server.ws.Change;
  31. import org.sonar.api.server.ws.Request;
  32. import org.sonar.api.server.ws.Response;
  33. import org.sonar.api.server.ws.WebService;
  34. import org.sonar.api.utils.KeyValueFormat;
  35. import org.sonar.db.DbClient;
  36. import org.sonar.db.DbSession;
  37. import org.sonar.db.rule.RuleDefinitionDto;
  38. import org.sonar.db.rule.RuleParamDto;
  39. import org.sonar.server.rule.NewCustomRule;
  40. import org.sonar.server.rule.ReactivationException;
  41. import org.sonar.server.rule.RuleCreator;
  42. import org.sonarqube.ws.Rules;
  43. import static com.google.common.base.Strings.isNullOrEmpty;
  44. import static java.net.HttpURLConnection.HTTP_CONFLICT;
  45. import static java.util.Collections.singletonList;
  46. import static java.util.Optional.ofNullable;
  47. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  48. public class CreateAction implements RulesWsAction {
  49. public static final String PARAM_CUSTOM_KEY = "custom_key";
  50. public static final String PARAM_NAME = "name";
  51. public static final String PARAM_DESCRIPTION = "markdown_description";
  52. public static final String PARAM_SEVERITY = "severity";
  53. public static final String PARAM_STATUS = "status";
  54. public static final String PARAM_TEMPLATE_KEY = "template_key";
  55. public static final String PARAM_TYPE = "type";
  56. public static final String PARAMS = "params";
  57. public static final String PARAM_PREVENT_REACTIVATION = "prevent_reactivation";
  58. static final int KEY_MAXIMUM_LENGTH = 200;
  59. static final int NAME_MAXIMUM_LENGTH = 200;
  60. private final DbClient dbClient;
  61. private final RuleCreator ruleCreator;
  62. private final RuleMapper ruleMapper;
  63. private final RuleWsSupport ruleWsSupport;
  64. public CreateAction(DbClient dbClient, RuleCreator ruleCreator, RuleMapper ruleMapper, RuleWsSupport ruleWsSupport) {
  65. this.dbClient = dbClient;
  66. this.ruleCreator = ruleCreator;
  67. this.ruleMapper = ruleMapper;
  68. this.ruleWsSupport = ruleWsSupport;
  69. }
  70. @Override
  71. public void define(WebService.NewController controller) {
  72. WebService.NewAction action = controller
  73. .createAction("create")
  74. .setPost(true)
  75. .setDescription("Create a custom rule.<br>" +
  76. "Requires the 'Administer Quality Profiles' permission")
  77. .setResponseExample(Resources.getResource(getClass(), "create-example.json"))
  78. .setSince("4.4")
  79. .setChangelog(
  80. new Change("5.5", "Creating manual rule is not more possible"))
  81. .setHandler(this);
  82. action
  83. .createParam(PARAM_CUSTOM_KEY)
  84. .setRequired(true)
  85. .setMaximumLength(KEY_MAXIMUM_LENGTH)
  86. .setDescription("Key of the custom rule")
  87. .setExampleValue("Todo_should_not_be_used");
  88. action
  89. .createParam("manual_key")
  90. .setDescription("Manual rules are no more supported. This parameter is ignored")
  91. .setExampleValue("Error_handling")
  92. .setDeprecatedSince("5.5");
  93. action
  94. .createParam(PARAM_TEMPLATE_KEY)
  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")
  107. .setExampleValue("Description of my custom rule");
  108. action
  109. .createParam(PARAM_SEVERITY)
  110. .setPossibleValues(Severity.ALL)
  111. .setDescription("Rule severity");
  112. action
  113. .createParam(PARAM_STATUS)
  114. .setPossibleValues(RuleStatus.values())
  115. .setDefaultValue(RuleStatus.READY)
  116. .setDescription("Rule status");
  117. action.createParam(PARAMS)
  118. .setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only for custom rule)");
  119. action
  120. .createParam(PARAM_PREVENT_REACTIVATION)
  121. .setBooleanPossibleValues()
  122. .setDefaultValue(false)
  123. .setDescription("If set to true and if the rule has been deactivated (status 'REMOVED'), a status 409 will be returned");
  124. action.createParam(PARAM_TYPE)
  125. .setPossibleValues(RuleType.names())
  126. .setDescription("Rule type")
  127. .setSince("6.7");
  128. }
  129. @Override
  130. public void handle(Request request, Response response) throws Exception {
  131. ruleWsSupport.checkQProfileAdminPermissionOnDefaultOrganization();
  132. String customKey = request.mandatoryParam(PARAM_CUSTOM_KEY);
  133. try (DbSession dbSession = dbClient.openSession(false)) {
  134. try {
  135. NewCustomRule newRule = NewCustomRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
  136. .setName(request.mandatoryParam(PARAM_NAME))
  137. .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
  138. .setSeverity(request.mandatoryParam(PARAM_SEVERITY))
  139. .setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS)))
  140. .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
  141. String params = request.param(PARAMS);
  142. if (!isNullOrEmpty(params)) {
  143. newRule.setParameters(KeyValueFormat.parse(params));
  144. }
  145. ofNullable(request.param(PARAM_TYPE)).ifPresent(t -> newRule.setType(RuleType.valueOf(t)));
  146. writeResponse(dbSession, request, response, ruleCreator.create(dbSession, newRule));
  147. } catch (ReactivationException e) {
  148. response.stream().setStatus(HTTP_CONFLICT);
  149. writeResponse(dbSession, request, response, e.ruleKey());
  150. }
  151. }
  152. }
  153. private void writeResponse(DbSession dbSession, Request request, Response response, RuleKey ruleKey) {
  154. writeProtobuf(createResponse(dbSession, ruleKey), request, response);
  155. }
  156. private Rules.CreateResponse createResponse(DbSession dbSession, RuleKey ruleKey) {
  157. RuleDefinitionDto rule = dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey)
  158. .orElseThrow(() -> new IllegalStateException(String.format("Cannot load rule, that has just been created '%s'", ruleKey)));
  159. List<RuleDefinitionDto> templateRules = new ArrayList<>();
  160. if (rule.isCustomRule()) {
  161. Optional<RuleDefinitionDto> templateRule = dbClient.ruleDao().selectDefinitionById(rule.getTemplateId(), dbSession);
  162. templateRule.ifPresent(templateRules::add);
  163. }
  164. List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleIds(dbSession, singletonList(rule.getId()));
  165. SearchAction.SearchResult searchResult = new SearchAction.SearchResult()
  166. .setRuleParameters(ruleParameters)
  167. .setTemplateRules(templateRules)
  168. .setTotal(1L);
  169. return Rules.CreateResponse.newBuilder()
  170. .setRule(ruleMapper.toWsRule(rule, searchResult, Collections.emptySet()))
  171. .build();
  172. }
  173. }