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.

BulkUpdateKeyAction.java 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.project.ws;
  21. import com.google.common.collect.ImmutableList;
  22. import java.util.Map;
  23. import org.sonar.api.server.ws.Request;
  24. import org.sonar.api.server.ws.Response;
  25. import org.sonar.api.server.ws.WebService;
  26. import org.sonar.api.web.UserRole;
  27. import org.sonar.db.DbClient;
  28. import org.sonar.db.DbSession;
  29. import org.sonar.db.component.ComponentKeyUpdaterDao;
  30. import org.sonar.db.project.ProjectDto;
  31. import org.sonar.server.component.ComponentFinder;
  32. import org.sonar.server.component.ComponentService;
  33. import org.sonar.server.user.UserSession;
  34. import org.sonarqube.ws.Projects.BulkUpdateKeyWsResponse;
  35. import static com.google.common.base.Preconditions.checkArgument;
  36. import static org.sonar.server.exceptions.BadRequestException.checkRequest;
  37. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  38. import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_BULK_UPDATE_KEY;
  39. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_DRY_RUN;
  40. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_FROM;
  41. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
  42. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_TO;
  43. public class BulkUpdateKeyAction implements ProjectsWsAction {
  44. private final DbClient dbClient;
  45. private final ComponentFinder componentFinder;
  46. private final ComponentKeyUpdaterDao componentKeyUpdater;
  47. private final ComponentService componentService;
  48. private final UserSession userSession;
  49. public BulkUpdateKeyAction(DbClient dbClient, ComponentFinder componentFinder, ComponentService componentService, UserSession userSession) {
  50. this.dbClient = dbClient;
  51. this.componentKeyUpdater = dbClient.componentKeyUpdaterDao();
  52. this.componentFinder = componentFinder;
  53. this.componentService = componentService;
  54. this.userSession = userSession;
  55. }
  56. @Override
  57. public void define(WebService.NewController context) {
  58. doDefine(context);
  59. }
  60. public WebService.NewAction doDefine(WebService.NewController context) {
  61. WebService.NewAction action = context.createAction(ACTION_BULK_UPDATE_KEY)
  62. .setDescription("Bulk update a project key and all its sub-components keys. " +
  63. "The bulk update allows to replace a part of the current key by another string on the current project.<br>" +
  64. "It's possible to simulate the bulk update by setting the parameter '%s' at true. No key is updated with a dry run.<br>" +
  65. "Ex: to rename a project with key 'my_project' to 'my_new_project' and all its sub-components keys, call the WS with parameters:" +
  66. "<ul>" +
  67. " <li>%s: my_project</li>" +
  68. " <li>%s: my_</li>" +
  69. " <li>%s: my_new_</li>" +
  70. "</ul>" +
  71. "Requires one of the following permissions: " +
  72. "<ul>" +
  73. "<li>'Administer System'</li>" +
  74. "<li>'Administer' rights on the specified project</li>" +
  75. "</ul>",
  76. PARAM_DRY_RUN,
  77. PARAM_PROJECT, PARAM_FROM, PARAM_TO)
  78. .setDeprecatedSince("7.6")
  79. .setSince("6.1")
  80. .setPost(true)
  81. .setResponseExample(getClass().getResource("bulk_update_key-example.json"))
  82. .setHandler(this);
  83. action.createParam(PARAM_PROJECT)
  84. .setDescription("Project key")
  85. .setRequired(true)
  86. .setExampleValue("my_old_project");
  87. action.createParam(PARAM_FROM)
  88. .setDescription("String to match in components keys")
  89. .setRequired(true)
  90. .setExampleValue("_old");
  91. action.createParam(PARAM_TO)
  92. .setDescription("String replacement in components keys")
  93. .setRequired(true)
  94. .setExampleValue("_new");
  95. action.createParam(PARAM_DRY_RUN)
  96. .setDescription("Simulate bulk update. No component key is updated.")
  97. .setBooleanPossibleValues()
  98. .setDefaultValue(false);
  99. return action;
  100. }
  101. @Override
  102. public void handle(Request request, Response response) throws Exception {
  103. writeProtobuf(doHandle(toWsRequest(request)), request, response);
  104. }
  105. private BulkUpdateKeyWsResponse doHandle(BulkUpdateKeyRequest request) {
  106. try (DbSession dbSession = dbClient.openSession(false)) {
  107. ProjectDto project = componentFinder.getProjectByKey(dbSession, request.getProjectKey());
  108. userSession.checkProjectPermission(UserRole.ADMIN, project);
  109. Map<String, String> newKeysByOldKeys = componentKeyUpdater.simulateBulkUpdateKey(dbSession, project.getUuid(), request.getFrom(), request.getTo());
  110. Map<String, Boolean> newKeysWithDuplicateMap = componentKeyUpdater.checkComponentKeys(dbSession, ImmutableList.copyOf(newKeysByOldKeys.values()));
  111. if (!request.isDryRun()) {
  112. checkNoDuplicate(newKeysWithDuplicateMap);
  113. bulkUpdateKey(dbSession, request, project);
  114. }
  115. return buildResponse(newKeysByOldKeys, newKeysWithDuplicateMap);
  116. }
  117. }
  118. private static void checkNoDuplicate(Map<String, Boolean> newKeysWithDuplicateMap) {
  119. newKeysWithDuplicateMap.forEach((key, value) -> checkRequest(!value, "Impossible to update key: a component with key \"%s\" already exists.", key));
  120. }
  121. private void bulkUpdateKey(DbSession dbSession, BulkUpdateKeyRequest request, ProjectDto project) {
  122. componentService.bulkUpdateKey(dbSession, project, request.getFrom(), request.getTo());
  123. }
  124. private static BulkUpdateKeyWsResponse buildResponse(Map<String, String> newKeysByOldKeys, Map<String, Boolean> newKeysWithDuplicateMap) {
  125. BulkUpdateKeyWsResponse.Builder response = BulkUpdateKeyWsResponse.newBuilder();
  126. newKeysByOldKeys.entrySet().stream()
  127. // sort by old key
  128. .sorted(Map.Entry.comparingByKey())
  129. .forEach(
  130. entry -> {
  131. String newKey = entry.getValue();
  132. response.addKeysBuilder()
  133. .setKey(entry.getKey())
  134. .setNewKey(newKey)
  135. .setDuplicate(newKeysWithDuplicateMap.getOrDefault(newKey, false));
  136. });
  137. return response.build();
  138. }
  139. private static BulkUpdateKeyRequest toWsRequest(Request request) {
  140. return BulkUpdateKeyRequest.builder()
  141. .setProjectKey(request.mandatoryParam(PARAM_PROJECT))
  142. .setFrom(request.mandatoryParam(PARAM_FROM))
  143. .setTo(request.mandatoryParam(PARAM_TO))
  144. .setDryRun(request.mandatoryParamAsBoolean(PARAM_DRY_RUN))
  145. .build();
  146. }
  147. private static class BulkUpdateKeyRequest {
  148. private final String projectKey;
  149. private final String from;
  150. private final String to;
  151. private final boolean dryRun;
  152. public BulkUpdateKeyRequest(Builder builder) {
  153. this.projectKey = builder.projectKey;
  154. this.from = builder.from;
  155. this.to = builder.to;
  156. this.dryRun = builder.dryRun;
  157. }
  158. public String getProjectKey() {
  159. return projectKey;
  160. }
  161. public String getFrom() {
  162. return from;
  163. }
  164. public String getTo() {
  165. return to;
  166. }
  167. public boolean isDryRun() {
  168. return dryRun;
  169. }
  170. public static Builder builder() {
  171. return new Builder();
  172. }
  173. }
  174. public static class Builder {
  175. private String projectKey;
  176. private String from;
  177. private String to;
  178. private boolean dryRun;
  179. private Builder() {
  180. // enforce method constructor
  181. }
  182. public Builder setProjectKey(String projectKey) {
  183. this.projectKey = projectKey;
  184. return this;
  185. }
  186. public Builder setFrom(String from) {
  187. this.from = from;
  188. return this;
  189. }
  190. public Builder setTo(String to) {
  191. this.to = to;
  192. return this;
  193. }
  194. public Builder setDryRun(boolean dryRun) {
  195. this.dryRun = dryRun;
  196. return this;
  197. }
  198. public BulkUpdateKeyRequest build() {
  199. checkArgument(projectKey != null && !projectKey.isEmpty(), "The key must not be empty");
  200. checkArgument(from != null && !from.isEmpty(), "The string to match must not be empty");
  201. checkArgument(to != null && !to.isEmpty(), "The string replacement must not be empty");
  202. return new BulkUpdateKeyRequest(this);
  203. }
  204. }
  205. }