3 * Copyright (C) 2009-2023 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.ce.task.projectexport.issue;
22 import com.google.common.annotations.VisibleForTesting;
23 import com.google.protobuf.ByteString;
24 import com.google.protobuf.InvalidProtocolBufferException;
25 import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
26 import java.sql.PreparedStatement;
27 import java.sql.ResultSet;
28 import java.sql.SQLException;
29 import java.util.List;
30 import java.util.Objects;
31 import java.util.Optional;
32 import java.util.stream.Collectors;
33 import org.sonar.api.rule.RuleKey;
34 import org.sonar.api.utils.log.Loggers;
35 import org.sonar.ce.task.projectexport.component.ComponentRepository;
36 import org.sonar.ce.task.projectexport.rule.Rule;
37 import org.sonar.ce.task.projectexport.rule.RuleRepository;
38 import org.sonar.ce.task.projectexport.steps.DumpElement;
39 import org.sonar.ce.task.projectexport.steps.DumpElement.IssueDumpElement;
40 import org.sonar.ce.task.projectexport.steps.DumpWriter;
41 import org.sonar.ce.task.projectexport.steps.ProjectHolder;
42 import org.sonar.ce.task.projectexport.steps.StreamWriter;
43 import org.sonar.ce.task.step.ComputationStep;
44 import org.sonar.db.DatabaseUtils;
45 import org.sonar.db.DbClient;
46 import org.sonar.db.DbSession;
47 import org.sonar.db.protobuf.DbIssues;
49 import static java.lang.String.format;
50 import static org.sonar.ce.task.projectexport.util.ResultSetUtils.defaultIfNull;
51 import static org.sonar.ce.task.projectexport.util.ResultSetUtils.emptyIfNull;
53 public class ExportIssuesStep implements ComputationStep {
54 private static final String RULE_STATUS_REMOVED = "REMOVED";
55 private static final String ISSUE_STATUS_CLOSED = "CLOSED";
57 // ordered by rule_id to reduce calls to RuleRepository
58 private static final String QUERY = "select" +
59 " i.kee, r.uuid, r.plugin_rule_key, r.plugin_name, i.issue_type," +
60 " i.component_uuid, i.message, i.line, i.checksum, i.status," +
61 " i.resolution, i.severity, i.manual_severity, i.gap, effort," +
62 " i.assignee, i.author_login, i.tags, i.issue_creation_date," +
63 " i.issue_update_date, i.issue_close_date, i.locations, i.project_uuid," +
64 " i.rule_description_context_key, i.message_formattings " +
66 " join rules r on r.uuid = i.rule_uuid and r.status <> ?" +
67 " join components p on p.uuid = i.project_uuid" +
68 " join project_branches pb on pb.uuid = p.uuid" +
69 " where pb.project_uuid = ? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=?" +
70 " and i.status <> ?" +
72 " i.rule_uuid asc, i.created_at asc";
74 private final DbClient dbClient;
75 private final ProjectHolder projectHolder;
76 private final DumpWriter dumpWriter;
77 private final RuleRegistrar ruleRegistrar;
78 private final ComponentRepository componentRepository;
80 public ExportIssuesStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter, RuleRepository ruleRepository,
81 ComponentRepository componentRepository) {
82 this.dbClient = dbClient;
83 this.projectHolder = projectHolder;
84 this.dumpWriter = dumpWriter;
85 this.componentRepository = componentRepository;
86 this.ruleRegistrar = new RuleRegistrar(ruleRepository);
90 public String getDescription() {
91 return "Export issues";
95 public void execute(Context context) {
98 StreamWriter<ProjectDump.Issue> output = dumpWriter.newStreamWriter(DumpElement.ISSUES);
99 DbSession dbSession = dbClient.openSession(false);
100 PreparedStatement stmt = createStatement(dbSession);
101 ResultSet rs = stmt.executeQuery()) {
102 ProjectDump.Issue.Builder builder = ProjectDump.Issue.newBuilder();
104 ProjectDump.Issue issue = toIssue(builder, rs);
108 Loggers.get(getClass()).debug("{} issues exported", count);
109 } catch (Exception e) {
110 throw new IllegalStateException(format("Issue export failed after processing %d issues successfully", count), e);
114 private PreparedStatement createStatement(DbSession dbSession) throws SQLException {
115 PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY);
117 stmt.setString(1, RULE_STATUS_REMOVED);
118 stmt.setString(2, projectHolder.projectDto().getUuid());
119 stmt.setBoolean(3, true);
120 stmt.setString(4, ISSUE_STATUS_CLOSED);
122 } catch (Exception t) {
123 DatabaseUtils.closeQuietly(stmt);
128 private ProjectDump.Issue toIssue(ProjectDump.Issue.Builder builder, ResultSet rs) throws SQLException {
130 String issueUuid = rs.getString(1);
131 setRule(builder, rs);
134 .setType(rs.getInt(5))
135 .setComponentRef(componentRepository.getRef(rs.getString(6)))
136 .setMessage(emptyIfNull(rs, 7))
137 .setLine(rs.getInt(8))
138 .setChecksum(emptyIfNull(rs, 9))
139 .setStatus(emptyIfNull(rs, 10))
140 .setResolution(emptyIfNull(rs, 11))
141 .setSeverity(emptyIfNull(rs, 12))
142 .setManualSeverity(rs.getBoolean(13))
143 .setGap(defaultIfNull(rs, 14, IssueDumpElement.NO_GAP))
144 .setEffort(defaultIfNull(rs, 15, IssueDumpElement.NO_EFFORT))
145 .setAssignee(emptyIfNull(rs, 16))
146 .setAuthor(emptyIfNull(rs, 17))
147 .setTags(emptyIfNull(rs, 18))
148 .setIssueCreatedAt(rs.getLong(19))
149 .setIssueUpdatedAt(rs.getLong(20))
150 .setIssueClosedAt(rs.getLong(21))
151 .setProjectUuid(rs.getString(23));
152 Optional.ofNullable(rs.getString(24)).ifPresent(builder::setRuleDescriptionContextKey);
153 setLocations(builder, rs, issueUuid);
154 setMessageFormattings(builder, rs, issueUuid);
155 return builder.build();
158 private void setRule(ProjectDump.Issue.Builder builder, ResultSet rs) throws SQLException {
159 String ruleUuid = rs.getString(2);
160 String ruleKey = rs.getString(3);
161 String repositoryKey = rs.getString(4);
162 builder.setRuleRef(ruleRegistrar.register(ruleUuid, repositoryKey, ruleKey).getRef());
165 private static void setLocations(ProjectDump.Issue.Builder builder, ResultSet rs, String issueUuid) throws SQLException {
167 byte[] bytes = rs.getBytes(22);
169 // fail fast, ensure we can read data from DB
170 DbIssues.Locations.parseFrom(bytes);
171 builder.setLocations(ByteString.copyFrom(bytes));
173 } catch (InvalidProtocolBufferException e) {
174 throw new IllegalStateException(format("Fail to read locations from DB for issue %s", issueUuid), e);
178 private static void setMessageFormattings(ProjectDump.Issue.Builder builder, ResultSet rs, String issueUuid) throws SQLException {
180 byte[] bytes = rs.getBytes(25);
182 // fail fast, ensure we can read data from DB
183 DbIssues.MessageFormattings messageFormattings = DbIssues.MessageFormattings.parseFrom(bytes);
184 if (messageFormattings != null) {
185 builder.addAllMessageFormattings(dbToDumpMessageFormatting(messageFormattings.getMessageFormattingList()));
188 } catch (InvalidProtocolBufferException e) {
189 throw new IllegalStateException(format("Fail to read message formattings from DB for issue %s", issueUuid), e);
194 static List<ProjectDump.MessageFormatting> dbToDumpMessageFormatting(List<DbIssues.MessageFormatting> messageFormattingList) {
195 return messageFormattingList.stream()
196 .map(e -> ProjectDump.MessageFormatting.newBuilder()
197 .setStart(e.getStart())
199 .setType(ProjectDump.MessageFormattingType.valueOf(e.getType().name())).build())
200 .collect(Collectors.toList());
203 private static class RuleRegistrar {
204 private final RuleRepository ruleRepository;
205 private Rule previousRule = null;
206 private String previousRuleUuid = null;
208 private RuleRegistrar(RuleRepository ruleRepository) {
209 this.ruleRepository = ruleRepository;
212 public Rule register(String ruleUuid, String repositoryKey, String ruleKey) {
213 if (Objects.equals(previousRuleUuid, ruleUuid)) {
216 return lookup(ruleUuid, RuleKey.of(repositoryKey, ruleKey));
219 private Rule lookup(String ruleUuid, RuleKey ruleKey) {
220 this.previousRule = ruleRepository.register(ruleUuid, ruleKey);
221 this.previousRuleUuid = ruleUuid;