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.

IssueQueryFactory.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 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.issue.index;
  21. import com.google.common.base.Joiner;
  22. import com.google.common.base.Strings;
  23. import com.google.common.collect.ImmutableList;
  24. import java.time.Clock;
  25. import java.time.OffsetDateTime;
  26. import java.time.Period;
  27. import java.util.ArrayList;
  28. import java.util.Arrays;
  29. import java.util.Collection;
  30. import java.util.Collections;
  31. import java.util.Date;
  32. import java.util.HashSet;
  33. import java.util.List;
  34. import java.util.Locale;
  35. import java.util.Map;
  36. import java.util.Objects;
  37. import java.util.Optional;
  38. import java.util.Set;
  39. import java.util.stream.Collectors;
  40. import javax.annotation.CheckForNull;
  41. import javax.annotation.Nullable;
  42. import org.apache.commons.lang.BooleanUtils;
  43. import org.sonar.api.resources.Qualifiers;
  44. import org.sonar.api.rule.RuleKey;
  45. import org.sonar.api.server.ServerSide;
  46. import org.sonar.api.web.UserRole;
  47. import org.sonar.db.DbClient;
  48. import org.sonar.db.DbSession;
  49. import org.sonar.db.component.ComponentDto;
  50. import org.sonar.db.component.SnapshotDto;
  51. import org.sonar.db.organization.OrganizationDto;
  52. import org.sonar.db.rule.RuleDefinitionDto;
  53. import org.sonar.server.issue.SearchRequest;
  54. import org.sonar.server.issue.index.IssueQuery.PeriodStart;
  55. import org.sonar.server.user.UserSession;
  56. import static com.google.common.base.Preconditions.checkArgument;
  57. import static com.google.common.collect.Collections2.transform;
  58. import static java.lang.String.format;
  59. import static java.util.Collections.singleton;
  60. import static java.util.Collections.singletonList;
  61. import static org.sonar.api.issue.Issue.STATUSES;
  62. import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
  63. import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
  64. import static org.sonar.api.utils.DateUtils.longToDate;
  65. import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
  66. import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
  67. import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
  68. import static org.sonar.core.util.stream.MoreCollectors.toHashSet;
  69. import static org.sonar.core.util.stream.MoreCollectors.toList;
  70. import static org.sonar.core.util.stream.MoreCollectors.toSet;
  71. import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
  72. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_KEYS;
  73. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_UUIDS;
  74. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AFTER;
  75. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_IN_LAST;
  76. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SINCE_LEAK_PERIOD;
  77. /**
  78. * This component is used to create an IssueQuery, in order to transform the component and component roots keys into uuid.
  79. */
  80. @ServerSide
  81. public class IssueQueryFactory {
  82. public static final String UNKNOWN = "<UNKNOWN>";
  83. public static final List<String> ISSUE_STATUSES = STATUSES.stream()
  84. .filter(s -> !s.equals(STATUS_TO_REVIEW))
  85. .filter(s -> !s.equals(STATUS_REVIEWED))
  86. .collect(ImmutableList.toImmutableList());
  87. private static final ComponentDto UNKNOWN_COMPONENT = new ComponentDto().setUuid(UNKNOWN).setProjectUuid(UNKNOWN);
  88. private final DbClient dbClient;
  89. private final Clock clock;
  90. private final UserSession userSession;
  91. public IssueQueryFactory(DbClient dbClient, Clock clock, UserSession userSession) {
  92. this.dbClient = dbClient;
  93. this.clock = clock;
  94. this.userSession = userSession;
  95. }
  96. public IssueQuery create(SearchRequest request) {
  97. try (DbSession dbSession = dbClient.openSession(false)) {
  98. IssueQuery.Builder builder = IssueQuery.builder()
  99. .issueKeys(request.getIssues())
  100. .severities(request.getSeverities())
  101. .statuses(request.getStatuses())
  102. .resolutions(request.getResolutions())
  103. .resolved(request.getResolved())
  104. .rules(ruleKeysToRuleId(dbSession, request.getRules()))
  105. .assigneeUuids(request.getAssigneeUuids())
  106. .authors(request.getAuthors())
  107. .languages(request.getLanguages())
  108. .tags(request.getTags())
  109. .types(request.getTypes())
  110. .owaspTop10(request.getOwaspTop10())
  111. .sansTop25(request.getSansTop25())
  112. .cwe(request.getCwe())
  113. .sonarsourceSecurity(request.getSonarsourceSecurity())
  114. .assigned(request.getAssigned())
  115. .createdAt(parseDateOrDateTime(request.getCreatedAt()))
  116. .createdBefore(parseEndingDateOrDateTime(request.getCreatedBefore()))
  117. .facetMode(request.getFacetMode())
  118. .organizationUuid(convertOrganizationKeyToUuid(dbSession, request.getOrganization()));
  119. List<ComponentDto> allComponents = new ArrayList<>();
  120. boolean effectiveOnComponentOnly = mergeDeprecatedComponentParameters(dbSession, request, allComponents);
  121. addComponentParameters(builder, dbSession, effectiveOnComponentOnly, allComponents, request);
  122. setCreatedAfterFromRequest(dbSession, builder, request, allComponents);
  123. String sort = request.getSort();
  124. if (!Strings.isNullOrEmpty(sort)) {
  125. builder.sort(sort);
  126. builder.asc(request.getAsc());
  127. }
  128. return builder.build();
  129. }
  130. }
  131. private void setCreatedAfterFromDates(IssueQuery.Builder builder, @Nullable Date createdAfter, @Nullable String createdInLast, boolean createdAfterInclusive) {
  132. checkArgument(createdAfter == null || createdInLast == null, format("Parameters %s and %s cannot be set simultaneously", PARAM_CREATED_AFTER, PARAM_CREATED_IN_LAST));
  133. Date actualCreatedAfter = createdAfter;
  134. if (createdInLast != null) {
  135. actualCreatedAfter = Date.from(
  136. OffsetDateTime.now(clock)
  137. .minus(Period.parse("P" + createdInLast.toUpperCase(Locale.ENGLISH)))
  138. .toInstant());
  139. }
  140. builder.createdAfter(actualCreatedAfter, createdAfterInclusive);
  141. }
  142. @CheckForNull
  143. private String convertOrganizationKeyToUuid(DbSession dbSession, @Nullable String organizationKey) {
  144. if (organizationKey == null) {
  145. return null;
  146. }
  147. Optional<OrganizationDto> organization = dbClient.organizationDao().selectByKey(dbSession, organizationKey);
  148. return organization.map(OrganizationDto::getUuid).orElse(UNKNOWN);
  149. }
  150. private void setCreatedAfterFromRequest(DbSession dbSession, IssueQuery.Builder builder, SearchRequest request, List<ComponentDto> componentUuids) {
  151. Date createdAfter = parseStartingDateOrDateTime(request.getCreatedAfter());
  152. String createdInLast = request.getCreatedInLast();
  153. if (request.getSinceLeakPeriod() == null || !request.getSinceLeakPeriod()) {
  154. setCreatedAfterFromDates(builder, createdAfter, createdInLast, true);
  155. } else {
  156. checkArgument(createdAfter == null, "Parameters '%s' and '%s' cannot be set simultaneously", PARAM_CREATED_AFTER, PARAM_SINCE_LEAK_PERIOD);
  157. checkArgument(componentUuids.size() == 1, "One and only one component must be provided when searching since leak period");
  158. ComponentDto component = componentUuids.iterator().next();
  159. Date createdAfterFromSnapshot = findCreatedAfterFromComponentUuid(dbSession, component);
  160. setCreatedAfterFromDates(builder, createdAfterFromSnapshot, createdInLast, false);
  161. }
  162. }
  163. @CheckForNull
  164. private Date findCreatedAfterFromComponentUuid(DbSession dbSession, ComponentDto component) {
  165. Optional<SnapshotDto> snapshot = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.uuid());
  166. return snapshot.map(s -> longToDate(s.getPeriodDate())).orElse(null);
  167. }
  168. private boolean mergeDeprecatedComponentParameters(DbSession session, SearchRequest request, List<ComponentDto> allComponents) {
  169. Boolean onComponentOnly = request.getOnComponentOnly();
  170. Collection<String> components = request.getComponents();
  171. Collection<String> componentUuids = request.getComponentUuids();
  172. Collection<String> componentKeys = request.getComponentKeys();
  173. Collection<String> componentRootUuids = request.getComponentRootUuids();
  174. Collection<String> componentRoots = request.getComponentRoots();
  175. String branch = request.getBranch();
  176. String pullRequest = request.getPullRequest();
  177. boolean effectiveOnComponentOnly = false;
  178. checkArgument(atMostOneNonNullElement(components, componentUuids, componentKeys, componentRootUuids, componentRoots),
  179. "At most one of the following parameters can be provided: %s and %s", PARAM_COMPONENT_KEYS, PARAM_COMPONENT_UUIDS);
  180. if (componentRootUuids != null) {
  181. allComponents.addAll(getComponentsFromUuids(session, componentRootUuids));
  182. } else if (componentRoots != null) {
  183. allComponents.addAll(getComponentsFromKeys(session, componentRoots, branch, pullRequest));
  184. } else if (components != null) {
  185. allComponents.addAll(getComponentsFromKeys(session, components, branch, pullRequest));
  186. effectiveOnComponentOnly = true;
  187. } else if (componentUuids != null) {
  188. allComponents.addAll(getComponentsFromUuids(session, componentUuids));
  189. effectiveOnComponentOnly = BooleanUtils.isTrue(onComponentOnly);
  190. } else if (componentKeys != null) {
  191. allComponents.addAll(getComponentsFromKeys(session, componentKeys, branch, pullRequest));
  192. effectiveOnComponentOnly = BooleanUtils.isTrue(onComponentOnly);
  193. }
  194. return effectiveOnComponentOnly;
  195. }
  196. private static boolean atMostOneNonNullElement(Object... objects) {
  197. return Arrays.stream(objects)
  198. .filter(Objects::nonNull)
  199. .count() <= 1;
  200. }
  201. private void addComponentParameters(IssueQuery.Builder builder, DbSession session, boolean onComponentOnly, List<ComponentDto> components, SearchRequest request) {
  202. builder.onComponentOnly(onComponentOnly);
  203. if (onComponentOnly) {
  204. builder.componentUuids(components.stream().map(ComponentDto::uuid).collect(toList()));
  205. setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
  206. return;
  207. }
  208. List<String> projectKeys = request.getProjectKeys();
  209. if (projectKeys != null) {
  210. List<ComponentDto> projects = getComponentsFromKeys(session, projectKeys, request.getBranch(), request.getPullRequest());
  211. builder.projectUuids(projects.stream().map(IssueQueryFactory::toProjectUuid).collect(toList()));
  212. setBranch(builder, projects.get(0), request.getBranch(), request.getPullRequest());
  213. }
  214. builder.moduleUuids(request.getModuleUuids());
  215. builder.directories(request.getDirectories());
  216. builder.fileUuids(request.getFileUuids());
  217. addComponentsBasedOnQualifier(builder, session, components, request);
  218. }
  219. private void addComponentsBasedOnQualifier(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> components, SearchRequest request) {
  220. if (components.isEmpty()) {
  221. return;
  222. }
  223. if (components.stream().map(ComponentDto::uuid).anyMatch(uuid -> uuid.equals(UNKNOWN))) {
  224. builder.componentUuids(singleton(UNKNOWN));
  225. return;
  226. }
  227. Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(toHashSet());
  228. checkArgument(qualifiers.size() == 1, "All components must have the same qualifier, found %s", String.join(",", qualifiers));
  229. setBranch(builder, components.get(0), request.getBranch(), request.getPullRequest());
  230. String qualifier = qualifiers.iterator().next();
  231. switch (qualifier) {
  232. case Qualifiers.VIEW:
  233. case Qualifiers.SUBVIEW:
  234. addViewsOrSubViews(builder, components);
  235. break;
  236. case Qualifiers.APP:
  237. addApplications(builder, dbSession, components, request);
  238. addProjectUuidsForApplication(builder, dbSession, request);
  239. break;
  240. case Qualifiers.PROJECT:
  241. builder.projectUuids(components.stream().map(IssueQueryFactory::toProjectUuid).collect(toList()));
  242. break;
  243. case Qualifiers.MODULE:
  244. builder.moduleRootUuids(components.stream().map(ComponentDto::uuid).collect(toList()));
  245. break;
  246. case Qualifiers.DIRECTORY:
  247. addDirectories(builder, components);
  248. break;
  249. case Qualifiers.FILE:
  250. case Qualifiers.UNIT_TEST_FILE:
  251. builder.fileUuids(components.stream().map(ComponentDto::uuid).collect(toList()));
  252. break;
  253. default:
  254. throw new IllegalArgumentException("Unable to set search root context for components " + Joiner.on(',').join(components));
  255. }
  256. }
  257. private void addProjectUuidsForApplication(IssueQuery.Builder builder, DbSession session, SearchRequest request) {
  258. List<String> projectKeys = request.getProjectKeys();
  259. if (projectKeys != null) {
  260. // On application, branch should only be applied on the application, not on projects
  261. List<ComponentDto> projects = getComponentsFromKeys(session, projectKeys, null, null);
  262. builder.projectUuids(projects.stream().map(ComponentDto::uuid).collect(toList()));
  263. }
  264. }
  265. private void addViewsOrSubViews(IssueQuery.Builder builder, Collection<ComponentDto> viewOrSubViewUuids) {
  266. List<String> filteredViewUuids = viewOrSubViewUuids.stream()
  267. .filter(uuid -> userSession.hasComponentPermission(UserRole.USER, uuid))
  268. .map(ComponentDto::uuid)
  269. .collect(Collectors.toList());
  270. if (filteredViewUuids.isEmpty()) {
  271. filteredViewUuids.add(UNKNOWN);
  272. }
  273. builder.viewUuids(filteredViewUuids);
  274. }
  275. private void addApplications(IssueQuery.Builder builder, DbSession dbSession, List<ComponentDto> applications, SearchRequest request) {
  276. Set<String> authorizedApplicationUuids = applications.stream()
  277. .filter(app -> userSession.hasComponentPermission(UserRole.USER, app))
  278. .map(ComponentDto::uuid)
  279. .collect(toSet());
  280. builder.viewUuids(authorizedApplicationUuids.isEmpty() ? singleton(UNKNOWN) : authorizedApplicationUuids);
  281. addCreatedAfterByProjects(builder, dbSession, request, authorizedApplicationUuids);
  282. }
  283. private void addCreatedAfterByProjects(IssueQuery.Builder builder, DbSession dbSession, SearchRequest request, Set<String> applicationUuids) {
  284. if (request.getSinceLeakPeriod() == null || !request.getSinceLeakPeriod()) {
  285. return;
  286. }
  287. Set<String> projectUuids = applicationUuids.stream()
  288. .flatMap(app -> dbClient.componentDao().selectProjectsFromView(dbSession, app, app).stream())
  289. .collect(toSet());
  290. Map<String, PeriodStart> leakByProjects = dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, projectUuids)
  291. .stream()
  292. .filter(s -> s.getPeriodDate() != null)
  293. .collect(uniqueIndex(SnapshotDto::getComponentUuid, s -> new PeriodStart(longToDate(s.getPeriodDate()), false)));
  294. builder.createdAfterByProjectUuids(leakByProjects);
  295. }
  296. private static void addDirectories(IssueQuery.Builder builder, List<ComponentDto> directories) {
  297. Collection<String> directoryModuleUuids = new HashSet<>();
  298. Collection<String> directoryPaths = new HashSet<>();
  299. for (ComponentDto directory : directories) {
  300. directoryModuleUuids.add(directory.moduleUuid());
  301. directoryPaths.add(directory.path());
  302. }
  303. builder.moduleUuids(directoryModuleUuids);
  304. builder.directories(directoryPaths);
  305. }
  306. private List<ComponentDto> getComponentsFromKeys(DbSession dbSession, Collection<String> componentKeys, @Nullable String branch, @Nullable String pullRequest) {
  307. List<ComponentDto> componentDtos;
  308. if (branch != null) {
  309. componentDtos = dbClient.componentDao().selectByKeysAndBranch(dbSession, componentKeys, branch);
  310. } else if (pullRequest != null) {
  311. componentDtos = dbClient.componentDao().selectByKeysAndPullRequest(dbSession, componentKeys, pullRequest);
  312. } else {
  313. componentDtos = dbClient.componentDao().selectByKeys(dbSession, componentKeys);
  314. }
  315. if (!componentKeys.isEmpty() && componentDtos.isEmpty()) {
  316. return singletonList(UNKNOWN_COMPONENT);
  317. }
  318. return componentDtos;
  319. }
  320. private List<ComponentDto> getComponentsFromUuids(DbSession dbSession, Collection<String> componentUuids) {
  321. List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, componentUuids);
  322. if (!componentUuids.isEmpty() && componentDtos.isEmpty()) {
  323. return singletonList(UNKNOWN_COMPONENT);
  324. }
  325. return componentDtos;
  326. }
  327. @CheckForNull
  328. private Collection<RuleDefinitionDto> ruleKeysToRuleId(DbSession dbSession, @Nullable Collection<String> rules) {
  329. if (rules != null) {
  330. return dbClient.ruleDao().selectDefinitionByKeys(dbSession, transform(rules, RuleKey::parse));
  331. }
  332. return Collections.emptyList();
  333. }
  334. private static String toProjectUuid(ComponentDto componentDto) {
  335. String mainBranchProjectUuid = componentDto.getMainBranchProjectUuid();
  336. return mainBranchProjectUuid == null ? componentDto.projectUuid() : mainBranchProjectUuid;
  337. }
  338. private static void setBranch(IssueQuery.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
  339. builder.branchUuid(branch == null && pullRequest == null ? null : component.projectUuid());
  340. builder.mainBranch(UNKNOWN_COMPONENT.equals(component)
  341. || (branch == null && pullRequest == null)
  342. || (branch != null && !branch.equals(component.getBranch()))
  343. || (pullRequest != null && !pullRequest.equals(component.getPullRequest())));
  344. }
  345. }