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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 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 javax.annotation.Nullable;
  25. import org.sonar.api.server.ws.Change;
  26. import org.sonar.api.server.ws.Request;
  27. import org.sonar.api.server.ws.Response;
  28. import org.sonar.api.server.ws.WebService;
  29. import org.sonar.api.server.ws.WebService.Param;
  30. import org.sonar.api.utils.Paging;
  31. import org.sonar.core.util.stream.MoreCollectors;
  32. import org.sonar.db.DatabaseUtils;
  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.component.SnapshotDto;
  38. import org.sonar.db.organization.OrganizationDto;
  39. import org.sonar.db.permission.OrganizationPermission;
  40. import org.sonar.server.project.Visibility;
  41. import org.sonar.server.user.UserSession;
  42. import org.sonarqube.ws.Projects.SearchWsResponse;
  43. import static com.google.common.base.Preconditions.checkArgument;
  44. import static java.lang.String.format;
  45. import static org.sonar.api.resources.Qualifiers.APP;
  46. import static org.sonar.api.resources.Qualifiers.PROJECT;
  47. import static org.sonar.api.resources.Qualifiers.VIEW;
  48. import static org.sonar.api.utils.DateUtils.formatDateTime;
  49. import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
  50. import static org.sonar.core.util.Protobuf.setNullable;
  51. import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
  52. import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
  53. import static org.sonar.server.project.Visibility.PRIVATE;
  54. import static org.sonar.server.project.Visibility.PUBLIC;
  55. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  56. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
  57. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  58. import static org.sonarqube.ws.Projects.SearchWsResponse.Component;
  59. import static org.sonarqube.ws.Projects.SearchWsResponse.newBuilder;
  60. import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_SEARCH;
  61. import static org.sonarqube.ws.client.project.ProjectsWsParameters.MAX_PAGE_SIZE;
  62. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
  63. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
  64. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ORGANIZATION;
  65. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
  66. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT_IDS;
  67. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
  68. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
  69. public class SearchAction implements ProjectsWsAction {
  70. private final DbClient dbClient;
  71. private final UserSession userSession;
  72. private final ProjectsWsSupport support;
  73. public SearchAction(DbClient dbClient, UserSession userSession, ProjectsWsSupport support) {
  74. this.dbClient = dbClient;
  75. this.userSession = userSession;
  76. this.support = support;
  77. }
  78. @Override
  79. public void define(WebService.NewController context) {
  80. WebService.NewAction action = context.createAction(ACTION_SEARCH)
  81. .setSince("6.3")
  82. .setDescription("Search for projects or views to administrate them.<br>" +
  83. "Requires 'System Administrator' permission")
  84. .addPagingParams(100, MAX_PAGE_SIZE)
  85. .setResponseExample(getClass().getResource("search-example.json"))
  86. .setHandler(this);
  87. action.setChangelog(
  88. new Change("6.4", "The 'uuid' field is deprecated in the response"),
  89. new Change("6.7.2", format("Parameters %s and %s accept maximum %d values", PARAM_PROJECTS, PARAM_PROJECT_IDS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)));
  90. action.createParam(Param.TEXT_QUERY)
  91. .setDescription("Limit search 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. support.addOrganizationParam(action);
  101. action.createParam(PARAM_VISIBILITY)
  102. .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
  103. "If no visibility is specified, the default project visibility of the organization will be used.",
  104. Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
  105. .setRequired(false)
  106. .setInternal(true)
  107. .setSince("6.4")
  108. .setPossibleValues(Visibility.getLabels());
  109. action.createParam(PARAM_ANALYZED_BEFORE)
  110. .setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
  111. "Either a date (server timezone) or datetime can be provided.")
  112. .setSince("6.6")
  113. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  114. action.createParam(PARAM_ON_PROVISIONED_ONLY)
  115. .setDescription("Filter the projects that are provisioned")
  116. .setBooleanPossibleValues()
  117. .setDefaultValue("false")
  118. .setSince("6.6");
  119. action
  120. .createParam(PARAM_PROJECTS)
  121. .setDescription("Comma-separated list of project keys")
  122. .setSince("6.6")
  123. // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
  124. // Restricting size of HTTP parameter allows to not fail with SQL error
  125. .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
  126. .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
  127. action
  128. .createParam(PARAM_PROJECT_IDS)
  129. .setDescription("Comma-separated list of project ids")
  130. .setSince("6.6")
  131. // parameter added to match api/projects/bulk_delete parameters
  132. .setDeprecatedSince("6.6")
  133. // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
  134. // Restricting size of HTTP parameter allows to not fail with SQL error
  135. .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
  136. .setExampleValue(String.join(",", UUID_EXAMPLE_01, UUID_EXAMPLE_02));
  137. }
  138. @Override
  139. public void handle(Request wsRequest, Response wsResponse) throws Exception {
  140. SearchWsResponse searchWsResponse = doHandle(toSearchWsRequest(wsRequest));
  141. writeProtobuf(searchWsResponse, wsRequest, wsResponse);
  142. }
  143. private static SearchRequest toSearchWsRequest(Request request) {
  144. return SearchRequest.builder()
  145. .setOrganization(request.param(PARAM_ORGANIZATION))
  146. .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
  147. .setQuery(request.param(Param.TEXT_QUERY))
  148. .setPage(request.mandatoryParamAsInt(Param.PAGE))
  149. .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
  150. .setVisibility(request.param(PARAM_VISIBILITY))
  151. .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
  152. .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
  153. .setProjects(request.paramAsStrings(PARAM_PROJECTS))
  154. .setProjectIds(request.paramAsStrings(PARAM_PROJECT_IDS))
  155. .build();
  156. }
  157. private SearchWsResponse doHandle(SearchRequest request) {
  158. try (DbSession dbSession = dbClient.openSession(false)) {
  159. OrganizationDto organization = support.getOrganization(dbSession, request.getOrganization());
  160. userSession.checkPermission(OrganizationPermission.ADMINISTER, organization);
  161. ComponentQuery query = buildDbQuery(request);
  162. Paging paging = buildPaging(dbSession, request, organization, query);
  163. List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, organization.getUuid(), query, paging.offset(), paging.pageSize());
  164. Map<String, Long> analysisDateByComponentUuid = dbClient.snapshotDao()
  165. .selectLastAnalysesByRootComponentUuids(dbSession, components.stream().map(ComponentDto::uuid).collect(MoreCollectors.toList())).stream()
  166. .collect(MoreCollectors.uniqueIndex(SnapshotDto::getComponentUuid, SnapshotDto::getCreatedAt));
  167. return buildResponse(components, organization, analysisDateByComponentUuid, paging);
  168. }
  169. }
  170. static ComponentQuery buildDbQuery(SearchRequest request) {
  171. List<String> qualifiers = request.getQualifiers();
  172. ComponentQuery.Builder query = ComponentQuery.builder()
  173. .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
  174. setNullable(request.getQuery(), q -> {
  175. query.setNameOrKeyQuery(q);
  176. query.setPartialMatchOnKey(true);
  177. return query;
  178. });
  179. setNullable(request.getVisibility(), v -> query.setPrivate(Visibility.isPrivate(v)));
  180. setNullable(request.getAnalyzedBefore(), d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
  181. setNullable(request.isOnProvisionedOnly(), query::setOnProvisionedOnly);
  182. setNullable(request.getProjects(), keys -> query.setComponentKeys(new HashSet<>(keys)));
  183. setNullable(request.getProjectIds(), uuids -> query.setComponentUuids(new HashSet<>(uuids)));
  184. return query.build();
  185. }
  186. private Paging buildPaging(DbSession dbSession, SearchRequest request, OrganizationDto organization, ComponentQuery query) {
  187. int total = dbClient.componentDao().countByQuery(dbSession, organization.getUuid(), query);
  188. return Paging.forPageIndex(request.getPage())
  189. .withPageSize(request.getPageSize())
  190. .andTotal(total);
  191. }
  192. private static SearchWsResponse buildResponse(List<ComponentDto> components, OrganizationDto organization, Map<String, Long> analysisDateByComponentUuid, Paging paging) {
  193. SearchWsResponse.Builder responseBuilder = newBuilder();
  194. responseBuilder.getPagingBuilder()
  195. .setPageIndex(paging.pageIndex())
  196. .setPageSize(paging.pageSize())
  197. .setTotal(paging.total())
  198. .build();
  199. components.stream()
  200. .map(dto -> dtoToProject(organization, dto, analysisDateByComponentUuid.get(dto.uuid())))
  201. .forEach(responseBuilder::addComponents);
  202. return responseBuilder.build();
  203. }
  204. private static Component dtoToProject(OrganizationDto organization, ComponentDto dto, @Nullable Long analysisDate) {
  205. checkArgument(
  206. organization.getUuid().equals(dto.getOrganizationUuid()),
  207. "No Organization found for uuid '%s'",
  208. dto.getOrganizationUuid());
  209. Component.Builder builder = Component.newBuilder()
  210. .setOrganization(organization.getKey())
  211. .setId(dto.uuid())
  212. .setKey(dto.getDbKey())
  213. .setName(dto.name())
  214. .setQualifier(dto.qualifier())
  215. .setVisibility(dto.isPrivate() ? PRIVATE.getLabel() : PUBLIC.getLabel());
  216. setNullable(analysisDate, d -> builder.setLastAnalysisDate(formatDateTime(d)));
  217. return builder.build();
  218. }
  219. }