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.

SearchAction.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 java.util.HashSet;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import java.util.stream.Collectors;
  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.api.utils.Paging;
  33. import org.sonar.core.util.stream.MoreCollectors;
  34. import org.sonar.db.DatabaseUtils;
  35. import org.sonar.db.DbClient;
  36. import org.sonar.db.DbSession;
  37. import org.sonar.db.component.ComponentDto;
  38. import org.sonar.db.component.ComponentQuery;
  39. import org.sonar.db.component.ProjectLastAnalysisDateDto;
  40. import org.sonar.db.component.SnapshotDto;
  41. import org.sonar.db.permission.GlobalPermission;
  42. import org.sonar.server.project.Visibility;
  43. import org.sonar.server.user.UserSession;
  44. import org.sonarqube.ws.Projects.SearchWsResponse;
  45. import static java.util.Optional.ofNullable;
  46. import static java.util.function.Function.identity;
  47. import static org.sonar.api.resources.Qualifiers.APP;
  48. import static org.sonar.api.resources.Qualifiers.PROJECT;
  49. import static org.sonar.api.resources.Qualifiers.VIEW;
  50. import static org.sonar.api.utils.DateUtils.formatDateTime;
  51. import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
  52. import static org.sonar.server.project.Visibility.PRIVATE;
  53. import static org.sonar.server.project.Visibility.PUBLIC;
  54. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  55. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
  56. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  57. import static org.sonarqube.ws.Projects.SearchWsResponse.Component;
  58. import static org.sonarqube.ws.Projects.SearchWsResponse.newBuilder;
  59. import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_SEARCH;
  60. import static org.sonarqube.ws.client.project.ProjectsWsParameters.MAX_PAGE_SIZE;
  61. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
  62. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
  63. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
  64. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
  65. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
  66. public class SearchAction implements ProjectsWsAction {
  67. private final DbClient dbClient;
  68. private final UserSession userSession;
  69. public SearchAction(DbClient dbClient, UserSession userSession) {
  70. this.dbClient = dbClient;
  71. this.userSession = userSession;
  72. }
  73. @Override
  74. public void define(WebService.NewController context) {
  75. WebService.NewAction action = context.createAction(ACTION_SEARCH)
  76. .setSince("6.3")
  77. .setDescription("Search for projects or views to administrate them.<br>" +
  78. "Requires 'Administer System' permission")
  79. .addPagingParams(100, MAX_PAGE_SIZE)
  80. .setResponseExample(getClass().getResource("search-example.json"))
  81. .setChangelog(new Change("9.1", "The parameter '" + PARAM_ANALYZED_BEFORE + "' and the field 'lastAnalysisDate' of the returned projects "
  82. + "take into account the analysis of all branches and pull requests, not only the main branch."))
  83. .setHandler(this);
  84. action.createParam(Param.TEXT_QUERY)
  85. .setDescription("Limit search to: <ul>" +
  86. "<li>component names that contain the supplied string</li>" +
  87. "<li>component keys that contain the supplied string</li>" +
  88. "</ul>")
  89. .setExampleValue("sonar");
  90. action.createParam(PARAM_QUALIFIERS)
  91. .setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers")
  92. .setPossibleValues(PROJECT, VIEW, APP)
  93. .setDefaultValue(PROJECT);
  94. action.createParam(PARAM_VISIBILITY)
  95. .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
  96. "If no visibility is specified, the default project visibility will be used.",
  97. Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
  98. .setRequired(false)
  99. .setInternal(true)
  100. .setSince("6.4")
  101. .setPossibleValues(Visibility.getLabels());
  102. action.createParam(PARAM_ANALYZED_BEFORE)
  103. .setDescription("Filter the projects for which the last analysis of all branches are older than the given date (exclusive).<br> " +
  104. "Either a date (server timezone) or datetime can be provided.")
  105. .setSince("6.6")
  106. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  107. action.createParam(PARAM_ON_PROVISIONED_ONLY)
  108. .setDescription("Filter the projects that are provisioned")
  109. .setBooleanPossibleValues()
  110. .setDefaultValue("false")
  111. .setSince("6.6");
  112. action
  113. .createParam(PARAM_PROJECTS)
  114. .setDescription("Comma-separated list of project keys")
  115. .setSince("6.6")
  116. // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
  117. // Restricting size of HTTP parameter allows to not fail with SQL error
  118. .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
  119. .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
  120. }
  121. @Override
  122. public void handle(Request wsRequest, Response wsResponse) throws Exception {
  123. SearchWsResponse searchWsResponse = doHandle(toSearchWsRequest(wsRequest));
  124. writeProtobuf(searchWsResponse, wsRequest, wsResponse);
  125. }
  126. private static SearchRequest toSearchWsRequest(Request request) {
  127. return SearchRequest.builder()
  128. .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
  129. .setQuery(request.param(Param.TEXT_QUERY))
  130. .setPage(request.mandatoryParamAsInt(Param.PAGE))
  131. .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
  132. .setVisibility(request.param(PARAM_VISIBILITY))
  133. .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
  134. .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
  135. .setProjects(request.paramAsStrings(PARAM_PROJECTS))
  136. .build();
  137. }
  138. private SearchWsResponse doHandle(SearchRequest request) {
  139. try (DbSession dbSession = dbClient.openSession(false)) {
  140. userSession.checkPermission(GlobalPermission.ADMINISTER);
  141. ComponentQuery query = buildDbQuery(request);
  142. Paging paging = buildPaging(dbSession, request, query);
  143. List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, query, paging.offset(), paging.pageSize());
  144. Set<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(MoreCollectors.toHashSet(components.size()));
  145. Map<String, Long> lastAnalysisDateByComponentUuid = dbClient.snapshotDao().selectLastAnalysisDateByProjects(dbSession, componentUuids).stream()
  146. .collect(Collectors.toMap(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate));
  147. Map<String, SnapshotDto> snapshotsByComponentUuid = dbClient.snapshotDao()
  148. .selectLastAnalysesByRootComponentUuids(dbSession, componentUuids).stream()
  149. .collect(MoreCollectors.uniqueIndex(SnapshotDto::getComponentUuid, identity()));
  150. return buildResponse(components, snapshotsByComponentUuid, lastAnalysisDateByComponentUuid, paging);
  151. }
  152. }
  153. static ComponentQuery buildDbQuery(SearchRequest request) {
  154. List<String> qualifiers = request.getQualifiers();
  155. ComponentQuery.Builder query = ComponentQuery.builder()
  156. .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
  157. ofNullable(request.getQuery()).ifPresent(q -> {
  158. query.setNameOrKeyQuery(q);
  159. query.setPartialMatchOnKey(true);
  160. });
  161. ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
  162. ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAllBranchesAnalyzedBefore(parseDateOrDateTime(d).getTime()));
  163. query.setOnProvisionedOnly(request.isOnProvisionedOnly());
  164. ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
  165. return query.build();
  166. }
  167. private Paging buildPaging(DbSession dbSession, SearchRequest request, ComponentQuery query) {
  168. int total = dbClient.componentDao().countByQuery(dbSession, query);
  169. return Paging.forPageIndex(request.getPage())
  170. .withPageSize(request.getPageSize())
  171. .andTotal(total);
  172. }
  173. private static SearchWsResponse buildResponse(List<ComponentDto> components, Map<String, SnapshotDto> snapshotsByComponentUuid,
  174. Map<String, Long> lastAnalysisDateByComponentUuid, Paging paging) {
  175. SearchWsResponse.Builder responseBuilder = newBuilder();
  176. responseBuilder.getPagingBuilder()
  177. .setPageIndex(paging.pageIndex())
  178. .setPageSize(paging.pageSize())
  179. .setTotal(paging.total())
  180. .build();
  181. components.stream()
  182. .map(dto -> dtoToProject(dto, snapshotsByComponentUuid.get(dto.uuid()), lastAnalysisDateByComponentUuid.get(dto.uuid())))
  183. .forEach(responseBuilder::addComponents);
  184. return responseBuilder.build();
  185. }
  186. private static Component dtoToProject(ComponentDto dto, @Nullable SnapshotDto snapshot, @Nullable Long lastAnalysisDate) {
  187. Component.Builder builder = Component.newBuilder()
  188. .setKey(dto.getDbKey())
  189. .setName(dto.name())
  190. .setQualifier(dto.qualifier())
  191. .setVisibility(dto.isPrivate() ? PRIVATE.getLabel() : PUBLIC.getLabel());
  192. if (snapshot != null) {
  193. ofNullable(lastAnalysisDate).ifPresent(d -> builder.setLastAnalysisDate(formatDateTime(d)));
  194. ofNullable(snapshot.getRevision()).ifPresent(builder::setRevision);
  195. }
  196. return builder.build();
  197. }
  198. }