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.

UpdateAction.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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.base.Splitter;
  22. import com.google.common.io.Resources;
  23. import java.util.ArrayList;
  24. import java.util.Collections;
  25. import java.util.List;
  26. import org.apache.commons.lang.StringUtils;
  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.server.debt.DebtRemediationFunction;
  31. import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
  32. import org.sonar.api.server.ws.Change;
  33. import org.sonar.api.server.ws.Request;
  34. import org.sonar.api.server.ws.Response;
  35. import org.sonar.api.server.ws.WebService;
  36. import org.sonar.api.utils.KeyValueFormat;
  37. import org.sonar.db.DbClient;
  38. import org.sonar.db.DbSession;
  39. import org.sonar.db.rule.RuleDto;
  40. import org.sonar.db.rule.RuleParamDto;
  41. import org.sonar.server.exceptions.NotFoundException;
  42. import org.sonar.server.rule.RuleUpdate;
  43. import org.sonar.server.rule.RuleUpdater;
  44. import org.sonar.server.user.UserSession;
  45. import org.sonarqube.ws.Rules.UpdateResponse;
  46. import static com.google.common.collect.Sets.newHashSet;
  47. import static java.lang.String.format;
  48. import static java.util.Collections.emptyMap;
  49. import static java.util.Collections.singletonList;
  50. import static java.util.Optional.ofNullable;
  51. import static org.sonar.server.rule.ws.CreateAction.KEY_MAXIMUM_LENGTH;
  52. import static org.sonar.server.rule.ws.CreateAction.NAME_MAXIMUM_LENGTH;
  53. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  54. public class UpdateAction implements RulesWsAction {
  55. public static final String PARAM_KEY = "key";
  56. public static final String PARAM_TAGS = "tags";
  57. public static final String PARAM_MARKDOWN_NOTE = "markdown_note";
  58. public static final String PARAM_REMEDIATION_FN_TYPE = "remediation_fn_type";
  59. public static final String PARAM_REMEDIATION_FN_BASE_EFFORT = "remediation_fn_base_effort";
  60. public static final String PARAM_REMEDIATION_FN_GAP_MULTIPLIER = "remediation_fy_gap_multiplier";
  61. public static final String PARAM_NAME = "name";
  62. public static final String PARAM_DESCRIPTION = "markdownDescription";
  63. public static final String PARAM_SEVERITY = "severity";
  64. public static final String PARAM_STATUS = "status";
  65. public static final String PARAMS = "params";
  66. private final DbClient dbClient;
  67. private final RuleUpdater ruleUpdater;
  68. private final RuleMapper mapper;
  69. private final UserSession userSession;
  70. private final RuleWsSupport ruleWsSupport;
  71. public UpdateAction(DbClient dbClient, RuleUpdater ruleUpdater, RuleMapper mapper, UserSession userSession, RuleWsSupport ruleWsSupport) {
  72. this.dbClient = dbClient;
  73. this.ruleUpdater = ruleUpdater;
  74. this.mapper = mapper;
  75. this.userSession = userSession;
  76. this.ruleWsSupport = ruleWsSupport;
  77. }
  78. @Override
  79. public void define(WebService.NewController controller) {
  80. WebService.NewAction action = controller
  81. .createAction("update")
  82. .setPost(true)
  83. .setResponseExample(Resources.getResource(getClass(), "update-example.json"))
  84. .setDescription("Update an existing rule.<br>" +
  85. "Requires the 'Administer Quality Profiles' permission")
  86. .setChangelog(
  87. new Change("10.2", "The field 'severity' and 'type' in the response have been deprecated, use 'impacts' instead.")
  88. )
  89. .setSince("4.4")
  90. .setChangelog(
  91. new Change("10.2", "Add 'impacts', 'cleanCodeAttribute', 'cleanCodeAttributeCategory' fields to the response"))
  92. .setHandler(this);
  93. action.createParam(PARAM_KEY)
  94. .setRequired(true)
  95. .setMaximumLength(KEY_MAXIMUM_LENGTH)
  96. .setDescription("Key of the rule to update")
  97. .setExampleValue("javascript:NullCheck");
  98. action.createParam(PARAM_TAGS)
  99. .setDescription("Optional comma-separated list of tags to set. Use blank value to remove current tags. Tags " +
  100. "are not changed if the parameter is not set.")
  101. .setExampleValue("java8,security");
  102. action.createParam(PARAM_MARKDOWN_NOTE)
  103. .setDescription("Optional note in <a href='/formatting/help'>markdown format</a>. Use empty value to remove current note. Note is not changed " +
  104. "if the parameter is not set.")
  105. .setExampleValue("my *note*");
  106. action.createParam(PARAM_REMEDIATION_FN_TYPE)
  107. .setDescription("Type of the remediation function of the rule")
  108. .setPossibleValues(DebtRemediationFunction.Type.values())
  109. .setSince("5.5");
  110. action.createParam(PARAM_REMEDIATION_FN_BASE_EFFORT)
  111. .setDescription("Base effort of the remediation function of the rule")
  112. .setExampleValue("1d")
  113. .setSince("5.5");
  114. action.createParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER)
  115. .setDescription("Gap multiplier of the remediation function of the rule")
  116. .setExampleValue("3min")
  117. .setSince("5.5");
  118. action
  119. .createParam(PARAM_NAME)
  120. .setMaximumLength(NAME_MAXIMUM_LENGTH)
  121. .setDescription("Rule name (mandatory for custom rule)")
  122. .setExampleValue("My custom rule");
  123. action
  124. .createParam(PARAM_DESCRIPTION)
  125. .setDescription("Rule description (mandatory for custom rule and manual rule) in <a href='/formatting/help'>markdown format</a>")
  126. .setExampleValue("Description of my custom rule")
  127. .setDeprecatedKey("markdown_description", "10.2");
  128. action
  129. .createParam(PARAM_SEVERITY)
  130. .setDescription("Rule severity (Only when updating a custom rule)")
  131. .setPossibleValues(Severity.ALL);
  132. action
  133. .createParam(PARAM_STATUS)
  134. .setPossibleValues(RuleStatus.values())
  135. .setDescription("Rule status (Only when updating a custom rule)");
  136. action.createParam(PARAMS)
  137. .setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only when updating a custom rule)");
  138. }
  139. @Override
  140. public void handle(Request request, Response response) throws Exception {
  141. userSession.checkLoggedIn();
  142. try (DbSession dbSession = dbClient.openSession(false)) {
  143. ruleWsSupport.checkQProfileAdminPermission();
  144. RuleUpdate update = readRequest(dbSession, request);
  145. ruleUpdater.update(dbSession, update, userSession);
  146. UpdateResponse updateResponse = buildResponse(dbSession, update.getRuleKey());
  147. writeProtobuf(updateResponse, request, response);
  148. }
  149. }
  150. private RuleUpdate readRequest(DbSession dbSession, Request request) {
  151. RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY));
  152. RuleUpdate update = createRuleUpdate(dbSession, key);
  153. readTags(request, update);
  154. readMarkdownNote(request, update);
  155. readDebt(request, update);
  156. String name = request.param(PARAM_NAME);
  157. if (name != null) {
  158. update.setName(name);
  159. }
  160. String description = request.param(PARAM_DESCRIPTION);
  161. if (description != null) {
  162. update.setMarkdownDescription(description);
  163. }
  164. String severity = request.param(PARAM_SEVERITY);
  165. if (severity != null) {
  166. update.setSeverity(severity);
  167. }
  168. String status = request.param(PARAM_STATUS);
  169. if (status != null) {
  170. update.setStatus(RuleStatus.valueOf(status));
  171. }
  172. String params = request.param(PARAMS);
  173. if (params != null) {
  174. update.setParameters(KeyValueFormat.parse(params));
  175. }
  176. return update;
  177. }
  178. private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key) {
  179. RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key)
  180. .orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key)));
  181. return ofNullable(rule.getTemplateUuid())
  182. .map(x -> RuleUpdate.createForCustomRule(key))
  183. .orElseGet(() -> RuleUpdate.createForPluginRule(key));
  184. }
  185. private static void readTags(Request request, RuleUpdate update) {
  186. String value = request.param(PARAM_TAGS);
  187. if (value != null) {
  188. if (StringUtils.isBlank(value)) {
  189. update.setTags(null);
  190. } else {
  191. update.setTags(newHashSet(Splitter.on(',').omitEmptyStrings().trimResults().split(value)));
  192. }
  193. }
  194. // else do not touch this field
  195. }
  196. private static void readMarkdownNote(Request request, RuleUpdate update) {
  197. String value = request.param(PARAM_MARKDOWN_NOTE);
  198. if (value != null) {
  199. update.setMarkdownNote(value);
  200. }
  201. // else do not touch this field
  202. }
  203. private static void readDebt(Request request, RuleUpdate update) {
  204. String value = request.param(PARAM_REMEDIATION_FN_TYPE);
  205. if (value != null) {
  206. if (StringUtils.isBlank(value)) {
  207. update.setDebtRemediationFunction(null);
  208. } else {
  209. DebtRemediationFunction fn = new DefaultDebtRemediationFunction(
  210. DebtRemediationFunction.Type.valueOf(value),
  211. request.param(PARAM_REMEDIATION_FN_GAP_MULTIPLIER),
  212. request.param(PARAM_REMEDIATION_FN_BASE_EFFORT));
  213. update.setDebtRemediationFunction(fn);
  214. }
  215. }
  216. }
  217. private UpdateResponse buildResponse(DbSession dbSession, RuleKey key) {
  218. RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key)
  219. .orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key)));
  220. List<RuleDto> templateRules = new ArrayList<>(1);
  221. if (rule.isCustomRule()) {
  222. dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession).ifPresent(templateRules::add);
  223. }
  224. List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid()));
  225. UpdateResponse.Builder responseBuilder = UpdateResponse.newBuilder();
  226. RulesResponseFormatter.SearchResult searchResult = new RulesResponseFormatter.SearchResult()
  227. .setRules(singletonList(rule))
  228. .setTemplateRules(templateRules)
  229. .setRuleParameters(ruleParameters)
  230. .setTotal(1L);
  231. responseBuilder
  232. .setRule(mapper.toWsRule(rule, searchResult, Collections.emptySet(),
  233. ruleWsSupport.getUsersByUuid(dbSession, singletonList(rule)), emptyMap()));
  234. return responseBuilder.build();
  235. }
  236. }