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.server.projectanalysis.ws;
22 import com.google.common.collect.ListMultimap;
23 import com.google.gson.Gson;
24 import com.google.gson.JsonSyntaxException;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import javax.annotation.Nullable;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.sonar.db.component.SnapshotDto;
34 import org.sonar.db.event.EventComponentChangeDto;
35 import org.sonar.db.event.EventDto;
36 import org.sonarqube.ws.ProjectAnalyses;
37 import org.sonarqube.ws.ProjectAnalyses.Analysis;
38 import org.sonarqube.ws.ProjectAnalyses.Event;
39 import org.sonarqube.ws.ProjectAnalyses.QualityGate;
40 import org.sonarqube.ws.ProjectAnalyses.SearchResponse;
42 import static java.lang.String.format;
43 import static java.util.Optional.ofNullable;
44 import static org.sonar.api.utils.DateUtils.formatDateTime;
45 import static org.sonar.core.util.stream.MoreCollectors.index;
46 import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
48 class SearchResponseBuilder {
49 private static final Logger LOGGER = LoggerFactory.getLogger(SearchResponseBuilder.class);
51 private final Analysis.Builder wsAnalysis;
52 private final Event.Builder wsEvent;
53 private final SearchData searchData;
54 private final QualityGate.Builder wsQualityGate;
55 private final ProjectAnalyses.DefinitionChange.Builder wsDefinitionChange;
57 SearchResponseBuilder(SearchData searchData) {
58 this.wsAnalysis = Analysis.newBuilder();
59 this.wsEvent = Event.newBuilder();
60 this.wsQualityGate = QualityGate.newBuilder();
61 this.wsDefinitionChange = ProjectAnalyses.DefinitionChange.newBuilder();
62 this.searchData = searchData;
65 SearchResponse build() {
66 SearchResponse.Builder wsResponse = SearchResponse.newBuilder();
67 addAnalyses(wsResponse);
68 addPagination(wsResponse);
69 return wsResponse.build();
72 private void addAnalyses(SearchResponse.Builder wsResponse) {
73 searchData.analyses.stream()
74 .map(this::dbToWsAnalysis)
75 .map(this::attachEvents)
76 .forEach(wsResponse::addAnalyses);
79 private Analysis.Builder dbToWsAnalysis(SnapshotDto dbAnalysis) {
80 var builder = wsAnalysis.clear();
82 .setKey(dbAnalysis.getUuid())
83 .setDate(formatDateTime(dbAnalysis.getCreatedAt()))
84 .setManualNewCodePeriodBaseline(searchData.getManualBaseline().filter(dbAnalysis.getUuid()::equals).isPresent());
85 ofNullable(dbAnalysis.getProjectVersion()).ifPresent(builder::setProjectVersion);
86 ofNullable(dbAnalysis.getBuildString()).ifPresent(builder::setBuildString);
87 ofNullable(dbAnalysis.getRevision()).ifPresent(builder::setRevision);
88 ofNullable(searchData.detectedCIs.get(dbAnalysis.getUuid())).ifPresent(builder::setDetectedCI);
93 private Analysis.Builder attachEvents(Analysis.Builder analysis) {
94 searchData.eventsByAnalysis.get(analysis.getKey())
96 .map(this::dbToWsEvent)
97 .forEach(analysis::addEvents);
101 private Event.Builder dbToWsEvent(EventDto dbEvent) {
102 wsEvent.clear().setKey(dbEvent.getUuid());
103 ofNullable(dbEvent.getName()).ifPresent(wsEvent::setName);
104 ofNullable(dbEvent.getDescription()).ifPresent(wsEvent::setDescription);
105 ofNullable(dbEvent.getCategory()).ifPresent(cat -> wsEvent.setCategory(fromLabel(cat).name()));
106 if (dbEvent.getCategory() != null) {
107 switch (EventCategory.fromLabel(dbEvent.getCategory())) {
108 case DEFINITION_CHANGE:
109 addDefinitionChange(dbEvent);
112 addQualityGateInformation(dbEvent);
121 private void addQualityGateInformation(EventDto event) {
122 wsQualityGate.clear();
123 List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
124 if (eventComponentChangeDtos.isEmpty()) {
128 if (event.getData() != null) {
130 Gson gson = new Gson();
131 Data data = gson.fromJson(event.getData(), Data.class);
133 wsQualityGate.setStillFailing(data.isStillFailing());
134 wsQualityGate.setStatus(data.getStatus());
135 } catch (JsonSyntaxException ex) {
136 LOGGER.error("Unable to retrieve data from event uuid=" + event.getUuid(), ex);
141 wsQualityGate.addAllFailing(eventComponentChangeDtos.stream()
142 .map(SearchResponseBuilder::toFailing)
144 wsEvent.setQualityGate(wsQualityGate.build());
147 private void addDefinitionChange(EventDto event) {
148 wsDefinitionChange.clear();
149 List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
150 if (eventComponentChangeDtos.isEmpty()) {
154 ListMultimap<String, EventComponentChangeDto> componentChangeByKey = eventComponentChangeDtos.stream()
155 .collect(index(EventComponentChangeDto::getComponentKey));
158 wsDefinitionChange.addAllProjects(
159 componentChangeByKey.asMap().values().stream()
160 .map(SearchResponseBuilder::addChange)
161 .map(Project::toProject)
164 wsEvent.setDefinitionChange(wsDefinitionChange.build());
165 } catch (IllegalStateException e) {
166 LOGGER.error(e.getMessage(), e);
170 private static Project addChange(Collection<EventComponentChangeDto> changes) {
171 if (changes.size() == 1) {
172 return addSingleChange(changes.iterator().next());
174 return addBranchChange(changes);
178 private static Project addSingleChange(EventComponentChangeDto componentChange) {
179 Project project = new Project()
180 .setKey(componentChange.getComponentKey())
181 .setName(componentChange.getComponentName())
182 .setBranch(componentChange.getComponentBranchKey());
184 switch (componentChange.getCategory()) {
186 project.setChangeType("ADDED");
189 project.setChangeType("REMOVED");
192 throw new IllegalStateException(format("Unknown change %s for eventComponentChange uuid: %s", componentChange.getCategory(), componentChange.getUuid()));
198 private static Project addBranchChange(Collection<EventComponentChangeDto> changes) {
199 if (changes.size() != 2) {
200 throw new IllegalStateException(format("Too many changes on same project (%d) for eventComponentChange uuids : %s",
202 changes.stream().map(EventComponentChangeDto::getUuid).collect(Collectors.joining(","))));
205 Optional<EventComponentChangeDto> addedChange = changes.stream().filter(c -> c.getCategory().equals(EventComponentChangeDto.ChangeCategory.ADDED)).findFirst();
206 Optional<EventComponentChangeDto> removedChange = changes.stream().filter(c -> c.getCategory().equals(EventComponentChangeDto.ChangeCategory.REMOVED)).findFirst();
208 if (!addedChange.isPresent() || !removedChange.isPresent() || addedChange.equals(removedChange)) {
209 Iterator<EventComponentChangeDto> iterator = changes.iterator();
210 // We are missing two different ADDED and REMOVED changes
211 EventComponentChangeDto firstChange = iterator.next();
212 EventComponentChangeDto secondChange = iterator.next();
213 throw new IllegalStateException(format("Incorrect changes : [uuid=%s change=%s, branch=%s] and [uuid=%s, change=%s, branch=%s]",
214 firstChange.getUuid(), firstChange.getCategory().name(), firstChange.getComponentBranchKey(),
215 secondChange.getUuid(), secondChange.getCategory().name(), secondChange.getComponentBranchKey()));
219 .setName(addedChange.get().getComponentName())
220 .setKey(addedChange.get().getComponentKey())
221 .setChangeType("BRANCH_CHANGED")
222 .setNewBranch(addedChange.get().getComponentBranchKey())
223 .setOldBranch(removedChange.get().getComponentBranchKey());
226 private void addPagination(SearchResponse.Builder wsResponse) {
227 wsResponse.getPagingBuilder()
228 .setPageIndex(searchData.paging.pageIndex())
229 .setPageSize(searchData.paging.pageSize())
230 .setTotal(searchData.paging.total())
234 private static ProjectAnalyses.Failing toFailing(EventComponentChangeDto change) {
235 ProjectAnalyses.Failing.Builder builder = ProjectAnalyses.Failing.newBuilder()
236 .setKey(change.getComponentKey())
237 .setName(change.getComponentName());
238 if (change.getComponentBranchKey() != null) {
239 builder.setBranch(change.getComponentBranchKey());
241 return builder.build();
244 private static class Data {
245 private boolean stillFailing;
246 private String status;
249 // Empty constructor because it's used by GSon
252 boolean isStillFailing() {
256 public Data setStillFailing(boolean stillFailing) {
257 this.stillFailing = stillFailing;
265 public Data setStatus(String status) {
266 this.status = status;
271 private static class Project {
274 private String changeType;
275 private String branch;
276 private String oldBranch;
277 private String newBranch;
279 public Project setKey(String key) {
284 public Project setName(String name) {
289 public Project setChangeType(String changeType) {
290 this.changeType = changeType;
294 public Project setBranch(@Nullable String branch) {
295 this.branch = branch;
299 public Project setOldBranch(@Nullable String oldBranch) {
300 this.oldBranch = oldBranch;
304 public Project setNewBranch(@Nullable String newBranch) {
305 this.newBranch = newBranch;
309 private ProjectAnalyses.Project toProject() {
310 ProjectAnalyses.Project.Builder builder = ProjectAnalyses.Project.newBuilder();
314 .setChangeType(changeType);
315 ofNullable(branch).ifPresent(builder::setBranch);
316 ofNullable(oldBranch).ifPresent(builder::setOldBranch);
317 ofNullable(newBranch).ifPresent(builder::setNewBranch);
318 return builder.build();