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 java.sql.PreparedStatement;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.stream.Collectors;
30 import java.util.stream.IntStream;
31 import javax.annotation.CheckForNull;
32 import javax.annotation.Nullable;
33 import org.apache.commons.lang.StringUtils;
34 import org.sonar.api.resources.Qualifiers;
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.elasticsearch.common.Strings.isNullOrEmpty;
45 import static org.sonar.api.utils.DateUtils.longToDate;
46 import static org.sonar.db.DatabaseUtils.getLong;
47 import static org.sonar.db.rule.RuleDto.deserializeSecurityStandardsString;
48 import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
51 * Scrolls over table ISSUES and reads documents to populate
54 class IssueIteratorForSingleChunk implements IssueIterator {
56 private static final String[] FIELDS = {
67 "i.issue_creation_date",
70 "i.issue_update_date",
78 "c.main_branch_project_uuid",
83 "r.security_standards",
88 private static final String SQL_ALL = "select " + StringUtils.join(FIELDS, ",") + " from issues i " +
89 "inner join rules r on r.uuid = i.rule_uuid " +
90 "inner join components c on c.uuid = i.component_uuid ";
92 private static final String SQL_NEW_CODE_JOIN = "left join new_code_reference_issues n on n.issue_key = i.kee ";
94 private static final String PROJECT_FILTER = " and c.project_uuid = ? and i.project_uuid = ? ";
95 private static final String ISSUE_KEY_FILTER_PREFIX = " and i.kee in (";
96 private static final String ISSUE_KEY_FILTER_SUFFIX = ") ";
98 static final Splitter TAGS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
99 static final Splitter MODULE_PATH_SPLITTER = Splitter.on('.').trimResults().omitEmptyStrings();
101 private final DbSession session;
104 private final String projectUuid;
107 private final Collection<String> issueKeys;
109 private final PreparedStatement stmt;
110 private final ResultSetIterator<IssueDoc> iterator;
112 IssueIteratorForSingleChunk(DbClient dbClient, @Nullable String projectUuid, @Nullable Collection<String> issueKeys) {
113 checkArgument(issueKeys == null || issueKeys.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE,
114 "Cannot search for more than " + DatabaseUtils.PARTITION_SIZE_FOR_ORACLE + " issue keys at once. Please provide the keys in smaller chunks.");
115 this.projectUuid = projectUuid;
116 this.issueKeys = issueKeys;
117 this.session = dbClient.openSession(false);
120 String sql = createSql();
121 stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql);
122 iterator = createIterator();
123 } catch (Exception e) {
125 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
129 private IssueIteratorInternal createIterator() {
132 return new IssueIteratorInternal(stmt);
133 } catch (SQLException e) {
134 DatabaseUtils.closeQuietly(stmt);
135 throw new IllegalStateException("Fail to prepare SQL request to select all issues", e);
140 public boolean hasNext() {
141 return iterator.hasNext();
145 public IssueDoc next() {
146 return iterator.next();
149 private String createSql() {
150 String sql = SQL_ALL;
151 sql += projectUuid == null ? "" : PROJECT_FILTER;
152 if (issueKeys != null && !issueKeys.isEmpty()) {
153 sql += ISSUE_KEY_FILTER_PREFIX;
154 sql += IntStream.range(0, issueKeys.size()).mapToObj(i -> "?").collect(Collectors.joining(","));
155 sql += ISSUE_KEY_FILTER_SUFFIX;
157 sql += SQL_NEW_CODE_JOIN;
161 private void setParameters(PreparedStatement stmt) throws SQLException {
163 if (projectUuid != null) {
164 stmt.setString(index, projectUuid);
166 stmt.setString(index, projectUuid);
169 if (issueKeys != null) {
170 for (String key : issueKeys) {
171 stmt.setString(index, key);
178 public void close() {
182 DatabaseUtils.closeQuietly(stmt);
187 private static final class IssueIteratorInternal extends ResultSetIterator<IssueDoc> {
189 public IssueIteratorInternal(PreparedStatement stmt) throws SQLException {
194 protected IssueDoc read(ResultSet rs) throws SQLException {
195 IssueDoc doc = new IssueDoc(new HashMap<>(30));
197 String key = rs.getString(1);
199 // all the fields must be present, even if value is null
201 doc.setAssigneeUuid(rs.getString(2));
202 doc.setLine(DatabaseUtils.getInt(rs, 3));
203 doc.setResolution(rs.getString(4));
204 doc.setSeverity(rs.getString(5));
205 doc.setStatus(rs.getString(6));
206 doc.setEffort(getLong(rs, 7));
207 doc.setAuthorLogin(rs.getString(8));
208 doc.setFuncCloseDate(longToDate(getLong(rs, 9)));
209 doc.setFuncCreationDate(longToDate(getLong(rs, 10)));
210 doc.setFuncUpdateDate(longToDate(getLong(rs, 11)));
211 doc.setRuleUuid(rs.getString(12));
212 doc.setLanguage(rs.getString(13));
213 doc.setComponentUuid(rs.getString(14));
214 String moduleUuidPath = rs.getString(15);
215 doc.setModuleUuidPath(moduleUuidPath);
216 String scope = rs.getString(17);
217 String filePath = extractFilePath(rs.getString(16), scope);
218 doc.setFilePath(filePath);
219 doc.setDirectoryPath(extractDirPath(doc.filePath(), scope));
220 String branchUuid = rs.getString(18);
221 String mainBranchProjectUuid = DatabaseUtils.getString(rs, 19);
222 doc.setBranchUuid(branchUuid);
223 if (mainBranchProjectUuid == null) {
224 doc.setProjectUuid(branchUuid);
225 doc.setIsMainBranch(true);
227 doc.setProjectUuid(mainBranchProjectUuid);
228 doc.setIsMainBranch(false);
230 String tags = rs.getString(20);
231 doc.setTags(IssueIteratorForSingleChunk.TAGS_SPLITTER.splitToList(tags == null ? "" : tags));
232 doc.setType(RuleType.valueOf(rs.getInt(21)));
234 SecurityStandards securityStandards = fromSecurityStandards(deserializeSecurityStandardsString(rs.getString(22)));
235 SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
236 doc.setOwaspTop10(securityStandards.getOwaspTop10());
237 doc.setOwaspTop10For2021(securityStandards.getOwaspTop10For2021());
238 doc.setPciDss32(securityStandards.getPciDss32());
239 doc.setPciDss40(securityStandards.getPciDss40());
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)) {