3 * Copyright (C) 2009-2022 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.Qualifiers;
36 import org.sonar.api.resources.Scopes;
37 import org.sonar.api.rules.RuleType;
38 import org.sonar.db.DatabaseUtils;
39 import org.sonar.db.DbClient;
40 import org.sonar.db.DbSession;
41 import org.sonar.db.ResultSetIterator;
42 import org.sonar.server.security.SecurityStandards;
44 import static com.google.common.base.Preconditions.checkArgument;
45 import static org.elasticsearch.common.Strings.isNullOrEmpty;
46 import static org.sonar.api.utils.DateUtils.longToDate;
47 import static org.sonar.db.DatabaseUtils.getLong;
48 import static org.sonar.db.rule.RuleDefinitionDto.deserializeSecurityStandardsString;
49 import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
52 * Scrolls over table ISSUES and reads documents to populate
55 class IssueIteratorForSingleChunk implements IssueIterator {
57 private static final String[] FIELDS = {
68 "i.issue_creation_date",
71 "i.issue_update_date",
79 "c.main_branch_project_uuid",
84 "r.security_standards",
89 private static final String SQL_ALL = "select " + StringUtils.join(FIELDS, ",") + " from issues i " +
90 "inner join rules r on r.uuid = i.rule_uuid " +
91 "inner join components c on c.uuid = i.component_uuid ";
93 private static final String SQL_NEW_CODE_JOIN = "left join new_code_reference_issues n on n.issue_key = i.kee ";
95 private static final String PROJECT_FILTER = " and c.project_uuid = ? and i.project_uuid = ? ";
96 private static final String ISSUE_KEY_FILTER_PREFIX = " and i.kee in (";
97 private static final String ISSUE_KEY_FILTER_SUFFIX = ") ";
99 static final Splitter TAGS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
100 static final Splitter MODULE_PATH_SPLITTER = Splitter.on('.').trimResults().omitEmptyStrings();
102 private final DbSession session;
105 private final String projectUuid;
108 private final Collection<String> issueKeys;
110 private final PreparedStatement stmt;
111 private final ResultSetIterator<IssueDoc> iterator;
113 IssueIteratorForSingleChunk(DbClient dbClient, @Nullable String projectUuid, @Nullable Collection<String> issueKeys) {
114 checkArgument(issueKeys == null || issueKeys.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE,
115 "Cannot search for more than " + DatabaseUtils.PARTITION_SIZE_FOR_ORACLE + " issue keys at once. Please provide the keys in smaller chunks.");
116 this.projectUuid = projectUuid;
117 this.issueKeys = issueKeys;
118 this.session = dbClient.openSession(false);
121 String sql = createSql();
122 stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql);
123 iterator = createIterator();
124 } catch (Exception e) {
126 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
130 private IssueIteratorInternal createIterator() {
133 return new IssueIteratorInternal(stmt);
134 } catch (SQLException e) {
135 DatabaseUtils.closeQuietly(stmt);
136 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
141 public boolean hasNext() {
142 return iterator.hasNext();
146 public IssueDoc next() {
147 return iterator.next();
150 private String createSql() {
151 String sql = SQL_ALL;
152 sql += projectUuid == null ? "" : PROJECT_FILTER;
153 if (issueKeys != null && !issueKeys.isEmpty()) {
154 sql += ISSUE_KEY_FILTER_PREFIX;
155 sql += IntStream.range(0, issueKeys.size()).mapToObj(i -> "?").collect(Collectors.joining(","));
156 sql += ISSUE_KEY_FILTER_SUFFIX;
158 sql += SQL_NEW_CODE_JOIN;
162 private void setParameters(PreparedStatement stmt) throws SQLException {
164 if (projectUuid != null) {
165 stmt.setString(index, projectUuid);
167 stmt.setString(index, projectUuid);
170 if (issueKeys != null) {
171 for (String key : issueKeys) {
172 stmt.setString(index, key);
179 public void close() {
183 DatabaseUtils.closeQuietly(stmt);
188 private static final class IssueIteratorInternal extends ResultSetIterator<IssueDoc> {
190 public IssueIteratorInternal(PreparedStatement stmt) throws SQLException {
195 protected IssueDoc read(ResultSet rs) throws SQLException {
196 IssueDoc doc = new IssueDoc(new HashMap<>(30));
198 String key = rs.getString(1);
200 // all the fields must be present, even if value is null
202 doc.setAssigneeUuid(rs.getString(2));
203 doc.setLine(DatabaseUtils.getInt(rs, 3));
204 doc.setResolution(rs.getString(4));
205 doc.setSeverity(rs.getString(5));
206 doc.setStatus(rs.getString(6));
207 doc.setEffort(getLong(rs, 7));
208 doc.setAuthorLogin(rs.getString(8));
209 doc.setFuncCloseDate(longToDate(getLong(rs, 9)));
210 doc.setFuncCreationDate(longToDate(getLong(rs, 10)));
211 doc.setFuncUpdateDate(longToDate(getLong(rs, 11)));
212 doc.setRuleUuid(rs.getString(12));
213 doc.setLanguage(rs.getString(13));
214 doc.setComponentUuid(rs.getString(14));
215 String moduleUuidPath = rs.getString(15);
216 doc.setModuleUuid(extractModule(moduleUuidPath));
217 doc.setModuleUuidPath(moduleUuidPath);
218 String scope = rs.getString(17);
219 String filePath = extractFilePath(rs.getString(16), scope);
220 doc.setFilePath(filePath);
221 doc.setDirectoryPath(extractDirPath(doc.filePath(), scope));
222 String branchUuid = rs.getString(18);
223 String mainBranchProjectUuid = DatabaseUtils.getString(rs, 19);
224 doc.setBranchUuid(branchUuid);
225 if (mainBranchProjectUuid == null) {
226 doc.setProjectUuid(branchUuid);
227 doc.setIsMainBranch(true);
229 doc.setProjectUuid(mainBranchProjectUuid);
230 doc.setIsMainBranch(false);
232 String tags = rs.getString(20);
233 doc.setTags(IssueIteratorForSingleChunk.TAGS_SPLITTER.splitToList(tags == null ? "" : tags));
234 doc.setType(RuleType.valueOf(rs.getInt(21)));
236 SecurityStandards securityStandards = fromSecurityStandards(deserializeSecurityStandardsString(rs.getString(22)));
237 SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
238 doc.setOwaspTop10(securityStandards.getOwaspTop10());
239 doc.setOwaspTop10For2021(securityStandards.getOwaspTop10For2021());
240 doc.setCwe(securityStandards.getCwe());
241 doc.setSansTop25(securityStandards.getSansTop25());
242 doc.setSonarSourceSecurityCategory(sqCategory);
243 doc.setVulnerabilityProbability(sqCategory.getVulnerability());
245 doc.setScope(Qualifiers.UNIT_TEST_FILE.equals(rs.getString(23)) ? IssueScope.TEST : IssueScope.MAIN);
246 doc.setIsNewCodeReference(!isNullOrEmpty(rs.getString(24)));
251 private static String extractDirPath(@Nullable String filePath, String scope) {
252 if (filePath != null) {
253 if (Scopes.DIRECTORY.equals(scope)) {
256 int lastSlashIndex = CharMatcher.anyOf("/").lastIndexIn(filePath);
257 if (lastSlashIndex > 0) {
258 return filePath.substring(0, lastSlashIndex);
266 private static String extractFilePath(@Nullable String filePath, String scope) {
267 // 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
269 // of files and directories.
270 // That's why the file path should be null on modules and projects.
271 if (filePath != null && !Scopes.PROJECT.equals(scope)) {
277 private static String extractModule(String moduleUuidPath) {
278 return Iterators.getLast(IssueIteratorForSingleChunk.MODULE_PATH_SPLITTER.split(moduleUuidPath).iterator());