3 * Copyright (C) 2009-2024 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.webhook.ws;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.function.Function;
28 import java.util.stream.Collectors;
29 import javax.annotation.Nullable;
30 import org.sonar.api.server.ws.Request;
31 import org.sonar.api.server.ws.Response;
32 import org.sonar.api.server.ws.WebService;
33 import org.sonar.api.web.UserRole;
34 import org.sonar.core.util.Uuids;
35 import org.sonar.db.DbClient;
36 import org.sonar.db.DbSession;
37 import org.sonar.db.Pagination;
38 import org.sonar.db.project.ProjectDto;
39 import org.sonar.db.webhook.WebhookDeliveryLiteDto;
40 import org.sonar.server.component.ComponentFinder;
41 import org.sonar.server.exceptions.ForbiddenException;
42 import org.sonar.server.user.UserSession;
43 import org.sonarqube.ws.Common;
44 import org.sonarqube.ws.Webhooks;
46 import static com.google.common.base.Preconditions.checkArgument;
47 import static org.apache.commons.lang.StringUtils.isNotBlank;
48 import static org.sonar.api.server.ws.WebService.Param.PAGE;
49 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
50 import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
51 import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
52 import static org.sonar.server.webhook.ws.WebhookWsSupport.copyDtoToProtobuf;
53 import static org.sonar.server.ws.WsUtils.writeProtobuf;
55 public class WebhookDeliveriesAction implements WebhooksWsAction {
57 private static final String PARAM_COMPONENT = "componentKey";
58 private static final String PARAM_TASK = "ceTaskId";
59 private static final String PARAM_WEBHOOK = "webhook";
61 private final DbClient dbClient;
62 private final UserSession userSession;
63 private final ComponentFinder componentFinder;
65 public WebhookDeliveriesAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) {
66 this.dbClient = dbClient;
67 this.userSession = userSession;
68 this.componentFinder = componentFinder;
72 public void define(WebService.NewController controller) {
73 WebService.NewAction action = controller.createAction("deliveries")
75 .setDescription("Get the recent deliveries for a specified project or Compute Engine task.<br/>" +
76 "Require 'Administer' permission on the related project.<br/>" +
77 "Note that additional information are returned by api/webhooks/delivery.")
78 .setResponseExample(getClass().getResource("example-deliveries.json"))
81 action.createParam(PARAM_COMPONENT)
82 .setDescription("Key of the project")
83 .setExampleValue("my-project");
85 action.createParam(PARAM_TASK)
86 .setDescription("Id of the Compute Engine task")
87 .setExampleValue(Uuids.UUID_EXAMPLE_01);
89 action.createParam(PARAM_WEBHOOK)
91 .setDescription("Key of the webhook that triggered those deliveries, " +
92 "auto-generated value that can be obtained through api/webhooks/create or api/webhooks/list")
93 .setExampleValue(UUID_EXAMPLE_02);
95 action.addPagingParamsSince(10, MAX_PAGE_SIZE, "7.1");
99 public void handle(Request request, Response response) throws Exception {
100 // fail-fast if not logged in
101 userSession.checkLoggedIn();
103 String ceTaskId = request.param(PARAM_TASK);
104 String projectKey = request.param(PARAM_COMPONENT);
105 String webhookUuid = request.param(PARAM_WEBHOOK);
106 int page = request.mandatoryParamAsInt(PAGE);
107 int pageSize = request.mandatoryParamAsInt(PAGE_SIZE);
109 checkArgument(webhookUuid != null ^ (ceTaskId != null ^ projectKey != null),
110 "Either '%s' or '%s' or '%s' must be provided", PARAM_TASK, PARAM_COMPONENT, PARAM_WEBHOOK);
112 Data data = loadFromDatabase(webhookUuid, ceTaskId, projectKey, page, pageSize);
113 data.ensureAdminPermission(userSession);
114 data.writeTo(request, response);
117 private Data loadFromDatabase(@Nullable String webhookUuid, @Nullable String ceTaskId, @Nullable String projectKey, int page, int pageSize) {
118 Map<String, ProjectDto> projectUuidMap;
119 List<WebhookDeliveryLiteDto> deliveries;
121 try (DbSession dbSession = dbClient.openSession(false)) {
122 if (isNotBlank(webhookUuid)) {
123 totalElements = dbClient.webhookDeliveryDao().countDeliveriesByWebhookUuid(dbSession, webhookUuid);
124 deliveries = dbClient.webhookDeliveryDao().selectByWebhookUuid(dbSession, webhookUuid, Pagination.forPage(page).andSize(pageSize));
125 projectUuidMap = getProjectsDto(dbSession, deliveries);
126 } else if (projectKey != null) {
127 ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey);
128 projectUuidMap = new HashMap<>();
129 projectUuidMap.put(project.getUuid(), project);
130 totalElements = dbClient.webhookDeliveryDao().countDeliveriesByProjectUuid(dbSession, project.getUuid());
131 deliveries = dbClient.webhookDeliveryDao().selectOrderedByProjectUuid(dbSession, project.getUuid(), Pagination.forPage(page).andSize(pageSize));
133 totalElements = dbClient.webhookDeliveryDao().countDeliveriesByCeTaskUuid(dbSession, ceTaskId);
134 deliveries = dbClient.webhookDeliveryDao().selectOrderedByCeTaskUuid(dbSession, ceTaskId, Pagination.forPage(page).andSize(pageSize));
135 projectUuidMap = getProjectsDto(dbSession, deliveries);
138 return new Data(projectUuidMap, deliveries).withPagingInfo(page, pageSize, totalElements);
141 private Map<String, ProjectDto> getProjectsDto(DbSession dbSession, List<WebhookDeliveryLiteDto> deliveries) {
142 Map<String, String> deliveredComponentUuid = deliveries
144 .collect(Collectors.toMap(WebhookDeliveryLiteDto::getUuid, WebhookDeliveryLiteDto::getProjectUuid));
146 if (!deliveredComponentUuid.isEmpty()) {
147 return dbClient.projectDao().selectByUuids(dbSession, new HashSet<>(deliveredComponentUuid.values()))
149 .collect(Collectors.toMap(ProjectDto::getUuid, Function.identity()));
151 return Collections.emptyMap();
155 private static class Data {
156 private final Map<String, ProjectDto> projectUuidMap;
157 private final List<WebhookDeliveryLiteDto> deliveryDtos;
159 private int pageIndex;
160 private int pageSize;
161 private int totalElements;
163 Data(Map<String, ProjectDto> projectUuidMap, List<WebhookDeliveryLiteDto> deliveries) {
164 this.deliveryDtos = deliveries;
165 if (deliveries.isEmpty()) {
166 this.projectUuidMap = projectUuidMap;
168 checkArgument(!projectUuidMap.isEmpty());
169 this.projectUuidMap = projectUuidMap;
173 void ensureAdminPermission(UserSession userSession) {
174 if (!projectUuidMap.isEmpty()) {
175 List<ProjectDto> projectsUserHasAccessTo = userSession.keepAuthorizedEntities(UserRole.ADMIN, projectUuidMap.values());
176 if (projectsUserHasAccessTo.size() != projectUuidMap.size()) {
177 throw new ForbiddenException("Insufficient privileges");
182 void writeTo(Request request, Response response) {
183 Webhooks.DeliveriesWsResponse.Builder responseBuilder = Webhooks.DeliveriesWsResponse.newBuilder();
184 Webhooks.Delivery.Builder deliveryBuilder = Webhooks.Delivery.newBuilder();
185 for (WebhookDeliveryLiteDto dto : deliveryDtos) {
186 ProjectDto project = projectUuidMap.get(dto.getProjectUuid());
187 copyDtoToProtobuf(project, dto, deliveryBuilder);
188 responseBuilder.addDeliveries(deliveryBuilder);
191 responseBuilder.setPaging(buildPaging(pageIndex, pageSize, totalElements));
192 writeProtobuf(responseBuilder.build(), request, response);
195 static Common.Paging buildPaging(int pageIndex, int pageSize, int totalElements) {
196 return Common.Paging.newBuilder()
197 .setPageIndex(pageIndex)
198 .setPageSize(pageSize)
199 .setTotal(totalElements)
203 public Data withPagingInfo(int pageIndex, int pageSize, int totalElements) {
204 this.pageIndex = pageIndex;
205 this.pageSize = pageSize;
206 this.totalElements = totalElements;