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.

BulkDeleteAction.java 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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.base.Strings;
  22. import java.util.HashSet;
  23. import java.util.List;
  24. import java.util.Set;
  25. import javax.annotation.CheckForNull;
  26. import javax.annotation.Nullable;
  27. import org.sonar.api.server.ws.Change;
  28. import org.sonar.api.server.ws.Request;
  29. import org.sonar.api.server.ws.Response;
  30. import org.sonar.api.server.ws.WebService;
  31. import org.sonar.api.server.ws.WebService.Param;
  32. import org.sonar.core.util.stream.MoreCollectors;
  33. import org.sonar.db.DbClient;
  34. import org.sonar.db.DbSession;
  35. import org.sonar.db.component.ComponentDto;
  36. import org.sonar.db.component.ComponentQuery;
  37. import org.sonar.db.permission.GlobalPermission;
  38. import org.sonar.server.component.ComponentCleanerService;
  39. import org.sonar.server.project.Project;
  40. import org.sonar.server.project.ProjectLifeCycleListeners;
  41. import org.sonar.server.project.Visibility;
  42. import org.sonar.server.user.UserSession;
  43. import static com.google.common.base.Preconditions.checkArgument;
  44. import static java.lang.Math.min;
  45. import static java.lang.String.format;
  46. import static org.sonar.api.resources.Qualifiers.APP;
  47. import static org.sonar.api.resources.Qualifiers.PROJECT;
  48. import static org.sonar.api.resources.Qualifiers.VIEW;
  49. import static org.sonar.server.project.ws.SearchAction.buildDbQuery;
  50. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  51. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
  52. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
  53. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
  54. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
  55. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
  56. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
  57. public class BulkDeleteAction implements ProjectsWsAction {
  58. private static final String ACTION = "bulk_delete";
  59. private final ComponentCleanerService componentCleanerService;
  60. private final DbClient dbClient;
  61. private final UserSession userSession;
  62. private final ProjectLifeCycleListeners projectLifeCycleListeners;
  63. public BulkDeleteAction(ComponentCleanerService componentCleanerService, DbClient dbClient, UserSession userSession,
  64. ProjectLifeCycleListeners projectLifeCycleListeners) {
  65. this.componentCleanerService = componentCleanerService;
  66. this.dbClient = dbClient;
  67. this.userSession = userSession;
  68. this.projectLifeCycleListeners = projectLifeCycleListeners;
  69. }
  70. @Override
  71. public void define(WebService.NewController context) {
  72. String parameterRequiredMessage = format("At least one parameter is required among %s, %s and %s",
  73. PARAM_ANALYZED_BEFORE, PARAM_PROJECTS, Param.TEXT_QUERY);
  74. WebService.NewAction action = context
  75. .createAction(ACTION)
  76. .setPost(true)
  77. .setDescription("Delete one or several projects.<br />" +
  78. "Only the 1'000 first items in project filters are taken into account.<br />" +
  79. "Requires 'Administer System' permission.<br />" +
  80. parameterRequiredMessage)
  81. .setSince("5.2")
  82. .setHandler(this)
  83. .setChangelog(new Change("7.8", parameterRequiredMessage))
  84. .setChangelog(new Change("9.1", "The parameter '" + PARAM_ANALYZED_BEFORE + "' "
  85. + "takes into account the analysis of all branches and pull requests, not only the main branch."));
  86. action
  87. .createParam(PARAM_PROJECTS)
  88. .setDescription("Comma-separated list of project keys")
  89. .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
  90. action.createParam(Param.TEXT_QUERY)
  91. .setDescription("Limit to: <ul>" +
  92. "<li>component names that contain the supplied string</li>" +
  93. "<li>component keys that contain the supplied string</li>" +
  94. "</ul>")
  95. .setExampleValue("sonar");
  96. action.createParam(PARAM_QUALIFIERS)
  97. .setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers")
  98. .setPossibleValues(PROJECT, VIEW, APP)
  99. .setDefaultValue(PROJECT);
  100. action.createParam(PARAM_VISIBILITY)
  101. .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
  102. "If no visibility is specified, the default project visibility will be used.",
  103. Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
  104. .setRequired(false)
  105. .setInternal(true)
  106. .setSince("6.4")
  107. .setPossibleValues(Visibility.getLabels());
  108. action.createParam(PARAM_ANALYZED_BEFORE)
  109. .setDescription("Filter the projects for which last analysis of any branch is older than the given date (exclusive).<br> " +
  110. "Either a date (server timezone) or datetime can be provided.")
  111. .setSince("6.6")
  112. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  113. action.createParam(PARAM_ON_PROVISIONED_ONLY)
  114. .setDescription("Filter the projects that are provisioned")
  115. .setBooleanPossibleValues()
  116. .setDefaultValue("false")
  117. .setSince("6.6");
  118. }
  119. @Override
  120. public void handle(Request request, Response response) throws Exception {
  121. SearchRequest searchRequest = toSearchWsRequest(request);
  122. userSession.checkLoggedIn();
  123. try (DbSession dbSession = dbClient.openSession(false)) {
  124. userSession.checkPermission(GlobalPermission.ADMINISTER);
  125. checkAtLeastOneParameterIsPresent(searchRequest);
  126. ComponentQuery query = buildDbQuery(searchRequest);
  127. Set<ComponentDto> componentDtos = new HashSet<>(dbClient.componentDao().selectByQuery(dbSession, query, 0, Integer.MAX_VALUE));
  128. try {
  129. componentDtos.forEach(p -> componentCleanerService.delete(dbSession, p));
  130. } finally {
  131. projectLifeCycleListeners.onProjectsDeleted(componentDtos.stream().map(Project::from).collect(MoreCollectors.toSet(componentDtos.size())));
  132. }
  133. }
  134. response.noContent();
  135. }
  136. private static void checkAtLeastOneParameterIsPresent(SearchRequest searchRequest) {
  137. boolean analyzedBeforePresent = !Strings.isNullOrEmpty(searchRequest.getAnalyzedBefore());
  138. List<String> projects = searchRequest.getProjects();
  139. boolean projectsPresent = projects != null && !projects.isEmpty();
  140. boolean queryPresent = !Strings.isNullOrEmpty(searchRequest.getQuery());
  141. boolean atLeastOneParameterIsPresent = analyzedBeforePresent || projectsPresent || queryPresent;
  142. checkArgument(atLeastOneParameterIsPresent, format("At lease one parameter among %s, %s and %s must be provided",
  143. PARAM_ANALYZED_BEFORE, PARAM_PROJECTS, Param.TEXT_QUERY));
  144. }
  145. private static SearchRequest toSearchWsRequest(Request request) {
  146. return SearchRequest.builder()
  147. .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
  148. .setQuery(request.param(Param.TEXT_QUERY))
  149. .setVisibility(request.param(PARAM_VISIBILITY))
  150. .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
  151. .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
  152. .setProjects(restrictTo1000Values(request.paramAsStrings(PARAM_PROJECTS)))
  153. .build();
  154. }
  155. @CheckForNull
  156. private static List<String> restrictTo1000Values(@Nullable List<String> values) {
  157. if (values == null) {
  158. return null;
  159. }
  160. return values.subList(0, min(values.size(), 1_000));
  161. }
  162. }