]> source.dussan.org Git - sonarqube.git/blob
83d2da299ece615eae6f0bb6a10eb118af71a1a7
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.server.projectanalysis.ws;
21
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;
41
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;
47
48 class SearchResponseBuilder {
49   private static final Logger LOGGER = LoggerFactory.getLogger(SearchResponseBuilder.class);
50
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;
56
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;
63   }
64
65   SearchResponse build() {
66     SearchResponse.Builder wsResponse = SearchResponse.newBuilder();
67     addAnalyses(wsResponse);
68     addPagination(wsResponse);
69     return wsResponse.build();
70   }
71
72   private void addAnalyses(SearchResponse.Builder wsResponse) {
73     searchData.analyses.stream()
74       .map(this::dbToWsAnalysis)
75       .map(this::attachEvents)
76       .forEach(wsResponse::addAnalyses);
77   }
78
79   private Analysis.Builder dbToWsAnalysis(SnapshotDto dbAnalysis) {
80     var builder = wsAnalysis.clear();
81     builder
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);
89
90     return builder;
91   }
92
93   private Analysis.Builder attachEvents(Analysis.Builder analysis) {
94     searchData.eventsByAnalysis.get(analysis.getKey())
95       .stream()
96       .map(this::dbToWsEvent)
97       .forEach(analysis::addEvents);
98     return analysis;
99   }
100
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);
110           break;
111         case QUALITY_GATE:
112           addQualityGateInformation(dbEvent);
113           break;
114         default:
115           break;
116       }
117     }
118     return wsEvent;
119   }
120
121   private void addQualityGateInformation(EventDto event) {
122     wsQualityGate.clear();
123     List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
124     if (eventComponentChangeDtos.isEmpty()) {
125       return;
126     }
127
128     if (event.getData() != null) {
129       try {
130         Gson gson = new Gson();
131         Data data = gson.fromJson(event.getData(), Data.class);
132
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);
137         return;
138       }
139     }
140
141     wsQualityGate.addAllFailing(eventComponentChangeDtos.stream()
142       .map(SearchResponseBuilder::toFailing)
143       .toList());
144     wsEvent.setQualityGate(wsQualityGate.build());
145   }
146
147   private void addDefinitionChange(EventDto event) {
148     wsDefinitionChange.clear();
149     List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
150     if (eventComponentChangeDtos.isEmpty()) {
151       return;
152     }
153
154     ListMultimap<String, EventComponentChangeDto> componentChangeByKey = eventComponentChangeDtos.stream()
155       .collect(index(EventComponentChangeDto::getComponentKey));
156
157     try {
158       wsDefinitionChange.addAllProjects(
159         componentChangeByKey.asMap().values().stream()
160           .map(SearchResponseBuilder::addChange)
161           .map(Project::toProject)
162           .toList()
163       );
164       wsEvent.setDefinitionChange(wsDefinitionChange.build());
165     } catch (IllegalStateException e) {
166       LOGGER.error(e.getMessage(), e);
167     }
168   }
169
170   private static Project addChange(Collection<EventComponentChangeDto> changes) {
171     if (changes.size() == 1) {
172       return addSingleChange(changes.iterator().next());
173     } else {
174       return addBranchChange(changes);
175     }
176   }
177
178   private static Project addSingleChange(EventComponentChangeDto componentChange) {
179     Project project = new Project()
180       .setKey(componentChange.getComponentKey())
181       .setName(componentChange.getComponentName())
182       .setBranch(componentChange.getComponentBranchKey());
183
184     switch (componentChange.getCategory()) {
185       case ADDED:
186         project.setChangeType("ADDED");
187         break;
188       case REMOVED:
189         project.setChangeType("REMOVED");
190         break;
191       default:
192         throw new IllegalStateException(format("Unknown change %s for eventComponentChange uuid: %s", componentChange.getCategory(), componentChange.getUuid()));
193     }
194
195     return project;
196   }
197
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",
201         changes.size(),
202         changes.stream().map(EventComponentChangeDto::getUuid).collect(Collectors.joining(","))));
203     }
204
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();
207
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()));
216     }
217
218     return new Project()
219       .setName(addedChange.get().getComponentName())
220       .setKey(addedChange.get().getComponentKey())
221       .setChangeType("BRANCH_CHANGED")
222       .setNewBranch(addedChange.get().getComponentBranchKey())
223       .setOldBranch(removedChange.get().getComponentBranchKey());
224   }
225
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())
231       .build();
232   }
233
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());
240     }
241     return builder.build();
242   }
243
244   private static class Data {
245     private boolean stillFailing;
246     private String status;
247
248     public Data() {
249       // Empty constructor because it's used by GSon
250     }
251
252     boolean isStillFailing() {
253       return stillFailing;
254     }
255
256     public Data setStillFailing(boolean stillFailing) {
257       this.stillFailing = stillFailing;
258       return this;
259     }
260
261     String getStatus() {
262       return status;
263     }
264
265     public Data setStatus(String status) {
266       this.status = status;
267       return this;
268     }
269   }
270
271   private static class Project {
272     private String key;
273     private String name;
274     private String changeType;
275     private String branch;
276     private String oldBranch;
277     private String newBranch;
278
279     public Project setKey(String key) {
280       this.key = key;
281       return this;
282     }
283
284     public Project setName(String name) {
285       this.name = name;
286       return this;
287     }
288
289     public Project setChangeType(String changeType) {
290       this.changeType = changeType;
291       return this;
292     }
293
294     public Project setBranch(@Nullable String branch) {
295       this.branch = branch;
296       return this;
297     }
298
299     public Project setOldBranch(@Nullable String oldBranch) {
300       this.oldBranch = oldBranch;
301       return this;
302     }
303
304     public Project setNewBranch(@Nullable String newBranch) {
305       this.newBranch = newBranch;
306       return this;
307     }
308
309     private ProjectAnalyses.Project toProject() {
310       ProjectAnalyses.Project.Builder builder = ProjectAnalyses.Project.newBuilder();
311       builder
312         .setKey(key)
313         .setName(name)
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();
319     }
320   }
321 }