3 * Copyright (C) 2009-2020 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.issue.index;
22 import com.google.common.base.CharMatcher;
23 import com.google.common.base.Splitter;
24 import com.google.common.collect.Iterators;
25 import java.sql.PreparedStatement;
26 import java.sql.ResultSet;
27 import java.sql.SQLException;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.stream.Collectors;
31 import java.util.stream.IntStream;
32 import javax.annotation.CheckForNull;
33 import javax.annotation.Nullable;
34 import org.apache.commons.lang.StringUtils;
35 import org.sonar.api.resources.Scopes;
36 import org.sonar.api.rules.RuleType;
37 import org.sonar.db.DatabaseUtils;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.ResultSetIterator;
41 import org.sonar.server.security.SecurityStandards;
43 import static com.google.common.base.Preconditions.checkArgument;
44 import static org.sonar.api.utils.DateUtils.longToDate;
45 import static org.sonar.db.DatabaseUtils.getLong;
46 import static org.sonar.db.rule.RuleDefinitionDto.deserializeSecurityStandardsString;
47 import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
50 * Scrolls over table ISSUES and reads documents to populate
53 class IssueIteratorForSingleChunk implements IssueIterator {
55 private static final String[] FIELDS = {
66 "i.issue_creation_date",
69 "i.issue_update_date",
76 "c.organization_uuid",
78 "c.main_branch_project_uuid",
83 "r.security_standards"
86 private static final String SQL_ALL = "select " + StringUtils.join(FIELDS, ",") + " from issues i " +
87 "inner join rules r on r.uuid = i.rule_uuid " +
88 "inner join components c on c.uuid = i.component_uuid ";
90 private static final String PROJECT_FILTER = " and c.project_uuid = ? and i.project_uuid = ? ";
91 private static final String ISSUE_KEY_FILTER_PREFIX = " and i.kee in (";
92 private static final String ISSUE_KEY_FILTER_SUFFIX = ")";
94 static final Splitter TAGS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
95 static final Splitter MODULE_PATH_SPLITTER = Splitter.on('.').trimResults().omitEmptyStrings();
97 private final DbSession session;
100 private final String projectUuid;
103 private final Collection<String> issueKeys;
105 private final PreparedStatement stmt;
106 private final ResultSetIterator<IssueDoc> iterator;
108 IssueIteratorForSingleChunk(DbClient dbClient, @Nullable String projectUuid, @Nullable Collection<String> issueKeys) {
109 checkArgument(issueKeys == null || issueKeys.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE,
110 "Cannot search for more than " + DatabaseUtils.PARTITION_SIZE_FOR_ORACLE + " issue keys at once. Please provide the keys in smaller chunks.");
111 this.projectUuid = projectUuid;
112 this.issueKeys = issueKeys;
113 this.session = dbClient.openSession(false);
116 String sql = createSql();
117 stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql);
118 iterator = createIterator();
119 } catch (Exception e) {
121 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
125 private IssueIteratorInternal createIterator() {
128 return new IssueIteratorInternal(stmt);
129 } catch (SQLException e) {
130 DatabaseUtils.closeQuietly(stmt);
131 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
136 public boolean hasNext() {
137 return iterator.hasNext();
141 public IssueDoc next() {
142 return iterator.next();
145 private String createSql() {
146 String sql = SQL_ALL;
147 sql += projectUuid == null ? "" : PROJECT_FILTER;
148 if (issueKeys != null && !issueKeys.isEmpty()) {
149 sql += ISSUE_KEY_FILTER_PREFIX;
150 sql += IntStream.range(0, issueKeys.size()).mapToObj(i -> "?").collect(Collectors.joining(","));
151 sql += ISSUE_KEY_FILTER_SUFFIX;
156 private void setParameters(PreparedStatement stmt) throws SQLException {
158 if (projectUuid != null) {
159 stmt.setString(index, projectUuid);
161 stmt.setString(index, projectUuid);
164 if (issueKeys != null) {
165 for (String key : issueKeys) {
166 stmt.setString(index, key);
173 public void close() {
177 DatabaseUtils.closeQuietly(stmt);
182 private static final class IssueIteratorInternal extends ResultSetIterator<IssueDoc> {
184 public IssueIteratorInternal(PreparedStatement stmt) throws SQLException {
189 protected IssueDoc read(ResultSet rs) throws SQLException {
190 IssueDoc doc = new IssueDoc(new HashMap<>(30));
192 String key = rs.getString(1);
194 // all the fields must be present, even if value is null
196 doc.setAssigneeUuid(rs.getString(2));
197 doc.setLine(DatabaseUtils.getInt(rs, 3));
198 doc.setResolution(rs.getString(4));
199 doc.setSeverity(rs.getString(5));
200 doc.setStatus(rs.getString(6));
201 doc.setEffort(getLong(rs, 7));
202 doc.setAuthorLogin(rs.getString(8));
203 doc.setFuncCloseDate(longToDate(getLong(rs, 9)));
204 doc.setFuncCreationDate(longToDate(getLong(rs, 10)));
205 doc.setFuncUpdateDate(longToDate(getLong(rs, 11)));
206 doc.setRuleUuid(rs.getString(12));
207 doc.setLanguage(rs.getString(13));
208 doc.setComponentUuid(rs.getString(14));
209 String moduleUuidPath = rs.getString(15);
210 doc.setModuleUuid(extractModule(moduleUuidPath));
211 doc.setModuleUuidPath(moduleUuidPath);
212 String scope = rs.getString(17);
213 String filePath = extractFilePath(rs.getString(16), scope);
214 doc.setFilePath(filePath);
215 doc.setDirectoryPath(extractDirPath(doc.filePath(), scope));
216 doc.setOrganizationUuid(rs.getString(18));
217 String branchUuid = rs.getString(19);
218 String mainBranchProjectUuid = DatabaseUtils.getString(rs, 20);
219 doc.setBranchUuid(branchUuid);
220 if (mainBranchProjectUuid == null) {
221 doc.setProjectUuid(branchUuid);
222 doc.setIsMainBranch(true);
224 doc.setProjectUuid(mainBranchProjectUuid);
225 doc.setIsMainBranch(false);
227 String tags = rs.getString(21);
228 doc.setTags(IssueIteratorForSingleChunk.TAGS_SPLITTER.splitToList(tags == null ? "" : tags));
229 doc.setType(RuleType.valueOf(rs.getInt(22)));
231 SecurityStandards securityStandards = fromSecurityStandards(deserializeSecurityStandardsString(rs.getString(23)));
232 SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
233 doc.setOwaspTop10(securityStandards.getOwaspTop10());
234 doc.setCwe(securityStandards.getCwe());
235 doc.setSansTop25(securityStandards.getSansTop25());
236 doc.setSonarSourceSecurityCategory(sqCategory);
237 doc.setVulnerabilityProbability(sqCategory.getVulnerability());
242 private static String extractDirPath(@Nullable String filePath, String scope) {
243 if (filePath != null) {
244 if (Scopes.DIRECTORY.equals(scope)) {
247 int lastSlashIndex = CharMatcher.anyOf("/").lastIndexIn(filePath);
248 if (lastSlashIndex > 0) {
249 return filePath.substring(0, lastSlashIndex);
257 private static String extractFilePath(@Nullable String filePath, String scope) {
258 // On modules, the path contains the relative path of the module starting from its parent, and in E/S we're only interested in the
260 // of files and directories.
261 // That's why the file path should be null on modules and projects.
262 if (filePath != null && !Scopes.PROJECT.equals(scope)) {
268 private static String extractModule(String moduleUuidPath) {
269 return Iterators.getLast(IssueIteratorForSingleChunk.MODULE_PATH_SPLITTER.split(moduleUuidPath).iterator());