3 * Copyright (C) 2009-2020 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 java.util.List;
23 import java.util.function.Consumer;
24 import java.util.function.Function;
25 import java.util.function.Predicate;
26 import java.util.stream.Stream;
27 import org.sonar.api.server.ws.Request;
28 import org.sonar.api.server.ws.Response;
29 import org.sonar.api.server.ws.WebService;
30 import org.sonar.api.web.UserRole;
31 import org.sonar.core.util.Uuids;
32 import org.sonar.db.DbClient;
33 import org.sonar.db.DbSession;
34 import org.sonar.db.component.SnapshotDto;
35 import org.sonar.db.event.EventDto;
36 import org.sonar.server.exceptions.NotFoundException;
37 import org.sonar.server.user.UserSession;
38 import org.sonarqube.ws.ProjectAnalyses.Event;
39 import org.sonarqube.ws.ProjectAnalyses.UpdateEventResponse;
41 import javax.annotation.CheckForNull;
43 import static com.google.common.base.Preconditions.checkArgument;
44 import static java.lang.String.format;
45 import static java.util.Objects.requireNonNull;
46 import static java.util.Optional.ofNullable;
47 import static org.apache.commons.lang.StringUtils.isNotBlank;
48 import static org.sonar.server.projectanalysis.ws.EventValidator.checkModifiable;
49 import static org.sonar.server.projectanalysis.ws.EventValidator.checkVersionName;
50 import static org.sonar.server.ws.WsUtils.writeProtobuf;
51 import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
52 import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
53 import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT;
54 import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME;
56 public class UpdateEventAction implements ProjectAnalysesWsAction {
57 private final DbClient dbClient;
58 private final UserSession userSession;
60 public UpdateEventAction(DbClient dbClient, UserSession userSession) {
61 this.dbClient = dbClient;
62 this.userSession = userSession;
66 public void define(WebService.NewController context) {
67 WebService.NewAction action = context.createAction("update_event")
68 .setDescription("Update a project analysis event.<br>" +
69 "Only events of category '%s' and '%s' can be updated.<br>" +
70 "Requires one of the following permissions:" +
72 " <li>'Administer System'</li>" +
73 " <li>'Administer' rights on the specified project</li>" +
75 EventCategory.VERSION.name(), EventCategory.OTHER.name())
78 .setResponseExample(getClass().getResource("update_event-example.json"))
81 action.createParam(PARAM_EVENT)
82 .setDescription("Event key")
83 .setExampleValue(Uuids.UUID_EXAMPLE_08)
86 action.createParam(PARAM_NAME)
87 .setMaximumLength(org.sonar.db.event.EventValidator.MAX_NAME_LENGTH)
88 .setDescription("New name")
89 .setExampleValue("5.6")
94 public void handle(Request httpRequest, Response httpResponse) throws Exception {
95 Stream.of(httpRequest)
96 .map(toUpdateEventRequest())
98 .forEach(wsResponse -> writeProtobuf(wsResponse, httpRequest, httpResponse));
101 private UpdateEventResponse doHandle(UpdateEventRequest request) {
102 try (DbSession dbSession = dbClient.openSession(false)) {
104 .of(getDbEvent(dbSession, request))
105 .peek(checkPermissions())
106 .peek(checkModifiable())
107 .peek(checkVersionNameLength(request))
108 .map(updateNameAndDescription(request))
109 .peek(checkNonConflictingOtherEvents(dbSession))
110 .peek(updateInDb(dbSession))
113 .orElseThrow(() -> new IllegalStateException("Event not found"));
117 private Consumer<EventDto> updateInDb(DbSession dbSession) {
119 dbClient.eventDao().update(dbSession, event.getUuid(), event.getName(), event.getDescription());
120 if (VERSION.getLabel().equals(event.getCategory())) {
121 SnapshotDto analysis = getAnalysis(dbSession, event);
122 analysis.setProjectVersion(event.getName());
123 dbClient.snapshotDao().update(dbSession, analysis);
129 private EventDto getDbEvent(DbSession dbSession, UpdateEventRequest request) {
130 checkArgument(isNotBlank(request.getName()), "A non empty name is required");
131 return dbClient.eventDao().selectByUuid(dbSession, request.getEvent())
132 .orElseThrow(() -> new NotFoundException(format("Event '%s' not found", request.getEvent())));
135 private Consumer<EventDto> checkPermissions() {
136 return event -> userSession.checkComponentUuidPermission(UserRole.ADMIN, event.getComponentUuid());
139 private Consumer<EventDto> checkNonConflictingOtherEvents(DbSession dbSession) {
140 return candidateEvent -> {
141 List<EventDto> dbEvents = dbClient.eventDao().selectByAnalysisUuid(dbSession, candidateEvent.getAnalysisUuid());
142 Predicate<EventDto> otherEventWithSameName = otherEvent -> !candidateEvent.getUuid().equals(otherEvent.getUuid()) && otherEvent.getName().equals(candidateEvent.getName());
144 .filter(otherEventWithSameName)
146 .ifPresent(event -> {
147 throw new IllegalArgumentException(format("An '%s' event with the same name already exists on analysis '%s'",
148 candidateEvent.getCategory(),
149 candidateEvent.getAnalysisUuid()));
154 private static Consumer<EventDto> checkVersionNameLength(UpdateEventRequest request) {
155 return candidateEvent -> checkVersionName(candidateEvent.getCategory(), request.getName());
158 private SnapshotDto getAnalysis(DbSession dbSession, EventDto event) {
159 return dbClient.snapshotDao().selectByUuid(dbSession, event.getAnalysisUuid())
160 .orElseThrow(() -> new IllegalStateException(format("Analysis '%s' is not found", event.getAnalysisUuid())));
163 private static Function<EventDto, EventDto> updateNameAndDescription(UpdateEventRequest request) {
165 ofNullable(request.getName()).ifPresent(event::setName);
170 private static Function<EventDto, UpdateEventResponse> toWsResponse() {
172 Event.Builder wsEvent = Event.newBuilder()
173 .setKey(dbEvent.getUuid())
174 .setCategory(fromLabel(dbEvent.getCategory()).name())
175 .setAnalysis(dbEvent.getAnalysisUuid());
176 ofNullable(dbEvent.getName()).ifPresent(wsEvent::setName);
177 ofNullable(dbEvent.getDescription()).ifPresent(wsEvent::setDescription);
179 return UpdateEventResponse.newBuilder().setEvent(wsEvent).build();
183 private static Function<Request, UpdateEventRequest> toUpdateEventRequest() {
184 return request -> new UpdateEventRequest(
185 request.mandatoryParam(PARAM_EVENT),
186 request.param(PARAM_NAME));
189 private static class UpdateEventRequest {
190 private final String event;
191 private final String name;
193 public UpdateEventRequest(String event, String name) {
194 this.event = requireNonNull(event, "Event key is required");
195 this.name = requireNonNull(name, "Name is required");
198 public String getEvent() {
203 public String getName() {