repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/WebServerStatusNodeCheck.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.health;
import java.util.EnumSet;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
/**
* Checks the running status of the WebServer when it is not anymore in safemode.
*/
public class WebServerStatusNodeCheck implements NodeHealthCheck {
private static final EnumSet<DatabaseMigrationState.Status> VALID_DATABASEMIGRATION_STATUSES = EnumSet.of(
DatabaseMigrationState.Status.NONE, DatabaseMigrationState.Status.SUCCEEDED);
private final DatabaseMigrationState migrationState;
private final Platform platform;
private final RestartFlagHolder restartFlagHolder;
public WebServerStatusNodeCheck(DatabaseMigrationState migrationState, Platform platform, RestartFlagHolder restartFlagHolder) {
this.migrationState = migrationState;
this.platform = platform;
this.restartFlagHolder = restartFlagHolder;
}
@Override
public Health check() {
Platform.Status platformStatus = platform.status();
if (platformStatus == Platform.Status.UP
&& VALID_DATABASEMIGRATION_STATUSES.contains(migrationState.getStatus())
&& !restartFlagHolder.isRestarting()) {
return Health.GREEN;
}
return Health.builder()
.setStatus(Health.Status.RED)
.addCause("SonarQube webserver is not up")
.build();
}
}
| 2,245 | 37.724138 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.health;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/AddCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.ws.IssueUpdater;
public class AddCommentAction implements HotspotsWsAction {
private static final String PARAM_HOTSPOT_KEY = "hotspot";
private static final String PARAM_COMMENT = "comment";
private static final Integer MAXIMUM_COMMENT_LENGTH = 1000;
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
public AddCommentAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport,
IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("add_comment")
.setHandler(this)
.setPost(true)
.setDescription("Add a comment to a Security Hotpot.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified Security Hotspot.")
.setSince("8.1")
.setInternal(true);
action.createParam(PARAM_HOTSPOT_KEY)
.setDescription("Key of the Security Hotspot")
.setExampleValue(Uuids.UUID_EXAMPLE_03)
.setRequired(true);
action.createParam(PARAM_COMMENT)
.setDescription("Comment text.")
.setMaximumLength(MAXIMUM_COMMENT_LENGTH)
.setExampleValue("This is safe because user input is validated by the calling code")
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
hotspotWsSupport.checkLoggedIn();
String hotspotKey = request.mandatoryParam(PARAM_HOTSPOT_KEY);
String comment = request.mandatoryParam(PARAM_COMMENT);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto hotspot = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
hotspotWsSupport.loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
DefaultIssue defaultIssue = hotspot.toDefaultIssue();
IssueChangeContext context = hotspotWsSupport.newIssueChangeContextWithoutMeasureRefresh();
issueFieldsSetter.addComment(defaultIssue, comment, context);
issueUpdater.saveIssueAndPreloadSearchResponseData(dbSession, defaultIssue, context);
response.noContent();
}
}
}
| 3,782 | 39.677419 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/AssignAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.ws.IssueUpdater;
import org.sonar.server.pushapi.hotspots.HotspotChangeEventService;
import org.sonar.server.pushapi.hotspots.HotspotChangedEvent;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.api.issue.Issue.RESOLUTION_ACKNOWLEDGED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional;
public class AssignAction implements HotspotsWsAction {
private static final String ACTION_ASSIGN = "assign";
private static final String PARAM_HOTSPOT_KEY = "hotspot";
private static final String PARAM_ASSIGNEE = "assignee";
private static final String PARAM_COMMENT = "comment";
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final HotspotChangeEventService hotspotChangeEventService;
public AssignAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, IssueFieldsSetter issueFieldsSetter,
IssueUpdater issueUpdater, HotspotChangeEventService hotspotChangeEventService) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.hotspotChangeEventService = hotspotChangeEventService;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_ASSIGN)
.setDescription("Assign a hotspot to an active user. Requires authentication and Browse permission on project")
.setSince("8.2")
.setHandler(this)
.setInternal(true)
.setPost(true)
.setChangelog(
new Change("8.9", "Parameter 'assignee' is no longer mandatory"));
action.createParam(PARAM_HOTSPOT_KEY)
.setDescription("Hotspot key")
.setRequired(true)
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_ASSIGNEE)
.setDescription("Login of the assignee with 'Browse' project permission")
.setExampleValue("admin");
action.createParam(PARAM_COMMENT)
.setDescription("A comment provided with assign action")
.setExampleValue("Hey Bob! Could you please have a look and confirm my assertion that we are safe here, please");
}
@Override
public void handle(Request request, Response response) throws Exception {
String assignee = request.param(PARAM_ASSIGNEE);
String key = request.mandatoryParam(PARAM_HOTSPOT_KEY);
String comment = request.param(PARAM_COMMENT);
assign(key, assignee, comment);
response.noContent();
}
private void assign(String hotspotKey, String login, @Nullable String comment) {
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto hotspotDto = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
checkHotspotStatusAndResolution(hotspotDto);
hotspotWsSupport.loadAndCheckBranch(dbSession, hotspotDto, UserRole.USER);
UserDto assignee = isNullOrEmpty(login) ? null : getAssignee(dbSession, login);
IssueChangeContext context = hotspotWsSupport.newIssueChangeContextWithoutMeasureRefresh();
DefaultIssue defaultIssue = hotspotDto.toDefaultIssue();
if (comment != null) {
issueFieldsSetter.addComment(defaultIssue, comment, context);
}
if (assignee != null) {
checkAssigneeProjectPermission(dbSession, assignee, hotspotDto.getProjectUuid());
}
if (issueFieldsSetter.assign(defaultIssue, assignee, context)) {
issueUpdater.saveIssueAndPreloadSearchResponseData(dbSession, defaultIssue, context);
BranchDto branch = issueUpdater.getBranch(dbSession, defaultIssue);
if (BRANCH.equals(branch.getBranchType())) {
HotspotChangedEvent hotspotChangedEvent = buildEventData(defaultIssue, assignee, hotspotDto.getFilePath());
hotspotChangeEventService.distributeHotspotChangedEvent(branch.getProjectUuid(), hotspotChangedEvent);
}
}
}
}
private static void checkHotspotStatusAndResolution(IssueDto hotspotDto) {
if (!STATUS_TO_REVIEW.equals(hotspotDto.getStatus()) && !RESOLUTION_ACKNOWLEDGED.equals(hotspotDto.getResolution())) {
throw new IllegalArgumentException("Cannot change the assignee of this hotspot given its current status and resolution");
}
}
private UserDto getAssignee(DbSession dbSession, String assignee) {
return checkFound(dbClient.userDao().selectActiveUserByLogin(dbSession, assignee), "Unknown user: %s", assignee);
}
private void checkAssigneeProjectPermission(DbSession dbSession, UserDto assignee, String issueBranchUuid) {
ProjectDto project = checkFoundWithOptional(dbClient.projectDao().selectByBranchUuid(dbSession, issueBranchUuid),
"Could not find branch for issue");
if (project.isPrivate() && !hasProjectPermission(dbSession, assignee.getUuid(), project.getUuid())) {
throw new IllegalArgumentException(String.format("Provided user with login '%s' does not have 'Browse' permission to project", assignee.getLogin()));
}
}
private boolean hasProjectPermission(DbSession dbSession, String userUuid, String projectUuid) {
return dbClient.authorizationDao().selectEntityPermissions(dbSession, projectUuid, userUuid).contains(UserRole.USER);
}
private static HotspotChangedEvent buildEventData(DefaultIssue defaultIssue, @Nullable UserDto assignee, String filePath) {
return new HotspotChangedEvent.Builder()
.setKey(defaultIssue.key())
.setProjectKey(defaultIssue.projectKey())
.setStatus(defaultIssue.status())
.setResolution(defaultIssue.resolution())
.setUpdateDate(defaultIssue.updateDate())
.setAssignee(assignee == null ? null : assignee.getLogin())
.setFilePath(filePath)
.build();
}
}
| 7,561 | 42.211429 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/ChangeStatusAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.issue.DefaultTransitions;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.TransitionService;
import org.sonar.server.issue.ws.IssueUpdater;
import org.sonar.server.pushapi.hotspots.HotspotChangeEventService;
import org.sonar.server.pushapi.hotspots.HotspotChangedEvent;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.api.issue.Issue.RESOLUTION_ACKNOWLEDGED;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.SECURITY_HOTSPOT_RESOLUTIONS;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.db.component.BranchType.BRANCH;
public class ChangeStatusAction implements HotspotsWsAction {
private static final String PARAM_HOTSPOT_KEY = "hotspot";
private static final String PARAM_RESOLUTION = "resolution";
private static final String PARAM_STATUS = "status";
private static final String PARAM_COMMENT = "comment";
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
private final TransitionService transitionService;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final HotspotChangeEventService hotspotChangeEventService;
public ChangeStatusAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, TransitionService transitionService,
IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater, HotspotChangeEventService hotspotChangeEventService) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.transitionService = transitionService;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.hotspotChangeEventService = hotspotChangeEventService;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("change_status")
.setHandler(this)
.setPost(true)
.setDescription("Change the status of a Security Hotpot.<br/>" +
"Requires the 'Administer Security Hotspot' permission.")
.setSince("8.1")
.setChangelog(
new Change("10.1", "Endpoint visibility change from internal to public"));
action.createParam(PARAM_HOTSPOT_KEY)
.setDescription("Key of the Security Hotspot")
.setExampleValue(Uuids.UUID_EXAMPLE_03)
.setRequired(true);
action.createParam(PARAM_STATUS)
.setDescription("New status of the Security Hotspot.")
.setPossibleValues(STATUS_TO_REVIEW, STATUS_REVIEWED)
.setRequired(true);
action.createParam(PARAM_RESOLUTION)
.setDescription("Resolution of the Security Hotspot when new status is " + STATUS_REVIEWED + ", otherwise must not be set.")
.setPossibleValues(SECURITY_HOTSPOT_RESOLUTIONS);
action.createParam(PARAM_COMMENT)
.setDescription("Comment text.")
.setExampleValue("This is safe because user input is validated by the calling code");
}
@Override
public void handle(Request request, Response response) throws Exception {
hotspotWsSupport.checkLoggedIn();
String hotspotKey = request.mandatoryParam(PARAM_HOTSPOT_KEY);
String newStatus = request.mandatoryParam(PARAM_STATUS);
String newResolution = resolutionParam(request, newStatus);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto hotspot = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
hotspotWsSupport.loadAndCheckBranch(dbSession, hotspot, UserRole.SECURITYHOTSPOT_ADMIN);
if (needStatusUpdate(hotspot, newStatus, newResolution)) {
String transitionKey = toTransitionKey(newStatus, newResolution);
doTransition(dbSession, hotspot, transitionKey, trimToNull(request.param(PARAM_COMMENT)));
}
response.noContent();
}
}
@CheckForNull
private static String resolutionParam(Request request, String newStatus) {
String resolution = request.param(PARAM_RESOLUTION);
checkArgument(STATUS_REVIEWED.equals(newStatus) || resolution == null,
"Parameter '%s' must not be specified when Parameter '%s' has value '%s'",
PARAM_RESOLUTION, PARAM_STATUS, STATUS_TO_REVIEW);
checkArgument(STATUS_TO_REVIEW.equals(newStatus) || resolution != null,
"Parameter '%s' must be specified when Parameter '%s' has value '%s'",
PARAM_RESOLUTION, PARAM_STATUS, STATUS_REVIEWED);
return resolution;
}
private static boolean needStatusUpdate(IssueDto hotspot, String newStatus, @Nullable String newResolution) {
return !(hotspot.getStatus().equals(newStatus) && Objects.equals(hotspot.getResolution(), newResolution));
}
private static String toTransitionKey(String newStatus, String newResolution) {
if (STATUS_TO_REVIEW.equals(newStatus)) {
return DefaultTransitions.RESET_AS_TO_REVIEW;
}
if (STATUS_REVIEWED.equals(newStatus) && RESOLUTION_FIXED.equals(newResolution)) {
return DefaultTransitions.RESOLVE_AS_REVIEWED;
}
if (STATUS_REVIEWED.equals(newStatus) && RESOLUTION_ACKNOWLEDGED.equals(newResolution)) {
return DefaultTransitions.RESOLVE_AS_ACKNOWLEDGED;
}
return DefaultTransitions.RESOLVE_AS_SAFE;
}
private void doTransition(DbSession session, IssueDto issueDto, String transitionKey, @Nullable String comment) {
DefaultIssue defaultIssue = issueDto.toDefaultIssue();
IssueChangeContext context = hotspotWsSupport.newIssueChangeContextWithMeasureRefresh();
transitionService.checkTransitionPermission(transitionKey, defaultIssue);
if (transitionService.doTransition(defaultIssue, context, transitionKey)) {
if (comment != null) {
issueFieldsSetter.addComment(defaultIssue, comment, context);
}
issueUpdater.saveIssueAndPreloadSearchResponseData(session, defaultIssue, context);
BranchDto branch = issueUpdater.getBranch(session, defaultIssue);
if (BRANCH.equals(branch.getBranchType())) {
HotspotChangedEvent hotspotChangedEvent = buildEventData(defaultIssue, issueDto);
hotspotChangeEventService.distributeHotspotChangedEvent(branch.getProjectUuid(), hotspotChangedEvent);
}
}
}
private static HotspotChangedEvent buildEventData(DefaultIssue defaultIssue, IssueDto issueDto) {
return new HotspotChangedEvent.Builder()
.setKey(defaultIssue.key())
.setProjectKey(defaultIssue.projectKey())
.setStatus(defaultIssue.status())
.setResolution(defaultIssue.resolution())
.setUpdateDate(defaultIssue.updateDate())
.setAssignee(issueDto.getAssigneeLogin())
.setFilePath(issueDto.getFilePath())
.build();
}
}
| 8,255 | 42.914894 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/DeleteCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.Objects;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
public class DeleteCommentAction implements HotspotsWsAction {
private static final String PARAM_COMMENT = "comment";
private final UserSession userSession;
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
public DeleteCommentAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, UserSession userSession) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("delete_comment")
.setHandler(this)
.setPost(true)
.setDescription("Delete comment from Security Hotpot.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified Security Hotspot.")
.setSince("8.2")
.setInternal(true);
action.createParam(PARAM_COMMENT)
.setDescription("Comment key.")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
}
@Override
public void handle(Request request, Response response) throws Exception {
hotspotWsSupport.checkLoggedIn();
String commentKey = request.mandatoryParam(PARAM_COMMENT);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueChangeDto hotspotComment = getHotspotComment(commentKey, dbSession);
validate(dbSession, hotspotComment);
deleteComment(dbSession, hotspotComment.getKey());
response.noContent();
}
}
private IssueChangeDto getHotspotComment(String commentKey, DbSession dbSession) {
return dbClient.issueChangeDao().selectCommentByKey(dbSession, commentKey)
.orElseThrow(() -> new NotFoundException(format("Comment with key '%s' does not exist", commentKey)));
}
private void validate(DbSession dbSession, IssueChangeDto issueChangeDto) {
hotspotWsSupport.loadAndCheckBranch(dbSession, issueChangeDto.getIssueKey());
checkArgument(Objects.equals(issueChangeDto.getUserUuid(), userSession.getUuid()), "You can only delete your own comments");
}
private void deleteComment(DbSession dbSession, String commentKey) {
dbClient.issueChangeDao().deleteByKey(dbSession, commentKey);
}
}
| 3,646 | 37.797872 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/EditCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.user.UserDto;
import org.sonar.markdown.Markdown;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Common.Comment;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class EditCommentAction implements HotspotsWsAction {
private static final String PARAM_COMMENT = "comment";
private static final String PARAM_TEXT = "text";
private static final Integer MAXIMUM_COMMENT_LENGTH = 1000;
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
private final UserSession userSession;
private final System2 system2;
public EditCommentAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, UserSession userSession, System2 system2) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.userSession = userSession;
this.system2 = system2;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("edit_comment")
.setDescription("Edit a comment.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified hotspot.")
.setSince("8.2")
.setHandler(this)
.setPost(true)
.setInternal(true)
.setResponseExample(getClass().getResource("edit-comment-example.json"));
action.createParam(PARAM_COMMENT)
.setDescription("Comment key")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_TEXT)
.setDescription("Comment text")
.setMaximumLength(MAXIMUM_COMMENT_LENGTH)
.setRequired(true)
.setExampleValue("Safe because it doesn't apply to the context");
}
@Override
public void handle(Request request, Response response) throws Exception {
hotspotWsSupport.checkLoggedIn();
String commentKey = request.mandatoryParam(PARAM_COMMENT);
String text = request.mandatoryParam(PARAM_TEXT);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueChangeDto hotspotComment = getHotspotComment(commentKey, dbSession);
validate(dbSession, hotspotComment);
editComment(dbSession, hotspotComment, text);
Comment commentData = prepareResponse(dbSession, hotspotComment);
writeProtobuf(commentData, request, response);
}
}
private IssueChangeDto getHotspotComment(String commentKey, DbSession dbSession) {
return dbClient.issueChangeDao().selectCommentByKey(dbSession, commentKey)
.orElseThrow(() -> new NotFoundException(format("Comment with key '%s' does not exist", commentKey)));
}
private void validate(DbSession dbSession, IssueChangeDto issueChangeDto) {
hotspotWsSupport.loadAndCheckBranch(dbSession, issueChangeDto.getIssueKey());
checkArgument(Objects.equals(issueChangeDto.getUserUuid(), userSession.getUuid()), "You can only edit your own comments");
}
private void editComment(DbSession dbSession, IssueChangeDto hotspotComment, String text) {
hotspotComment.setUpdatedAt(system2.now());
hotspotComment.setChangeData(text);
dbClient.issueChangeDao().update(dbSession, hotspotComment);
dbSession.commit();
}
private Comment prepareResponse(DbSession dbSession, IssueChangeDto hotspotComment) {
Comment.Builder commentBuilder = Comment.newBuilder();
commentBuilder.clear()
.setKey(hotspotComment.getKey())
.setUpdatable(true)
.setCreatedAt(DateUtils.formatDateTime(new Date(hotspotComment.getIssueChangeCreationDate())));
getUserByUuid(dbSession, hotspotComment.getUserUuid()).ifPresent(user -> commentBuilder.setLogin(user.getLogin()));
String markdown = hotspotComment.getChangeData();
commentBuilder
.setHtmlText(Markdown.convertToHtml(markdown))
.setMarkdown(markdown);
return commentBuilder.build();
}
private Optional<UserDto> getUserByUuid(DbSession dbSession, String userUuid) {
return Optional.ofNullable(dbClient.userDao().selectByUuid(dbSession, userUuid));
}
}
| 5,489 | 39.970149 | 126 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotWsResponseFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import javax.annotation.Nullable;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
import org.sonarqube.ws.Hotspots;
import static java.util.Optional.ofNullable;
public class HotspotWsResponseFormatter {
public HotspotWsResponseFormatter() {
// nothing to do here
}
Hotspots.Component formatProject(Hotspots.Component.Builder builder, ProjectDto project, @Nullable String branch, @Nullable String pullRequest) {
builder
.clear()
.setKey(project.getKey())
.setQualifier(project.getQualifier())
.setName(project.getName())
.setLongName(project.getName());
ofNullable(branch).ifPresent(builder::setBranch);
ofNullable(pullRequest).ifPresent(builder::setPullRequest);
return builder.build();
}
Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
builder
.clear()
.setKey(component.getKey())
.setQualifier(component.qualifier())
.setName(component.name())
.setLongName(component.longName());
ofNullable(branch).ifPresent(builder::setBranch);
ofNullable(pullRequest).ifPresent(builder::setPullRequest);
ofNullable(component.path()).ifPresent(builder::setPath);
return builder.build();
}
Hotspots.Component formatComponent(Hotspots.Component.Builder builder, ComponentDto component, @Nullable BranchDto branchDto) {
if (branchDto == null || branchDto.isMain()) {
return formatComponent(builder, component, null, null);
}
return formatComponent(builder, component, branchDto.getBranchKey(), branchDto.getPullRequestKey());
}
}
| 2,617 | 36.942029 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotWsSupport.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.Date;
import org.sonar.api.issue.Issue;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
public class HotspotWsSupport {
private final DbClient dbClient;
private final UserSession userSession;
private final System2 system2;
public HotspotWsSupport(DbClient dbClient, UserSession userSession, System2 system2) {
this.dbClient = dbClient;
this.userSession = userSession;
this.system2 = system2;
}
String checkLoggedIn() {
return userSession.checkLoggedIn().getUuid();
}
ProjectAndBranch loadAndCheckBranch(DbSession dbSession, String hotspotKey) {
IssueDto hotspot = loadHotspot(dbSession, hotspotKey);
return loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
}
IssueDto loadHotspot(DbSession dbSession, String hotspotKey) {
return dbClient.issueDao().selectByKey(dbSession, hotspotKey)
.filter(t -> t.getType() == RuleType.SECURITY_HOTSPOT.getDbConstant())
.filter(t -> !Issue.STATUS_CLOSED.equals(t.getStatus()))
.orElseThrow(() -> new NotFoundException(format("Hotspot '%s' does not exist", hotspotKey)));
}
ProjectAndBranch loadAndCheckBranch(DbSession dbSession, IssueDto hotspot, String userRole) {
String branchUuid = hotspot.getProjectUuid();
checkArgument(branchUuid != null, "Hotspot '%s' has no branch", hotspot.getKee());
BranchDto branch = dbClient.branchDao().selectByUuid(dbSession, branchUuid)
.orElseThrow(() -> new NotFoundException(format("Branch with uuid '%s' does not exist", branchUuid)));
ProjectDto project = dbClient.projectDao().selectByUuid(dbSession, branch.getProjectUuid())
.orElseThrow(() -> new NotFoundException(format("Project with uuid '%s' does not exist", branch.getProjectUuid())));
userSession.checkEntityPermission(userRole, project);
return new ProjectAndBranch(project, branch);
}
boolean canChangeStatus(ProjectDto project) {
return userSession.hasEntityPermission(UserRole.SECURITYHOTSPOT_ADMIN, project);
}
IssueChangeContext newIssueChangeContextWithoutMeasureRefresh() {
return issueChangeContextByUserBuilder(new Date(system2.now()), checkLoggedIn()).build();
}
IssueChangeContext newIssueChangeContextWithMeasureRefresh() {
return issueChangeContextByUserBuilder(new Date(system2.now()), checkLoggedIn()).withRefreshMeasures().build();
}
}
| 3,876 | 40.688172 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotsWs.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import org.sonar.api.server.ws.WebService;
public class HotspotsWs implements WebService {
private final HotspotsWsAction[] actions;
public HotspotsWs(HotspotsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/hotspots");
controller.setDescription("Read and update Security Hotspots.");
controller.setSince("8.1");
for (HotspotsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,444 | 31.840909 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotsWsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import org.sonar.server.ws.WsAction;
public interface HotspotsWsAction extends WsAction {
// marker interface
}
| 996 | 35.925926 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/HotspotsWsModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import org.sonar.core.platform.Module;
public class HotspotsWsModule extends Module {
@Override
protected void configureModule() {
add(
HotspotWsResponseFormatter.class,
HotspotWsSupport.class,
AssignAction.class,
SearchAction.class,
ShowAction.class,
ChangeStatusAction.class,
AddCommentAction.class,
DeleteCommentAction.class,
EditCommentAction.class,
PullAction.class,
PullHotspotsActionProtobufObjectGenerator.class,
HotspotsWs.class);
}
}
| 1,408 | 32.547619 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/PullAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueQueryParams;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.ws.BasePullAction;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Common;
import static java.util.Collections.emptyList;
public class PullAction extends BasePullAction implements HotspotsWsAction {
private static final String ISSUE_TYPE = "hotspots";
private static final String ACTION_NAME = "pull";
private static final String RESOURCE_EXAMPLE = "pull-hotspot-example.proto";
private static final String SINCE_VERSION = "10.1";
private final DbClient dbClient;
public PullAction(System2 system2, ComponentFinder componentFinder, DbClient dbClient, UserSession userSession,
PullHotspotsActionProtobufObjectGenerator protobufObjectGenerator) {
super(system2, componentFinder, dbClient, userSession, protobufObjectGenerator, ACTION_NAME,
ISSUE_TYPE, "", SINCE_VERSION, RESOURCE_EXAMPLE);
this.dbClient = dbClient;
}
@Override
protected Set<String> getIssueKeysSnapshot(IssueQueryParams issueQueryParams, int page) {
Long changedSinceDate = issueQueryParams.getChangedSince();
try (DbSession dbSession = dbClient.openSession(false)) {
if (changedSinceDate != null) {
return dbClient.issueDao().selectIssueKeysByComponentUuidAndChangedSinceDate(dbSession, issueQueryParams.getBranchUuid(),
changedSinceDate, issueQueryParams.getRuleRepositories(), emptyList(),
issueQueryParams.getLanguages(), page);
}
return dbClient.issueDao().selectIssueKeysByComponentUuid(dbSession, issueQueryParams.getBranchUuid(),
issueQueryParams.getRuleRepositories(),
emptyList(), issueQueryParams.getLanguages(), page);
}
}
@Override
protected IssueQueryParams initializeQueryParams(BranchDto branchDto, @Nullable List<String> languages,
@Nullable List<String> ruleRepositories, boolean resolvedOnly, @Nullable Long changedSince) {
return new IssueQueryParams(branchDto.getUuid(), languages, emptyList(), emptyList(), false, changedSince);
}
@Override
protected boolean filterNonClosedIssues(IssueDto issueDto, IssueQueryParams queryParams) {
return issueDto.getType() == Common.RuleType.SECURITY_HOTSPOT_VALUE;
}
}
| 3,417 | 40.180723 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/PullHotspotsActionProtobufObjectGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import org.sonar.api.server.ServerSide;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.ws.pull.ProtobufObjectGenerator;
import org.sonar.server.security.SecurityStandards;
import org.sonarqube.ws.Hotspots;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
@ServerSide
public class PullHotspotsActionProtobufObjectGenerator implements ProtobufObjectGenerator {
@Override
public Hotspots.HotspotPullQueryTimestamp generateTimestampMessage(long timestamp) {
Hotspots.HotspotPullQueryTimestamp.Builder responseBuilder = Hotspots.HotspotPullQueryTimestamp.newBuilder();
responseBuilder.setQueryTimestamp(timestamp);
return responseBuilder.build();
}
@Override
public Hotspots.HotspotLite generateIssueMessage(IssueDto hotspotDto, RuleDto ruleDto) {
Hotspots.HotspotLite.Builder builder = Hotspots.HotspotLite.newBuilder()
.setKey(hotspotDto.getKey())
.setFilePath(hotspotDto.getFilePath())
.setCreationDate(hotspotDto.getCreatedAt())
.setStatus(hotspotDto.getStatus())
.setRuleKey(hotspotDto.getRuleKey().toString())
.setStatus(hotspotDto.getStatus())
.setVulnerabilityProbability(getVulnerabilityProbability(ruleDto));
String resolution = hotspotDto.getResolution();
if (resolution != null) {
builder.setResolution(resolution);
}
String assigneeLogin = hotspotDto.getAssigneeLogin();
if (assigneeLogin != null) {
builder.setAssignee(assigneeLogin);
}
String message = hotspotDto.getMessage();
if (message != null) {
builder.setMessage(message);
}
DbIssues.Locations mainLocation = hotspotDto.parseLocations();
if (mainLocation != null) {
Hotspots.TextRange textRange = getTextRange(mainLocation);
builder.setTextRange(textRange);
}
return builder.build();
}
private static String getVulnerabilityProbability(RuleDto ruleDto) {
SecurityStandards.SQCategory sqCategory = fromSecurityStandards(ruleDto.getSecurityStandards()).getSqCategory();
return sqCategory.getVulnerability().name();
}
private static Hotspots.TextRange getTextRange(DbIssues.Locations mainLocation) {
int startLine = mainLocation.getTextRange().getStartLine();
int endLine = mainLocation.getTextRange().getEndLine();
int startOffset = mainLocation.getTextRange().getStartOffset();
int endOffset = mainLocation.getTextRange().getEndOffset();
return Hotspots.TextRange.newBuilder()
.setHash(mainLocation.getChecksum())
.setStartLine(startLine)
.setEndLine(endLine)
.setStartLineOffset(startOffset)
.setEndLineOffset(endOffset)
.build();
}
@Override
public Hotspots.HotspotLite generateClosedIssueMessage(String uuid) {
return Hotspots.HotspotLite.newBuilder()
.setKey(uuid)
.setClosed(true)
.build();
}
}
| 3,835 | 35.884615 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/SearchAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.jetbrains.annotations.NotNull;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.Paging;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.TextRangeResponseFormatter;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.issue.index.IssueQuery;
import org.sonar.server.security.SecurityStandards;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.MessageFormattingUtils;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Hotspots;
import org.sonarqube.ws.Hotspots.SearchWsResponse;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static org.sonar.api.issue.Issue.RESOLUTION_ACKNOWLEDGED;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.RESOLUTION_SAFE;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.api.utils.DateUtils.longToDate;
import static org.sonar.api.utils.Paging.forPageIndex;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_INSECURE_INTERACTION;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_POROUS_DEFENSES;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_RISKY_RESOURCE;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.WsUtils.nullToEmpty;
public class SearchAction implements HotspotsWsAction {
private static final Set<String> SUPPORTED_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.APP);
private static final String PARAM_PROJECT_KEY = "projectKey";
private static final String PARAM_STATUS = "status";
private static final String PARAM_RESOLUTION = "resolution";
private static final String PARAM_HOTSPOTS = "hotspots";
private static final String PARAM_BRANCH = "branch";
private static final String PARAM_PULL_REQUEST = "pullRequest";
private static final String PARAM_IN_NEW_CODE_PERIOD = "inNewCodePeriod";
private static final String PARAM_ONLY_MINE = "onlyMine";
private static final String PARAM_OWASP_ASVS_LEVEL = "owaspAsvsLevel";
private static final String PARAM_PCI_DSS_32 = "pciDss-3.2";
private static final String PARAM_PCI_DSS_40 = "pciDss-4.0";
private static final String PARAM_OWASP_ASVS_40 = "owaspAsvs-4.0";
private static final String PARAM_OWASP_TOP_10_2017 = "owaspTop10";
private static final String PARAM_OWASP_TOP_10_2021 = "owaspTop10-2021";
/**
* @deprecated SansTop25 report is outdated, it has been completely deprecated in version 10.0 and will be removed from version 11.0
*/
@Deprecated(since = "10.0", forRemoval = true)
private static final String PARAM_SANS_TOP_25 = "sansTop25";
private static final String PARAM_SONARSOURCE_SECURITY = "sonarsourceSecurity";
private static final String PARAM_CWE = "cwe";
private static final String PARAM_FILES = "files";
private static final List<String> STATUSES = List.of(STATUS_TO_REVIEW, STATUS_REVIEWED);
private final DbClient dbClient;
private final UserSession userSession;
private final IssueIndex issueIndex;
private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
private final HotspotWsResponseFormatter responseFormatter;
private final TextRangeResponseFormatter textRangeFormatter;
private final System2 system2;
private final ComponentFinder componentFinder;
public SearchAction(DbClient dbClient, UserSession userSession, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker,
HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter, System2 system2, ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.userSession = userSession;
this.issueIndex = issueIndex;
this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
this.responseFormatter = responseFormatter;
this.textRangeFormatter = textRangeFormatter;
this.system2 = system2;
this.componentFinder = componentFinder;
}
private static Set<String> setFromList(@Nullable List<String> list) {
return list != null ? Set.copyOf(list) : Set.of();
}
private static WsRequest toWsRequest(Request request) {
Set<String> hotspotKeys = setFromList(request.paramAsStrings(PARAM_HOTSPOTS));
Set<String> pciDss32 = setFromList(request.paramAsStrings(PARAM_PCI_DSS_32));
Set<String> pciDss40 = setFromList(request.paramAsStrings(PARAM_PCI_DSS_40));
Set<String> owaspAsvs40 = setFromList(request.paramAsStrings(PARAM_OWASP_ASVS_40));
Set<String> owasp2017Top10 = setFromList(request.paramAsStrings(PARAM_OWASP_TOP_10_2017));
Set<String> owasp2021Top10 = setFromList(request.paramAsStrings(PARAM_OWASP_TOP_10_2021));
Set<String> sansTop25 = setFromList(request.paramAsStrings(PARAM_SANS_TOP_25));
Set<String> sonarsourceSecurity = setFromList(request.paramAsStrings(PARAM_SONARSOURCE_SECURITY));
Set<String> cwes = setFromList(request.paramAsStrings(PARAM_CWE));
Set<String> files = setFromList(request.paramAsStrings(PARAM_FILES));
return new WsRequest(
request.mandatoryParamAsInt(PAGE), request.mandatoryParamAsInt(PAGE_SIZE), request.param(PARAM_PROJECT_KEY), request.param(PARAM_BRANCH),
request.param(PARAM_PULL_REQUEST), hotspotKeys, request.param(PARAM_STATUS), request.param(PARAM_RESOLUTION),
request.paramAsBoolean(PARAM_IN_NEW_CODE_PERIOD), request.paramAsBoolean(PARAM_ONLY_MINE), request.paramAsInt(PARAM_OWASP_ASVS_LEVEL),
pciDss32, pciDss40, owaspAsvs40, owasp2017Top10, owasp2021Top10, sansTop25, sonarsourceSecurity, cwes, files);
}
@Override
public void handle(Request request, Response response) throws Exception {
WsRequest wsRequest = toWsRequest(request);
validateParameters(wsRequest);
try (DbSession dbSession = dbClient.openSession(false)) {
checkIfNeedIssueSync(dbSession, wsRequest);
Optional<ProjectAndBranch> project = getAndValidateProjectOrApplication(dbSession, wsRequest);
SearchResponseData searchResponseData = searchHotspots(wsRequest, dbSession, project.orElse(null));
loadComponents(dbSession, searchResponseData);
loadRules(dbSession, searchResponseData);
writeProtobuf(formatResponse(searchResponseData), request, response);
}
}
private void checkIfNeedIssueSync(DbSession dbSession, WsRequest wsRequest) {
Optional<String> projectKey = wsRequest.getProjectKey();
if (projectKey.isPresent()) {
issueIndexSyncProgressChecker.checkIfComponentNeedIssueSync(dbSession, projectKey.get());
} else {
// component keys not provided - asking for global
issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(dbSession);
}
}
private static void addSecurityStandardFilters(WsRequest wsRequest, IssueQuery.Builder builder) {
if (!wsRequest.getPciDss32().isEmpty()) {
builder.pciDss32(wsRequest.getPciDss32());
}
if (!wsRequest.getPciDss40().isEmpty()) {
builder.pciDss40(wsRequest.getPciDss40());
}
if (!wsRequest.getOwaspAsvs40().isEmpty()) {
builder.owaspAsvs40(wsRequest.getOwaspAsvs40());
wsRequest.getOwaspAsvsLevel().ifPresent(builder::owaspAsvsLevel);
}
if (!wsRequest.getOwaspTop10For2017().isEmpty()) {
builder.owaspTop10(wsRequest.getOwaspTop10For2017());
}
if (!wsRequest.getOwaspTop10For2021().isEmpty()) {
builder.owaspTop10For2021(wsRequest.getOwaspTop10For2021());
}
if (!wsRequest.getSansTop25().isEmpty()) {
builder.sansTop25(wsRequest.getSansTop25());
}
if (!wsRequest.getSonarsourceSecurity().isEmpty()) {
builder.sonarsourceSecurity(wsRequest.getSonarsourceSecurity());
}
if (!wsRequest.getCwe().isEmpty()) {
builder.cwe(wsRequest.getCwe());
}
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("search")
.setHandler(this)
.setDescription("Search for Security Hotpots. <br>"
+ "Requires the 'Browse' permission on the specified project(s). <br>"
+ "For applications, it also requires 'Browse' permission on its child projects. <br>"
+ "When issue indexation is in progress returns 503 service unavailable HTTP code.")
.setSince("8.1")
.setChangelog(
new Change("10.0", "Parameter 'sansTop25' is deprecated"),
new Change("9.6", "Added parameters 'pciDss-3.2' and 'pciDss-4.0"),
new Change("9.7", "Hotspot flows in the response may contain a description and a type"),
new Change("9.7", "Hotspot in the response contain the corresponding ruleKey"),
new Change("9.8", "Endpoint visibility change from internal to public"),
new Change("9.8", "Add message formatting to issue and locations response"));
action.addPagingParams(100);
action.createParam(PARAM_PROJECT_KEY)
.setDescription(format(
"Key of the project or application. This parameter is required unless %s is provided.",
PARAM_HOTSPOTS))
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setDescription("Branch key. Not available in the community edition.")
.setExampleValue(KEY_BRANCH_EXAMPLE_001);
action.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id. Not available in the community edition.")
.setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001);
action.createParam(PARAM_HOTSPOTS)
.setDescription(format(
"Comma-separated list of Security Hotspot keys. This parameter is required unless %s is provided.",
PARAM_PROJECT_KEY))
.setExampleValue("AWhXpLoInp4On-Y3xc8x");
action.createParam(PARAM_STATUS)
.setDescription("If '%s' is provided, only Security Hotspots with the specified status are returned.", PARAM_PROJECT_KEY)
.setPossibleValues(STATUSES)
.setRequired(false);
action.createParam(PARAM_RESOLUTION)
.setDescription(format(
"If '%s' is provided and if status is '%s', only Security Hotspots with the specified resolution are returned.",
PARAM_PROJECT_KEY, STATUS_REVIEWED))
.setPossibleValues(RESOLUTION_FIXED, RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED)
.setRequired(false);
action.createParam(PARAM_IN_NEW_CODE_PERIOD)
.setDescription("If '%s' is provided, only Security Hotspots created in the new code period are returned.", PARAM_IN_NEW_CODE_PERIOD)
.setBooleanPossibleValues()
.setDefaultValue("false")
.setSince("9.5");
action.createParam(PARAM_OWASP_ASVS_LEVEL)
.setDescription("Filters hotspots with lower or equal OWASP ASVS level to the parameter value. Should be used in combination with the 'owaspAsvs-4.0' parameter.")
.setSince("9.7")
.setPossibleValues(1, 2, 3)
.setRequired(false)
.setExampleValue("2");
action.createParam(PARAM_PCI_DSS_32)
.setDescription("Comma-separated list of PCI DSS v3.2 categories.")
.setSince("9.6")
.setExampleValue("4,6.5.8,10.1");
action.createParam(PARAM_PCI_DSS_40)
.setDescription("Comma-separated list of PCI DSS v4.0 categories.")
.setSince("9.6")
.setExampleValue("4,6.5.8,10.1");
action.createParam(PARAM_OWASP_ASVS_40)
.setDescription("Comma-separated list of OWASP ASVS v4.0 categories or rules.")
.setSince("9.7")
.setExampleValue("6,6.1.2");
action.createParam(PARAM_ONLY_MINE)
.setDescription("If 'projectKey' is provided, returns only Security Hotspots assigned to the current user")
.setBooleanPossibleValues()
.setRequired(false);
action.createParam(PARAM_OWASP_TOP_10_2017)
.setDescription("Comma-separated list of OWASP 2017 Top 10 lowercase categories.")
.setSince("8.6")
.setPossibleValues("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
action.createParam(PARAM_OWASP_TOP_10_2021)
.setDescription("Comma-separated list of OWASP 2021 Top 10 lowercase categories.")
.setSince("9.4")
.setPossibleValues("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
action.createParam(PARAM_SANS_TOP_25)
.setDescription("Comma-separated list of SANS Top 25 categories.")
.setDeprecatedSince("10.0")
.setSince("8.6")
.setPossibleValues(SANS_TOP_25_INSECURE_INTERACTION, SANS_TOP_25_RISKY_RESOURCE, SANS_TOP_25_POROUS_DEFENSES);
action.createParam(PARAM_SONARSOURCE_SECURITY)
.setDescription("Comma-separated list of SonarSource security categories. Use '" + SecurityStandards.SQCategory.OTHERS.getKey() +
"' to select issues not associated with any category")
.setSince("8.6")
.setPossibleValues(Arrays.stream(SecurityStandards.SQCategory.values()).map(SecurityStandards.SQCategory::getKey).toList());
action.createParam(PARAM_CWE)
.setDescription("Comma-separated list of CWE numbers")
.setExampleValue("89,434,352")
.setSince("8.8");
action.createParam(PARAM_FILES)
.setDescription("Comma-separated list of files. Returns only hotspots found in those files")
.setExampleValue("src/main/java/org/sonar/server/Test.java")
.setSince("9.0");
action.setResponseExample(getClass().getResource("search-example.json"));
}
private Optional<ProjectAndBranch> getAndValidateProjectOrApplication(DbSession dbSession, WsRequest wsRequest) {
return wsRequest.getProjectKey().map(projectKey -> {
ProjectAndBranch appOrProjectAndBranch = componentFinder.getAppOrProjectAndBranch(dbSession, projectKey, wsRequest.getBranch().orElse(null),
wsRequest.getPullRequest().orElse(null));
if (!SUPPORTED_QUALIFIERS.contains(appOrProjectAndBranch.getProject().getQualifier())) {
throw new NotFoundException(format("Project '%s' not found", projectKey));
}
userSession.checkEntityPermission(USER, appOrProjectAndBranch.getProject());
userSession.checkChildProjectsPermission(USER, appOrProjectAndBranch.getProject());
return appOrProjectAndBranch;
});
}
private SearchResponseData searchHotspots(WsRequest wsRequest, DbSession dbSession, @Nullable ProjectAndBranch projectorApp) {
SearchResponse result = doIndexSearch(wsRequest, dbSession, projectorApp);
result.getHits();
List<String> issueKeys = Arrays.stream(result.getHits().getHits())
.map(SearchHit::getId)
.toList();
List<IssueDto> hotspots = toIssueDtos(dbSession, issueKeys);
Paging paging = forPageIndex(wsRequest.getPage()).withPageSize(wsRequest.getIndex()).andTotal((int) getTotalHits(result).value);
return new SearchResponseData(paging, hotspots);
}
private static TotalHits getTotalHits(SearchResponse response) {
return ofNullable(response.getHits().getTotalHits()).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results"));
}
private List<IssueDto> toIssueDtos(DbSession dbSession, List<String> issueKeys) {
List<IssueDto> unorderedHotspots = dbClient.issueDao().selectByKeys(dbSession, issueKeys);
Map<String, IssueDto> hotspotsByKey = unorderedHotspots
.stream()
.collect(Collectors.toMap(IssueDto::getKey, Function.identity()));
return issueKeys.stream()
.map(hotspotsByKey::get)
.filter(Objects::nonNull)
.toList();
}
private SearchResponse doIndexSearch(WsRequest wsRequest, DbSession dbSession, @Nullable ProjectAndBranch projectOrAppAndBranch) {
var builder = IssueQuery.builder()
.types(singleton(RuleType.SECURITY_HOTSPOT.name()))
.sort(IssueQuery.SORT_HOTSPOTS)
.asc(true)
.statuses(wsRequest.getStatus().map(Collections::singletonList).orElse(STATUSES));
if (projectOrAppAndBranch != null) {
ProjectDto projectOrApp = projectOrAppAndBranch.getProject();
BranchDto projectOrAppBranch = projectOrAppAndBranch.getBranch();
if (Qualifiers.APP.equals(projectOrApp.getQualifier())) {
builder.viewUuids(singletonList(projectOrAppBranch.getUuid()));
if (wsRequest.isInNewCodePeriod() && wsRequest.getPullRequest().isEmpty()) {
addInNewCodePeriodFilterByProjects(builder, dbSession, projectOrAppBranch);
}
} else {
builder.projectUuids(singletonList(projectOrApp.getUuid()));
if (wsRequest.isInNewCodePeriod() && wsRequest.getPullRequest().isEmpty()) {
addInNewCodePeriodFilter(dbSession, projectOrAppBranch, builder);
}
}
addMainBranchFilter(projectOrAppAndBranch.getBranch(), builder);
}
if (!wsRequest.getHotspotKeys().isEmpty()) {
builder.issueKeys(wsRequest.getHotspotKeys());
}
if (!wsRequest.getFiles().isEmpty()) {
builder.files(wsRequest.getFiles());
}
if (wsRequest.isOnlyMine()) {
userSession.checkLoggedIn();
builder.assigneeUuids(Collections.singletonList(userSession.getUuid()));
}
wsRequest.getStatus().ifPresent(status -> builder.resolved(STATUS_REVIEWED.equals(status)));
wsRequest.getResolution().ifPresent(resolution -> builder.resolutions(singleton(resolution)));
addSecurityStandardFilters(wsRequest, builder);
IssueQuery query = builder.build();
SearchOptions searchOptions = new SearchOptions()
.setPage(wsRequest.page, wsRequest.index);
return issueIndex.search(query, searchOptions);
}
private void validateParameters(WsRequest wsRequest) {
Optional<String> projectKey = wsRequest.getProjectKey();
Optional<String> branch = wsRequest.getBranch();
Optional<String> pullRequest = wsRequest.getPullRequest();
Set<String> hotspotKeys = wsRequest.getHotspotKeys();
checkArgument(
projectKey.isPresent() || !hotspotKeys.isEmpty(),
"A value must be provided for either parameter '%s' or parameter '%s'", PARAM_PROJECT_KEY, PARAM_HOTSPOTS);
checkArgument(
branch.isEmpty() || projectKey.isPresent(),
"Parameter '%s' must be used with parameter '%s'", PARAM_BRANCH, PARAM_PROJECT_KEY);
checkArgument(
pullRequest.isEmpty() || projectKey.isPresent(),
"Parameter '%s' must be used with parameter '%s'", PARAM_PULL_REQUEST, PARAM_PROJECT_KEY);
checkArgument(
!(branch.isPresent() && pullRequest.isPresent()),
"Only one of parameters '%s' and '%s' can be provided", PARAM_BRANCH, PARAM_PULL_REQUEST);
Optional<String> status = wsRequest.getStatus();
Optional<String> resolution = wsRequest.getResolution();
checkArgument(status.isEmpty() || hotspotKeys.isEmpty(),
"Parameter '%s' can't be used with parameter '%s'", PARAM_STATUS, PARAM_HOTSPOTS);
checkArgument(resolution.isEmpty() || hotspotKeys.isEmpty(),
"Parameter '%s' can't be used with parameter '%s'", PARAM_RESOLUTION, PARAM_HOTSPOTS);
resolution.ifPresent(
r -> checkArgument(status.filter(STATUS_REVIEWED::equals).isPresent(),
"Value '%s' of parameter '%s' can only be provided if value of parameter '%s' is '%s'",
r, PARAM_RESOLUTION, PARAM_STATUS, STATUS_REVIEWED));
if (wsRequest.isOnlyMine()) {
checkArgument(userSession.isLoggedIn(),
"Parameter '%s' requires user to be logged in", PARAM_ONLY_MINE);
checkArgument(wsRequest.getProjectKey().isPresent(),
"Parameter '%s' can be used with parameter '%s' only", PARAM_ONLY_MINE, PARAM_PROJECT_KEY);
}
}
private static void addMainBranchFilter(@NotNull BranchDto branch, IssueQuery.Builder builder) {
if (branch.isMain()) {
builder.mainBranch(true);
} else {
builder.branchUuid(branch.getUuid());
builder.mainBranch(false);
}
}
private void addInNewCodePeriodFilter(DbSession dbSession, @NotNull BranchDto projectBranch, IssueQuery.Builder builder) {
Optional<SnapshotDto> snapshot = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, projectBranch.getUuid());
boolean isLastAnalysisUsingReferenceBranch = snapshot.map(SnapshotDto::getPeriodMode)
.orElse("").equals(REFERENCE_BRANCH.name());
if (isLastAnalysisUsingReferenceBranch) {
builder.newCodeOnReference(true);
} else {
var sinceDate = snapshot
.map(s -> longToDate(s.getPeriodDate()))
.orElseGet(() -> new Date(system2.now()));
builder.createdAfter(sinceDate, false);
}
}
private void addInNewCodePeriodFilterByProjects(IssueQuery.Builder builder, DbSession dbSession, BranchDto appBranch) {
Set<String> branchUuids;
if (appBranch.isMain()) {
branchUuids = dbClient.applicationProjectsDao().selectProjectsMainBranchesOfApplication(dbSession, appBranch.getProjectUuid()).stream()
.map(BranchDto::getUuid)
.collect(Collectors.toSet());
} else {
branchUuids = dbClient.applicationProjectsDao().selectProjectBranchesFromAppBranchUuid(dbSession, appBranch.getUuid()).stream()
.map(BranchDto::getUuid)
.collect(Collectors.toSet());
}
long now = system2.now();
List<SnapshotDto> snapshots = dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, branchUuids);
Set<String> newCodeReferenceByProjects = snapshots
.stream()
.filter(s -> !isNullOrEmpty(s.getPeriodMode()) && s.getPeriodMode().equals(REFERENCE_BRANCH.name()))
.map(SnapshotDto::getRootComponentUuid)
.collect(Collectors.toSet());
Map<String, IssueQuery.PeriodStart> leakByProjects = snapshots
.stream()
.filter(s -> isNullOrEmpty(s.getPeriodMode()) || !s.getPeriodMode().equals(REFERENCE_BRANCH.name()))
.collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, s1 -> new IssueQuery.PeriodStart(longToDate(s1.getPeriodDate() == null ? now : s1.getPeriodDate()), false)));
builder.createdAfterByProjectUuids(leakByProjects);
builder.newCodeOnReferenceByProjectUuids(newCodeReferenceByProjects);
}
private void loadComponents(DbSession dbSession, SearchResponseData searchResponseData) {
Set<String> componentUuids = searchResponseData.getOrderedHotspots().stream()
.flatMap(hotspot -> Stream.of(hotspot.getComponentUuid(), hotspot.getProjectUuid()))
.collect(Collectors.toSet());
Set<String> locationComponentUuids = searchResponseData.getOrderedHotspots()
.stream()
.flatMap(hotspot -> getHotspotLocationComponentUuids(hotspot).stream())
.collect(Collectors.toSet());
Set<String> aggregatedComponentUuids = Stream.of(componentUuids, locationComponentUuids)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
if (!aggregatedComponentUuids.isEmpty()) {
List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, aggregatedComponentUuids);
searchResponseData.addComponents(componentDtos);
Set<String> branchUuids = componentDtos.stream().map(c -> c.getCopyComponentUuid() != null ? c.getCopyComponentUuid() : c.branchUuid()).collect(Collectors.toSet());
List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
searchResponseData.addBranches(branchDtos);
}
}
private static Set<String> getHotspotLocationComponentUuids(IssueDto hotspot) {
Set<String> locationComponentUuids = new HashSet<>();
DbIssues.Locations locations = hotspot.parseLocations();
if (locations == null) {
return locationComponentUuids;
}
List<DbIssues.Flow> flows = locations.getFlowList();
for (DbIssues.Flow flow : flows) {
List<DbIssues.Location> flowLocations = flow.getLocationList();
for (DbIssues.Location location : flowLocations) {
if (location.hasComponentId()) {
locationComponentUuids.add(location.getComponentId());
}
}
}
return locationComponentUuids;
}
private void loadRules(DbSession dbSession, SearchResponseData searchResponseData) {
Set<RuleKey> ruleKeys = searchResponseData.getOrderedHotspots()
.stream()
.map(IssueDto::getRuleKey)
.collect(Collectors.toSet());
if (!ruleKeys.isEmpty()) {
searchResponseData.addRules(dbClient.ruleDao().selectByKeys(dbSession, ruleKeys));
}
}
private SearchWsResponse formatResponse(SearchResponseData searchResponseData) {
SearchWsResponse.Builder responseBuilder = SearchWsResponse.newBuilder();
formatPaging(searchResponseData, responseBuilder);
if (!searchResponseData.isEmpty()) {
formatHotspots(searchResponseData, responseBuilder);
formatComponents(searchResponseData, responseBuilder);
}
return responseBuilder.build();
}
private static void formatPaging(SearchResponseData searchResponseData, SearchWsResponse.Builder responseBuilder) {
Paging paging = searchResponseData.getPaging();
Common.Paging.Builder pagingBuilder = Common.Paging.newBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total());
responseBuilder.setPaging(pagingBuilder.build());
}
private void formatHotspots(SearchResponseData searchResponseData, SearchWsResponse.Builder responseBuilder) {
List<IssueDto> orderedHotspots = searchResponseData.getOrderedHotspots();
if (orderedHotspots.isEmpty()) {
return;
}
SearchWsResponse.Hotspot.Builder builder = SearchWsResponse.Hotspot.newBuilder();
for (IssueDto hotspot : orderedHotspots) {
RuleDto rule = searchResponseData.getRule(hotspot.getRuleKey())
// due to join with table Rule when retrieving data from Issues, this can't happen
.orElseThrow(() -> new IllegalStateException(format(
"Rule with key '%s' not found for Hotspot '%s'", hotspot.getRuleKey(), hotspot.getKey())));
SecurityStandards.SQCategory sqCategory = fromSecurityStandards(rule.getSecurityStandards()).getSqCategory();
builder
.clear()
.setKey(hotspot.getKey())
.setComponent(hotspot.getComponentKey())
.setProject(hotspot.getProjectKey())
.setSecurityCategory(sqCategory.getKey())
.setVulnerabilityProbability(sqCategory.getVulnerability().name())
.setRuleKey(hotspot.getRuleKey().toString());
ofNullable(hotspot.getStatus()).ifPresent(builder::setStatus);
ofNullable(hotspot.getResolution()).ifPresent(builder::setResolution);
ofNullable(hotspot.getLine()).ifPresent(builder::setLine);
builder.setMessage(nullToEmpty(hotspot.getMessage()));
builder.addAllMessageFormattings(MessageFormattingUtils.dbMessageFormattingToWs(hotspot.parseMessageFormattings()));
ofNullable(hotspot.getAssigneeUuid()).ifPresent(builder::setAssignee);
builder.setAuthor(nullToEmpty(hotspot.getAuthorLogin()));
builder.setCreationDate(formatDateTime(hotspot.getIssueCreationDate()));
builder.setUpdateDate(formatDateTime(hotspot.getIssueUpdateDate()));
completeHotspotLocations(hotspot, builder, searchResponseData);
responseBuilder.addHotspots(builder.build());
}
}
private void completeHotspotLocations(IssueDto hotspot, SearchWsResponse.Hotspot.Builder hotspotBuilder, SearchResponseData data) {
DbIssues.Locations locations = hotspot.parseLocations();
if (locations == null) {
return;
}
textRangeFormatter.formatTextRange(locations, hotspotBuilder::setTextRange);
hotspotBuilder.addAllFlows(textRangeFormatter.formatFlows(locations, hotspotBuilder.getComponent(), data.getComponentsByUuid()));
}
private void formatComponents(SearchResponseData searchResponseData, SearchWsResponse.Builder responseBuilder) {
Collection<ComponentDto> components = searchResponseData.getComponents();
if (components.isEmpty()) {
return;
}
Hotspots.Component.Builder builder = Hotspots.Component.newBuilder();
for (ComponentDto component : components) {
String branchUuid = component.getCopyComponentUuid() != null ? component.getCopyComponentUuid() : component.branchUuid();
BranchDto branchDto = searchResponseData.getBranch(branchUuid);
if (branchDto == null && component.getCopyComponentUuid() == null) {
throw new IllegalStateException("Could not find a branch for a component " + component.getKey() + " with uuid " + component.uuid());
}
responseBuilder.addComponents(responseFormatter.formatComponent(builder, component, branchDto));
}
}
private static final class WsRequest {
private final int page;
private final int index;
private final String projectKey;
private final String branch;
private final String pullRequest;
private final Set<String> hotspotKeys;
private final String status;
private final String resolution;
private final boolean inNewCodePeriod;
private final boolean onlyMine;
private final Integer owaspAsvsLevel;
private final Set<String> pciDss32;
private final Set<String> pciDss40;
private final Set<String> owaspAsvs40;
private final Set<String> owaspTop10For2017;
private final Set<String> owaspTop10For2021;
private final Set<String> sansTop25;
private final Set<String> sonarsourceSecurity;
private final Set<String> cwe;
private final Set<String> files;
private WsRequest(int page, int index,
@Nullable String projectKey, @Nullable String branch, @Nullable String pullRequest, Set<String> hotspotKeys,
@Nullable String status, @Nullable String resolution, @Nullable Boolean inNewCodePeriod, @Nullable Boolean onlyMine,
@Nullable Integer owaspAsvsLevel, Set<String> pciDss32, Set<String> pciDss40, Set<String> owaspAsvs40,
Set<String> owaspTop10For2017, Set<String> owaspTop10For2021, Set<String> sansTop25, Set<String> sonarsourceSecurity,
Set<String> cwe, @Nullable Set<String> files) {
this.page = page;
this.index = index;
this.projectKey = projectKey;
this.branch = branch;
this.pullRequest = pullRequest;
this.hotspotKeys = hotspotKeys;
this.status = status;
this.resolution = resolution;
this.inNewCodePeriod = inNewCodePeriod != null && inNewCodePeriod;
this.onlyMine = onlyMine != null && onlyMine;
this.owaspAsvsLevel = owaspAsvsLevel;
this.pciDss32 = pciDss32;
this.pciDss40 = pciDss40;
this.owaspAsvs40 = owaspAsvs40;
this.owaspTop10For2017 = owaspTop10For2017;
this.owaspTop10For2021 = owaspTop10For2021;
this.sansTop25 = sansTop25;
this.sonarsourceSecurity = sonarsourceSecurity;
this.cwe = cwe;
this.files = files;
}
int getPage() {
return page;
}
int getIndex() {
return index;
}
Optional<String> getProjectKey() {
return ofNullable(projectKey);
}
Optional<String> getBranch() {
return ofNullable(branch);
}
Optional<String> getPullRequest() {
return ofNullable(pullRequest);
}
Set<String> getHotspotKeys() {
return hotspotKeys;
}
Optional<String> getStatus() {
return ofNullable(status);
}
Optional<String> getResolution() {
return ofNullable(resolution);
}
boolean isInNewCodePeriod() {
return inNewCodePeriod;
}
boolean isOnlyMine() {
return onlyMine;
}
public Optional<Integer> getOwaspAsvsLevel() {
return ofNullable(owaspAsvsLevel);
}
public Set<String> getPciDss32() {
return pciDss32;
}
public Set<String> getPciDss40() {
return pciDss40;
}
public Set<String> getOwaspAsvs40() {
return owaspAsvs40;
}
public Set<String> getOwaspTop10For2017() {
return owaspTop10For2017;
}
public Set<String> getOwaspTop10For2021() {
return owaspTop10For2021;
}
public Set<String> getSansTop25() {
return sansTop25;
}
public Set<String> getSonarsourceSecurity() {
return sonarsourceSecurity;
}
public Set<String> getCwe() {
return cwe;
}
public Set<String> getFiles() {
return files;
}
}
private static final class SearchResponseData {
private final Paging paging;
private final List<IssueDto> orderedHotspots;
private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
private final Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
private final Map<String, BranchDto> branchesByBranchUuid = new HashMap<>();
private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots) {
this.paging = paging;
this.orderedHotspots = orderedHotspots;
}
boolean isEmpty() {
return orderedHotspots.isEmpty();
}
public Paging getPaging() {
return paging;
}
List<IssueDto> getOrderedHotspots() {
return orderedHotspots;
}
void addComponents(Collection<ComponentDto> components) {
for (ComponentDto component : components) {
componentsByUuid.put(component.uuid(), component);
}
}
public void addBranches(List<BranchDto> branchDtos) {
for (BranchDto branch : branchDtos) {
branchesByBranchUuid.put(branch.getUuid(), branch);
}
}
public BranchDto getBranch(String branchUuid) {
return branchesByBranchUuid.get(branchUuid);
}
Collection<ComponentDto> getComponents() {
return componentsByUuid.values();
}
public Map<String, ComponentDto> getComponentsByUuid() {
return componentsByUuid;
}
void addRules(Collection<RuleDto> rules) {
rules.forEach(t -> rulesByRuleKey.put(t.getKey(), t));
}
Optional<RuleDto> getRule(RuleKey ruleKey) {
return ofNullable(rulesByRuleKey.get(ruleKey));
}
}
}
| 36,748 | 42.489941 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/ShowAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.hotspot.ws;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.protobuf.DbIssues.Locations;
import org.sonar.db.rule.RuleDescriptionSectionContextDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.markdown.Markdown;
import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.IssueChangeWSSupport;
import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext;
import org.sonar.server.issue.IssueChangeWSSupport.Load;
import org.sonar.server.issue.TextRangeResponseFormatter;
import org.sonar.server.issue.ws.UserResponseFormatter;
import org.sonar.server.security.SecurityStandards;
import org.sonar.server.ws.MessageFormattingUtils;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Hotspots;
import org.sonarqube.ws.Hotspots.ShowWsResponse;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Sets.difference;
import static java.lang.String.format;
import static java.util.Collections.singleton;
import static java.util.Comparator.comparing;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ShowAction implements HotspotsWsAction {
private static final String PARAM_HOTSPOT_KEY = "hotspot";
private final DbClient dbClient;
private final HotspotWsSupport hotspotWsSupport;
private final HotspotWsResponseFormatter responseFormatter;
private final TextRangeResponseFormatter textRangeFormatter;
private final UserResponseFormatter userFormatter;
private final IssueChangeWSSupport issueChangeSupport;
public ShowAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter,
UserResponseFormatter userFormatter, IssueChangeWSSupport issueChangeSupport) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.responseFormatter = responseFormatter;
this.textRangeFormatter = textRangeFormatter;
this.userFormatter = userFormatter;
this.issueChangeSupport = issueChangeSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("show")
.setHandler(this)
.setDescription("Provides the details of a Security Hotspot.")
.setSince("8.1")
.setChangelog(
new Change("10.1", "Add the 'codeVariants' response field"),
new Change("9.5", "The fields rule.riskDescription, rule.fixRecommendations, rule.vulnerabilityDescription of the response are deprecated."
+ " /api/rules/show endpoint should be used to fetch rule descriptions."),
new Change("9.7", "Hotspot flows in the response may contain a description and a type"),
new Change("9.8", "Add message formatting to issue and locations response"));
action.createParam(PARAM_HOTSPOT_KEY)
.setDescription("Key of the Security Hotspot")
.setExampleValue(Uuids.UUID_EXAMPLE_03)
.setRequired(true);
action.setResponseExample(getClass().getResource("show-example.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
String hotspotKey = request.mandatoryParam(PARAM_HOTSPOT_KEY);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto hotspot = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
Components components = loadComponents(dbSession, hotspot);
Users users = loadUsers(dbSession, hotspot);
RuleDto rule = loadRule(dbSession, hotspot);
ShowWsResponse.Builder responseBuilder = ShowWsResponse.newBuilder();
formatHotspot(responseBuilder, hotspot, users);
formatComponents(components, responseBuilder);
formatRule(responseBuilder, rule);
formatTextRange(responseBuilder, hotspot);
formatFlows(dbSession, responseBuilder, hotspot);
FormattingContext formattingContext = formatChangeLogAndComments(dbSession, hotspot, users, components, responseBuilder);
formatUsers(responseBuilder, users, formattingContext);
writeProtobuf(responseBuilder.build(), request, response);
}
}
private Users loadUsers(DbSession dbSession, IssueDto hotspot) {
UserDto assignee = ofNullable(hotspot.getAssigneeUuid())
.map(uuid -> dbClient.userDao().selectByUuid(dbSession, uuid))
.orElse(null);
UserDto author = ofNullable(hotspot.getAuthorLogin())
.map(login -> {
if (assignee != null && assignee.getLogin().equals(login)) {
return assignee;
}
return dbClient.userDao().selectByLogin(dbSession, login);
})
.orElse(null);
return new Users(assignee, author);
}
private static void formatHotspot(ShowWsResponse.Builder builder, IssueDto hotspot, Users users) {
builder.setKey(hotspot.getKey());
ofNullable(hotspot.getStatus()).ifPresent(builder::setStatus);
ofNullable(hotspot.getResolution()).ifPresent(builder::setResolution);
ofNullable(hotspot.getLine()).ifPresent(builder::setLine);
ofNullable(emptyToNull(hotspot.getChecksum())).ifPresent(builder::setHash);
builder.setMessage(nullToEmpty(hotspot.getMessage()));
builder.addAllMessageFormattings(MessageFormattingUtils.dbMessageFormattingToWs(hotspot.parseMessageFormattings()));
builder.setCreationDate(formatDateTime(hotspot.getIssueCreationDate()));
builder.setUpdateDate(formatDateTime(hotspot.getIssueUpdateDate()));
users.getAssignee().map(UserDto::getLogin).ifPresent(builder::setAssignee);
Optional.ofNullable(hotspot.getAuthorLogin()).ifPresent(builder::setAuthor);
builder.addAllCodeVariants(hotspot.getCodeVariants());
}
private void formatComponents(Components components, ShowWsResponse.Builder responseBuilder) {
responseBuilder
.setProject(responseFormatter.formatProject(Hotspots.Component.newBuilder(), components.getProjectDto(), components.getBranch(), components.getPullRequest()))
.setComponent(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getComponent(), components.getBranch(), components.getPullRequest()));
responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProjectDto()));
}
private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDto ruleDto) {
SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(ruleDto.getSecurityStandards());
SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
Hotspots.Rule.Builder ruleBuilder = Hotspots.Rule.newBuilder()
.setKey(ruleDto.getKey().toString())
.setName(nullToEmpty(ruleDto.getName()))
.setSecurityCategory(sqCategory.getKey())
.setVulnerabilityProbability(sqCategory.getVulnerability().name());
Map<String, String> sectionKeyToContent = getSectionKeyToContent(ruleDto);
Optional.ofNullable(sectionKeyToContent.get(DEFAULT_KEY)).ifPresent(ruleBuilder::setRiskDescription);
Optional.ofNullable(sectionKeyToContent.get(ROOT_CAUSE_SECTION_KEY)).ifPresent(ruleBuilder::setRiskDescription);
Optional.ofNullable(sectionKeyToContent.get(ASSESS_THE_PROBLEM_SECTION_KEY)).ifPresent(ruleBuilder::setVulnerabilityDescription);
Optional.ofNullable(sectionKeyToContent.get(HOW_TO_FIX_SECTION_KEY)).ifPresent(ruleBuilder::setFixRecommendations);
responseBuilder.setRule(ruleBuilder.build());
}
private static Map<String, String> getSectionKeyToContent(RuleDto ruleDefinitionDto) {
return ruleDefinitionDto.getRuleDescriptionSectionDtos().stream()
.sorted(comparing(r -> Optional.ofNullable(r.getContext())
.map(RuleDescriptionSectionContextDto::getKey).orElse("")))
.collect(toMap(
RuleDescriptionSectionDto::getKey,
section -> getContentAndConvertToHtmlIfNecessary(ruleDefinitionDto.getDescriptionFormat(), section),
(a, b) -> a));
}
private static String getContentAndConvertToHtmlIfNecessary(@Nullable RuleDto.Format descriptionFormat, RuleDescriptionSectionDto section) {
if (RuleDto.Format.MARKDOWN.equals(descriptionFormat)) {
return Markdown.convertToHtml(section.getContent());
}
return section.getContent();
}
private void formatTextRange(ShowWsResponse.Builder hotspotBuilder, IssueDto hotspot) {
textRangeFormatter.formatTextRange(hotspot, hotspotBuilder::setTextRange);
}
private void formatFlows(DbSession dbSession, ShowWsResponse.Builder hotspotBuilder, IssueDto hotspot) {
DbIssues.Locations locations = hotspot.parseLocations();
if (locations == null) {
return;
}
Set<String> componentUuids = readComponentUuidsFromLocations(hotspot, locations);
Map<String, ComponentDto> componentsByUuids = loadComponents(dbSession, componentUuids);
hotspotBuilder.addAllFlows(textRangeFormatter.formatFlows(locations, hotspotBuilder.getComponent().getKey(), componentsByUuids));
}
private static Set<String> readComponentUuidsFromLocations(IssueDto hotspot, Locations locations) {
Set<String> componentUuids = new HashSet<>();
componentUuids.add(hotspot.getComponentUuid());
for (DbIssues.Flow flow : locations.getFlowList()) {
for (DbIssues.Location location : flow.getLocationList()) {
if (location.hasComponentId()) {
componentUuids.add(location.getComponentId());
}
}
}
return componentUuids;
}
private Map<String, ComponentDto> loadComponents(DbSession dbSession, Set<String> componentUuids) {
Map<String, ComponentDto> componentsByUuids = dbClient.componentDao().selectSubProjectsByComponentUuids(dbSession,
componentUuids)
.stream()
.collect(toMap(ComponentDto::uuid, Function.identity(), (componentDto, componentDto2) -> componentDto2));
Set<String> componentUuidsToLoad = copyOf(difference(componentUuids, componentsByUuids.keySet()));
if (!componentUuidsToLoad.isEmpty()) {
dbClient.componentDao().selectByUuids(dbSession, componentUuidsToLoad)
.forEach(c -> componentsByUuids.put(c.uuid(), c));
}
return componentsByUuids;
}
private FormattingContext formatChangeLogAndComments(DbSession dbSession, IssueDto hotspot, Users users, Components components, ShowWsResponse.Builder responseBuilder) {
Set<UserDto> preloadedUsers = Stream.of(users.getAssignee(), users.getAuthor())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
FormattingContext formattingContext = issueChangeSupport
.newFormattingContext(dbSession, singleton(hotspot), Load.ALL, preloadedUsers, Set.of(components.component));
issueChangeSupport.formatChangelog(hotspot, formattingContext)
.forEach(responseBuilder::addChangelog);
issueChangeSupport.formatComments(hotspot, Common.Comment.newBuilder(), formattingContext)
.forEach(responseBuilder::addComment);
return formattingContext;
}
private void formatUsers(ShowWsResponse.Builder responseBuilder, Users users, FormattingContext formattingContext) {
Common.User.Builder userBuilder = Common.User.newBuilder();
Stream.concat(
Stream.of(users.getAssignee(), users.getAuthor())
.filter(Optional::isPresent)
.map(Optional::get),
formattingContext.getUsers().stream())
.distinct()
.map(user -> userFormatter.formatUser(userBuilder, user))
.forEach(responseBuilder::addUsers);
}
private RuleDto loadRule(DbSession dbSession, IssueDto hotspot) {
RuleKey ruleKey = hotspot.getRuleKey();
return dbClient.ruleDao().selectByKey(dbSession, ruleKey)
.orElseThrow(() -> new NotFoundException(format("Rule '%s' does not exist", ruleKey)));
}
private Components loadComponents(DbSession dbSession, IssueDto hotspot) {
String componentUuid = hotspot.getComponentUuid();
checkArgument(componentUuid != null, "Hotspot '%s' has no component", hotspot.getKee());
ProjectAndBranch projectAndBranch = hotspotWsSupport.loadAndCheckBranch(dbSession, hotspot, UserRole.USER);
BranchDto branch = projectAndBranch.getBranch();
ComponentDto component = dbClient.componentDao().selectByUuid(dbSession, componentUuid)
.orElseThrow(() -> new NotFoundException(format("Component with uuid '%s' does not exist", componentUuid)));
boolean hotspotOnBranch = Objects.equals(branch.getUuid(), componentUuid);
return new Components(projectAndBranch.getProject(), component, branch);
}
private static final class Components {
private final ProjectDto project;
private final ComponentDto component;
private final String branch;
private final String pullRequest;
private Components(ProjectDto projectDto, ComponentDto component, BranchDto branch) {
this.project = projectDto;
this.component = component;
if (branch.isMain()) {
this.branch = null;
this.pullRequest = null;
} else if (branch.getBranchType() == BranchType.BRANCH) {
this.branch = branch.getKey();
this.pullRequest = null;
} else {
this.branch = null;
this.pullRequest = branch.getKey();
}
}
public ProjectDto getProjectDto() {
return project;
}
@CheckForNull
public String getBranch() {
return branch;
}
@CheckForNull
public String getPullRequest() {
return pullRequest;
}
public ComponentDto getComponent() {
return component;
}
}
private static final class Users {
@CheckForNull
private final UserDto assignee;
@CheckForNull
private final UserDto author;
private Users(@Nullable UserDto assignee, @Nullable UserDto author) {
this.assignee = assignee;
this.author = author;
}
public Optional<UserDto> getAssignee() {
return ofNullable(assignee);
}
public Optional<UserDto> getAuthor() {
return ofNullable(author);
}
}
}
| 16,507 | 43.376344 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/hotspot/ws/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.hotspot.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/AbstractChangeTagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.rule.RuleTagFormat;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.user.UserSession;
@ServerSide
public abstract class AbstractChangeTagsAction extends Action {
public static final String TAGS_PARAMETER = "tags";
private static final Splitter TAGS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
private final IssueFieldsSetter issueUpdater;
protected AbstractChangeTagsAction(String key, IssueFieldsSetter issueUpdater) {
super(key);
this.issueUpdater = issueUpdater;
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
parseTags(properties);
return true;
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
Collection<String> tags = getTagsToSet(context, parseTags(properties));
return issueUpdater.setTags(context.issue(), tags, context.issueChangeContext());
}
protected abstract Collection<String> getTagsToSet(Context context, Collection<String> tagsFromParams);
@Override
public boolean shouldRefreshMeasures() {
return false;
}
private static Set<String> parseTags(Map<String, Object> properties) {
Set<String> result = new HashSet<>();
String tagsString = (String) properties.get(TAGS_PARAMETER);
if (!Strings.isNullOrEmpty(tagsString)) {
for (String tag : TAGS_SPLITTER.split(tagsString)) {
RuleTagFormat.validate(tag);
result.add(tag);
}
}
return result;
}
}
| 2,653 | 33.025641 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/Action.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.issue.workflow.Condition;
import org.sonar.server.user.UserSession;
import static com.google.common.collect.Lists.newArrayList;
/**
* @since 3.7
*/
@ServerSide
public abstract class Action {
private final String key;
private final List<Condition> conditions;
protected Action(String key) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key), "Action key must be set");
this.key = key;
this.conditions = newArrayList();
}
public String key() {
return key;
}
public Action setConditions(Condition... conditions) {
this.conditions.addAll(ImmutableList.copyOf(conditions));
return this;
}
public List<Condition> conditions() {
return conditions;
}
public boolean supports(DefaultIssue issue) {
for (Condition condition : conditions) {
if (!condition.matches(issue)) {
return false;
}
}
return true;
}
public abstract boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession);
public abstract boolean execute(Map<String, Object> properties, Context context);
public abstract boolean shouldRefreshMeasures();
public interface Context {
DefaultIssue issue();
IssueChangeContext issueChangeContext();
ComponentDto project();
}
}
| 2,576 | 27.955056 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ActionContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.component.ComponentDto;
public class ActionContext implements Action.Context {
private final DefaultIssue issue;
private final IssueChangeContext changeContext;
private final ComponentDto project;
public ActionContext(DefaultIssue issue, IssueChangeContext changeContext, ComponentDto project) {
this.issue = issue;
this.changeContext = changeContext;
this.project = project;
}
@Override
public DefaultIssue issue() {
return issue;
}
@Override
public IssueChangeContext issueChangeContext() {
return changeContext;
}
@Override
public ComponentDto project() {
return project;
}
}
| 1,622 | 30.211538 | 100 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/AddTagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.sonar.api.server.ServerSide;
@ServerSide
public class AddTagsAction extends AbstractChangeTagsAction {
public static final String KEY = "add_tags";
public AddTagsAction(IssueFieldsSetter issueUpdater) {
super(KEY, issueUpdater);
}
@Override
protected Collection<String> getTagsToSet(Context context, Collection<String> tagsFromParams) {
Set<String> allTags = new HashSet<>(context.issue().tags());
allTags.addAll(tagsFromParams);
return allTags;
}
}
| 1,446 | 32.651163 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/AssignAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.workflow.IsUnResolved;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
@ServerSide
public class AssignAction extends Action {
public static final String ASSIGN_KEY = "assign";
public static final String ASSIGNEE_PARAMETER = "assignee";
private static final String VERIFIED_ASSIGNEE = "verifiedAssignee";
private final DbClient dbClient;
private final IssueFieldsSetter issueFieldsSetter;
public AssignAction(DbClient dbClient, IssueFieldsSetter issueFieldsSetter) {
super(ASSIGN_KEY);
this.dbClient = dbClient;
this.issueFieldsSetter = issueFieldsSetter;
super.setConditions(new IsUnResolved());
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
String assigneeLogin = getAssigneeValue(properties);
UserDto assignee = isNullOrEmpty(assigneeLogin) ? null : getUser(assigneeLogin);
properties.put(VERIFIED_ASSIGNEE, assignee);
return true;
}
private static String getAssigneeValue(Map<String, Object> properties) {
return (String) properties.get(ASSIGNEE_PARAMETER);
}
private UserDto getUser(String assigneeKey) {
try (DbSession dbSession = dbClient.openSession(false)) {
return checkFound(dbClient.userDao().selectActiveUserByLogin(dbSession, assigneeKey), "Unknown user: %s", assigneeKey);
}
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
checkArgument(properties.containsKey(VERIFIED_ASSIGNEE), "Assignee is missing from the execution parameters");
UserDto assignee = (UserDto) properties.get(VERIFIED_ASSIGNEE);
return issueFieldsSetter.assign(context.issue(), assignee, context.issueChangeContext());
}
@Override
public boolean shouldRefreshMeasures() {
return false;
}
}
| 3,133 | 36.759036 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/AvatarResolver.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import org.sonar.db.user.UserDto;
public interface AvatarResolver {
/**
* Creates an avatar ID to load a user's avatar (ex: Gravatar identified by an email hash)
*/
String create(UserDto user);
}
| 1,084 | 34 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/AvatarResolverImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.hash.Hashing;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Strings.emptyToNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
public class AvatarResolverImpl implements AvatarResolver {
@Override
public String create(UserDto user) {
UserDto userDto = requireNonNull(user, "User cannot be null");
return hash(requireNonNull(emptyToNull(userDto.getEmail()), "Email cannot be null"));
}
private static String hash(String text) {
return Hashing.md5().hashString(text.toLowerCase(ENGLISH), UTF_8).toString();
}
}
| 1,558 | 36.119048 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/CommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Strings;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.user.UserSession;
@ServerSide
public class CommentAction extends Action {
public static final String COMMENT_KEY = "comment";
public static final String COMMENT_PROPERTY = "comment";
private final IssueFieldsSetter issueUpdater;
public CommentAction(IssueFieldsSetter issueUpdater) {
super(COMMENT_KEY);
this.issueUpdater = issueUpdater;
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
comment(properties);
return true;
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
issueUpdater.addComment(context.issue(), comment(properties), context.issueChangeContext());
return true;
}
@Override
public boolean shouldRefreshMeasures() {
return false;
}
private static String comment(Map<String, Object> properties) {
String param = (String) properties.get(COMMENT_PROPERTY);
if (Strings.isNullOrEmpty(param)) {
throw new IllegalArgumentException("Missing parameter : '" + COMMENT_PROPERTY + "'");
}
return param;
}
}
| 2,185 | 31.626866 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/IssueChangePostProcessor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.List;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
@ServerSide
public interface IssueChangePostProcessor {
/**
* Refresh measures, quality gate status and send webhooks
*
* @param components the components of changed issues
*/
void process(DbSession dbSession, List<DefaultIssue> changedIssues, Collection<ComponentDto> components, boolean fromAlm);
}
| 1,405 | 34.15 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/IssueChangePostProcessorImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.List;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.measure.live.LiveMeasureComputer;
import org.sonar.server.qualitygate.changeevent.QGChangeEvent;
import org.sonar.server.qualitygate.changeevent.QGChangeEventListeners;
public class IssueChangePostProcessorImpl implements IssueChangePostProcessor {
private final LiveMeasureComputer liveMeasureComputer;
private final QGChangeEventListeners qualityGateListeners;
public IssueChangePostProcessorImpl(LiveMeasureComputer liveMeasureComputer, QGChangeEventListeners qualityGateListeners) {
this.liveMeasureComputer = liveMeasureComputer;
this.qualityGateListeners = qualityGateListeners;
}
@Override
public void process(DbSession dbSession, List<DefaultIssue> changedIssues, Collection<ComponentDto> components, boolean fromAlm) {
List<QGChangeEvent> gateChangeEvents = liveMeasureComputer.refresh(dbSession, components);
qualityGateListeners.broadcastOnIssueChange(changedIssues, gateChangeEvents, fromAlm);
}
}
| 2,013 | 41.851064 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/IssueChangeWSSupport.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.utils.DateUtils;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.user.UserDto;
import org.sonar.markdown.Markdown;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Common;
import static com.google.common.base.Strings.emptyToNull;
import static java.util.Collections.emptyMap;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.db.issue.IssueChangeDto.TYPE_COMMENT;
import static org.sonar.db.issue.IssueChangeDto.TYPE_FIELD_CHANGE;
import static org.sonar.server.issue.IssueFieldsSetter.FILE;
import static org.sonar.server.issue.IssueFieldsSetter.TECHNICAL_DEBT;
public class IssueChangeWSSupport {
private static final String EFFORT_CHANGELOG_KEY = "effort";
private final DbClient dbClient;
private final AvatarResolver avatarFactory;
private final UserSession userSession;
public IssueChangeWSSupport(DbClient dbClient, AvatarResolver avatarFactory, UserSession userSession) {
this.dbClient = dbClient;
this.avatarFactory = avatarFactory;
this.userSession = userSession;
}
public enum Load {
CHANGE_LOG, COMMENTS, ALL
}
public interface FormattingContext {
List<FieldDiffs> getChanges(IssueDto dto);
List<IssueChangeDto> getComments(IssueDto dto);
Set<UserDto> getUsers();
Optional<UserDto> getUserByUuid(@Nullable String uuid);
Optional<ComponentDto> getFileByUuid(@Nullable String uuid);
boolean isUpdatableComment(IssueChangeDto comment);
}
public FormattingContext newFormattingContext(DbSession dbSession, Set<IssueDto> dtos, Load load) {
return newFormattingContext(dbSession, dtos, load, Set.of(), Set.of());
}
public FormattingContext newFormattingContext(DbSession dbSession, Set<IssueDto> dtos, Load load, Set<UserDto> preloadedUsers, Set<ComponentDto> preloadedComponents) {
Set<String> issueKeys = dtos.stream().map(IssueDto::getKey).collect(Collectors.toSet());
List<IssueChangeDto> changes = List.of();
List<IssueChangeDto> comments = List.of();
switch (load) {
case CHANGE_LOG:
changes = dbClient.issueChangeDao().selectByTypeAndIssueKeys(dbSession, issueKeys, TYPE_FIELD_CHANGE);
break;
case COMMENTS:
comments = dbClient.issueChangeDao().selectByTypeAndIssueKeys(dbSession, issueKeys, TYPE_COMMENT);
break;
case ALL:
List<IssueChangeDto> all = dbClient.issueChangeDao().selectByIssueKeys(dbSession, issueKeys);
changes = all.stream()
.filter(t -> TYPE_FIELD_CHANGE.equals(t.getChangeType()))
.toList();
comments = all.stream()
.filter(t -> TYPE_COMMENT.equals(t.getChangeType()))
.toList();
break;
default:
throw new IllegalStateException("Unsupported Load value:" + load);
}
Map<String, List<FieldDiffs>> changesByRuleKey = indexAndSort(changes, IssueChangeDto::toFieldDiffs, Comparator.comparing(FieldDiffs::creationDate));
Map<String, List<IssueChangeDto>> commentsByIssueKey = indexAndSort(comments, t -> t, Comparator.comparing(IssueChangeDto::getIssueChangeCreationDate));
Map<String, UserDto> usersByUuid = loadUsers(dbSession, changesByRuleKey, commentsByIssueKey, preloadedUsers);
Map<String, ComponentDto> filesByUuid = loadFiles(dbSession, changesByRuleKey, preloadedComponents);
Map<String, Boolean> updatableCommentByKey = loadUpdatableFlag(commentsByIssueKey);
return new FormattingContextImpl(changesByRuleKey, commentsByIssueKey, usersByUuid, filesByUuid, updatableCommentByKey);
}
private static <T> Map<String, List<T>> indexAndSort(List<IssueChangeDto> changes, Function<IssueChangeDto, T> transform, Comparator<T> sortingComparator) {
Multimap<String, IssueChangeDto> unordered = changes.stream()
.collect(MoreCollectors.index(IssueChangeDto::getIssueKey, t -> t));
return unordered.asMap().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, t -> t.getValue().stream()
.map(transform)
.sorted(sortingComparator)
.toList()));
}
private Map<String, UserDto> loadUsers(DbSession dbSession, Map<String, List<FieldDiffs>> changesByRuleKey,
Map<String, List<IssueChangeDto>> commentsByIssueKey, Set<UserDto> preloadedUsers) {
Set<String> userUuids = Stream.concat(
changesByRuleKey.values().stream()
.flatMap(Collection::stream)
.map(FieldDiffs::userUuid)
.filter(Optional::isPresent)
.map(Optional::get),
commentsByIssueKey.values().stream()
.flatMap(Collection::stream)
.map(IssueChangeDto::getUserUuid)
)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (userUuids.isEmpty()) {
return emptyMap();
}
Set<String> preloadedUserUuids = preloadedUsers.stream().map(UserDto::getUuid).collect(Collectors.toSet());
Set<String> missingUsersUuids = Sets.difference(userUuids, preloadedUserUuids).immutableCopy();
if (missingUsersUuids.isEmpty()) {
return preloadedUsers.stream()
.filter(t -> userUuids.contains(t.getUuid()))
.collect(Collectors.toMap(UserDto::getUuid, Function.identity()));
}
return Stream.concat(
preloadedUsers.stream(),
dbClient.userDao().selectByUuids(dbSession, missingUsersUuids).stream())
.filter(t -> userUuids.contains(t.getUuid()))
.collect(Collectors.toMap(UserDto::getUuid, Function.identity()));
}
private Map<String, ComponentDto> loadFiles(DbSession dbSession, Map<String, List<FieldDiffs>> changesByRuleKey, Set<ComponentDto> preloadedComponents) {
Set<String> fileUuids = changesByRuleKey.values().stream()
.flatMap(Collection::stream)
.flatMap(diffs -> {
FieldDiffs.Diff diff = diffs.get(FILE);
if (diff == null) {
return Stream.empty();
}
return Stream.of(toString(diff.newValue()), toString(diff.oldValue()));
})
.map(Strings::emptyToNull)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (fileUuids.isEmpty()) {
return emptyMap();
}
Set<String> preloadedFileUuids = preloadedComponents.stream().map(ComponentDto::uuid).collect(Collectors.toSet());
Set<String> missingFileUuids = Sets.difference(fileUuids, preloadedFileUuids).immutableCopy();
if (missingFileUuids.isEmpty()) {
return preloadedComponents.stream()
.filter(t -> fileUuids.contains(t.uuid()))
.collect(Collectors.toMap(ComponentDto::uuid, Function.identity()));
}
return Stream.concat(
preloadedComponents.stream(),
dbClient.componentDao().selectByUuids(dbSession, missingFileUuids).stream())
.filter(t -> fileUuids.contains(t.uuid()))
.collect(Collectors.toMap(ComponentDto::uuid, Function.identity()));
}
private Map<String, Boolean> loadUpdatableFlag(Map<String, List<IssueChangeDto>> commentsByIssueKey) {
if (!userSession.isLoggedIn()) {
return emptyMap();
}
String userUuid = userSession.getUuid();
if (userUuid == null) {
return emptyMap();
}
return commentsByIssueKey.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toMap(IssueChangeDto::getKey, t -> userUuid.equals(t.getUserUuid())));
}
public Stream<Common.Changelog> formatChangelog(IssueDto dto, FormattingContext formattingContext) {
return formattingContext.getChanges(dto).stream()
.map(toWsChangelog(formattingContext));
}
private Function<FieldDiffs, Common.Changelog> toWsChangelog(FormattingContext formattingContext) {
return change -> {
Common.Changelog.Builder changelogBuilder = Common.Changelog.newBuilder();
changelogBuilder.setCreationDate(formatDateTime(change.creationDate()));
change.userUuid().flatMap(formattingContext::getUserByUuid)
.ifPresent(user -> {
changelogBuilder.setUser(user.getLogin());
changelogBuilder.setIsUserActive(user.isActive());
ofNullable(user.getName()).ifPresent(changelogBuilder::setUserName);
ofNullable(emptyToNull(user.getEmail())).ifPresent(email -> changelogBuilder.setAvatar(avatarFactory.create(user)));
});
change.externalUser().ifPresent(changelogBuilder::setExternalUser);
change.webhookSource().ifPresent(changelogBuilder::setWebhookSource);
change.diffs().entrySet().stream()
.map(toWsDiff(formattingContext))
.forEach(changelogBuilder::addDiffs);
return changelogBuilder.build();
};
}
private static Function<Map.Entry<String, FieldDiffs.Diff>, Common.Changelog.Diff> toWsDiff(FormattingContext formattingContext) {
return diff -> {
FieldDiffs.Diff value = diff.getValue();
Common.Changelog.Diff.Builder diffBuilder = Common.Changelog.Diff.newBuilder();
String key = diff.getKey();
String oldValue = emptyToNull(toString(value.oldValue()));
String newValue = emptyToNull(toString(value.newValue()));
if (key.equals(FILE)) {
diffBuilder.setKey(key);
formattingContext.getFileByUuid(newValue).map(ComponentDto::longName).ifPresent(diffBuilder::setNewValue);
formattingContext.getFileByUuid(oldValue).map(ComponentDto::longName).ifPresent(diffBuilder::setOldValue);
} else {
diffBuilder.setKey(key.equals(TECHNICAL_DEBT) ? EFFORT_CHANGELOG_KEY : key);
ofNullable(newValue).ifPresent(diffBuilder::setNewValue);
ofNullable(oldValue).ifPresent(diffBuilder::setOldValue);
}
return diffBuilder.build();
};
}
public Stream<Common.Comment> formatComments(IssueDto dto, Common.Comment.Builder commentBuilder, FormattingContext formattingContext) {
return formattingContext.getComments(dto).stream()
.map(comment -> {
commentBuilder
.clear()
.setKey(comment.getKey())
.setUpdatable(formattingContext.isUpdatableComment(comment))
.setCreatedAt(DateUtils.formatDateTime(new Date(comment.getIssueChangeCreationDate())));
String markdown = comment.getChangeData();
formattingContext.getUserByUuid(comment.getUserUuid()).ifPresent(user -> commentBuilder.setLogin(user.getLogin()));
if (markdown != null) {
commentBuilder
.setHtmlText(Markdown.convertToHtml(markdown))
.setMarkdown(markdown);
}
return commentBuilder.build();
});
}
private static String toString(@Nullable Serializable serializable) {
if (serializable != null) {
return serializable.toString();
}
return null;
}
@Immutable
public static final class FormattingContextImpl implements FormattingContext {
private final Map<String, List<FieldDiffs>> changesByIssueKey;
private final Map<String, List<IssueChangeDto>> commentsByIssueKey;
private final Map<String, UserDto> usersByUuid;
private final Map<String, ComponentDto> filesByUuid;
private final Map<String, Boolean> updatableCommentByKey;
private FormattingContextImpl(Map<String, List<FieldDiffs>> changesByIssueKey,
Map<String, List<IssueChangeDto>> commentsByIssueKey,
Map<String, UserDto> usersByUuid, Map<String, ComponentDto> filesByUuid,
Map<String, Boolean> updatableCommentByKey) {
this.changesByIssueKey = changesByIssueKey;
this.commentsByIssueKey = commentsByIssueKey;
this.usersByUuid = usersByUuid;
this.filesByUuid = filesByUuid;
this.updatableCommentByKey = updatableCommentByKey;
}
@Override
public List<FieldDiffs> getChanges(IssueDto dto) {
List<FieldDiffs> fieldDiffs = changesByIssueKey.get(dto.getKey());
if (fieldDiffs == null) {
return List.of();
}
return List.copyOf(fieldDiffs);
}
@Override
public List<IssueChangeDto> getComments(IssueDto dto) {
List<IssueChangeDto> comments = commentsByIssueKey.get(dto.getKey());
if (comments == null) {
return List.of();
}
return List.copyOf(comments);
}
@Override
public Set<UserDto> getUsers() {
return ImmutableSet.copyOf(usersByUuid.values());
}
@Override
public Optional<UserDto> getUserByUuid(@Nullable String uuid) {
if (uuid == null) {
return empty();
}
return Optional.ofNullable(usersByUuid.get(uuid));
}
@Override
public Optional<ComponentDto> getFileByUuid(@Nullable String uuid) {
if (uuid == null) {
return empty();
}
return Optional.ofNullable(filesByUuid.get(uuid));
}
@Override
public boolean isUpdatableComment(IssueChangeDto comment) {
Boolean flag = updatableCommentByKey.get(comment.getKey());
return flag != null && flag;
}
}
}
| 14,535 | 39.603352 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/IssueFinder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import org.sonar.api.rules.RuleType;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
public class IssueFinder {
private final DbClient dbClient;
private final UserSession userSession;
public IssueFinder(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
public IssueDto getByKey(DbSession session, String issueKey) {
IssueDto issue = dbClient.issueDao().selectByKey(session, issueKey).orElseThrow(() -> new NotFoundException(format("Issue with key '%s' does not exist", issueKey)));
RuleType ruleType = RuleType.valueOfNullable(issue.getType());
if (SECURITY_HOTSPOT.equals(ruleType)) {
throw new NotFoundException(format("Issue with key '%s' does not exist", issueKey));
}
userSession.checkComponentUuidPermission(UserRole.USER, requireNonNull(issue.getProjectUuid()));
return issue;
}
}
| 2,106 | 35.964912 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/IssuesFinderSort.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.annotation.Nonnull;
import org.sonar.api.rule.Severity;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.index.IssueQuery;
/**
* @since 3.6
*/
class IssuesFinderSort {
private List<IssueDto> issues;
private IssueQuery query;
public IssuesFinderSort(List<IssueDto> issues, IssueQuery query) {
this.issues = issues;
this.query = query;
}
public List<IssueDto> sort() {
String sort = query.sort();
Boolean asc = query.asc();
if (sort != null && asc != null) {
return getIssueProcessor(sort).sort(issues, asc);
}
return issues;
}
private static IssueProcessor getIssueProcessor(String sort) {
if (IssueQuery.SORT_BY_SEVERITY.equals(sort)) {
return new SeveritySortIssueProcessor();
}
if (IssueQuery.SORT_BY_STATUS.equals(sort)) {
return new StatusSortIssueProcessor();
}
if (IssueQuery.SORT_BY_CREATION_DATE.equals(sort)) {
return new CreationDateSortIssueProcessor();
}
if (IssueQuery.SORT_BY_UPDATE_DATE.equals(sort)) {
return new UpdateDateSortIssueProcessor();
}
if (IssueQuery.SORT_BY_CLOSE_DATE.equals(sort)) {
return new CloseDateSortIssueProcessor();
}
throw new IllegalArgumentException("Cannot sort on field : " + sort);
}
interface IssueProcessor {
Function sortFieldFunction();
Ordering sortFieldOrdering(boolean ascending);
default List<IssueDto> sort(Collection<IssueDto> issueDtos, boolean ascending) {
Ordering<IssueDto> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
return ordering.immutableSortedCopy(issueDtos);
}
}
abstract static class TextSortIssueProcessor implements IssueProcessor {
@Override
public Function sortFieldFunction() {
return (Function<IssueDto, String>) this::sortField;
}
abstract String sortField(IssueDto issueDto);
@Override
public Ordering sortFieldOrdering(boolean ascending) {
Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast();
if (!ascending) {
ordering = ordering.reverse();
}
return ordering;
}
}
static class StatusSortIssueProcessor extends TextSortIssueProcessor {
@Override
String sortField(IssueDto issueDto) {
return issueDto.getStatus();
}
}
static class SeveritySortIssueProcessor implements IssueProcessor {
@Override
public Function sortFieldFunction() {
return IssueDtoToSeverity.INSTANCE;
}
@Override
public Ordering sortFieldOrdering(boolean ascending) {
Ordering<Integer> ordering = Ordering.<Integer>natural().nullsLast();
if (!ascending) {
ordering = ordering.reverse();
}
return ordering;
}
}
abstract static class DateSortRowProcessor implements IssueProcessor {
@Override
public Function sortFieldFunction() {
return (Function<IssueDto, Date>) this::sortField;
}
abstract Date sortField(IssueDto issueDto);
@Override
public Ordering sortFieldOrdering(boolean ascending) {
Ordering<Date> ordering = Ordering.<Date>natural().nullsLast();
if (!ascending) {
ordering = ordering.reverse();
}
return ordering;
}
}
static class CreationDateSortIssueProcessor extends DateSortRowProcessor {
@Override
Date sortField(IssueDto issueDto) {
return issueDto.getIssueCreationDate();
}
}
static class UpdateDateSortIssueProcessor extends DateSortRowProcessor {
@Override
Date sortField(IssueDto issueDto) {
return issueDto.getIssueUpdateDate();
}
}
static class CloseDateSortIssueProcessor extends DateSortRowProcessor {
@Override
Date sortField(IssueDto issueDto) {
return issueDto.getIssueCloseDate();
}
}
private enum IssueDtoToSeverity implements Function<IssueDto, Integer> {
INSTANCE;
@Override
public Integer apply(@Nonnull IssueDto issueDto) {
return Severity.ALL.indexOf(issueDto.getSeverity());
}
}
}
| 5,085 | 28.398844 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/RemoveTagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.sonar.api.server.ServerSide;
@ServerSide
public class RemoveTagsAction extends AbstractChangeTagsAction {
public static final String KEY = "remove_tags";
public RemoveTagsAction(IssueFieldsSetter issueUpdater) {
super(KEY, issueUpdater);
}
@Override
protected Collection<String> getTagsToSet(Context context, Collection<String> tagsFromParams) {
Set<String> newTags = new HashSet<>(context.issue().tags());
newTags.removeAll(tagsFromParams);
return newTags;
}
}
| 1,458 | 32.930233 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/Result.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Arrays;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import static com.google.common.collect.Lists.newArrayList;
/**
* @since 3.6
*/
public class Result<T> {
private T object;
private final List<Message> errors = newArrayList();
private Result(@Nullable T object) {
this.object = object;
}
public static <T> Result<T> of() {
return new Result<>(null);
}
public Result<T> set(@Nullable T object) {
this.object = object;
return this;
}
public T get() {
return object;
}
public Result<T> addError(String text) {
return addError(Message.of(text));
}
public Result<T> addError(Message message) {
errors.add(message);
return this;
}
/**
* List of error messages. Empty if there are no errors.
*/
public List<Message> errors() {
return errors;
}
/**
* True if there are no errors.
*/
public boolean ok() {
return errors.isEmpty();
}
public int httpStatus() {
if (ok()) {
return 200;
}
// TODO support 401, 403 and 500
return 400;
}
public static class Message {
private final String l10nKey;
private final Object[] l10nParams;
private final String text;
private Message(@Nullable String l10nKey, @Nullable Object[] l10nParams, @Nullable String text) {
this.l10nKey = l10nKey;
this.l10nParams = l10nParams;
this.text = text;
}
public static Message of(String text) {
return new Message(null, null, text);
}
public static Message ofL10n(String l10nKey, Object... l10nParams) {
return new Message(l10nKey, l10nParams, null);
}
@CheckForNull
public String text() {
return text;
}
@CheckForNull
public String l10nKey() {
return l10nKey;
}
@CheckForNull
public Object[] l10nParams() {
return l10nParams;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Message message = (Message) o;
if ((l10nKey != null) ? !l10nKey.equals(message.l10nKey) : (message.l10nKey != null)) {
return false;
}
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(l10nParams, message.l10nParams) && ((text != null) ? text.equals(message.text) : (message.text == null));
}
@Override
public int hashCode() {
int result = l10nKey != null ? l10nKey.hashCode() : 0;
result = 31 * result + (l10nParams != null ? Arrays.hashCode(l10nParams) : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new ReflectionToStringBuilder(this).toString();
}
}
}
| 3,829 | 24.364238 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/SetSeverityAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.issue.Issue;
import org.sonar.server.issue.workflow.IsUnResolved;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
@ServerSide
public class SetSeverityAction extends Action {
public static final String SET_SEVERITY_KEY = "set_severity";
public static final String SEVERITY_PARAMETER = "severity";
private final IssueFieldsSetter issueUpdater;
private final UserSession userSession;
public SetSeverityAction(IssueFieldsSetter issueUpdater, UserSession userSession) {
super(SET_SEVERITY_KEY);
this.issueUpdater = issueUpdater;
this.userSession = userSession;
super.setConditions(new IsUnResolved(), this::isCurrentUserIssueAdminAndNotSecurityHotspot);
}
private boolean isCurrentUserIssueAdminAndNotSecurityHotspot(Issue issue) {
DefaultIssue defaultIssue = (DefaultIssue) issue;
return (defaultIssue.type() != RuleType.SECURITY_HOTSPOT && userSession.hasComponentUuidPermission(ISSUE_ADMIN, issue.projectUuid()));
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
verifySeverityParameter(properties);
return true;
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
return issueUpdater.setManualSeverity(context.issue(), verifySeverityParameter(properties), context.issueChangeContext());
}
@Override
public boolean shouldRefreshMeasures() {
return true;
}
private static String verifySeverityParameter(Map<String, Object> properties) {
String param = (String) properties.get(SEVERITY_PARAMETER);
checkArgument(!isNullOrEmpty(param), "Missing parameter : '%s'", SEVERITY_PARAMETER);
return param;
}
}
| 2,950 | 36.833333 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/SetTypeAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.issue.Issue;
import org.sonar.api.rules.RuleType;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.workflow.IsUnResolved;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
public class SetTypeAction extends Action {
public static final String SET_TYPE_KEY = "set_type";
public static final String TYPE_PARAMETER = "type";
private final IssueFieldsSetter issueUpdater;
private final UserSession userSession;
public SetTypeAction(IssueFieldsSetter issueUpdater, UserSession userSession) {
super(SET_TYPE_KEY);
this.issueUpdater = issueUpdater;
this.userSession = userSession;
super.setConditions(new IsUnResolved(), this::isCurrentUserIssueAdmin);
}
private boolean isCurrentUserIssueAdmin(Issue issue) {
return userSession.hasComponentUuidPermission(UserRole.ISSUE_ADMIN, issue.projectUuid());
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
verifyTypeParameter(properties);
return true;
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
String type = verifyTypeParameter(properties);
return issueUpdater.setType(context.issue(), RuleType.valueOf(type), context.issueChangeContext());
}
@Override
public boolean shouldRefreshMeasures() {
return true;
}
private static String verifyTypeParameter(Map<String, Object> properties) {
String type = (String) properties.get(TYPE_PARAMETER);
checkArgument(!isNullOrEmpty(type), "Missing parameter : '%s'", TYPE_PARAMETER);
checkArgument(RuleType.names().contains(type), "Unknown type : %s", type);
return type;
}
}
| 2,798 | 35.350649 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/TextRangeResponseFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.server.ws.MessageFormattingUtils;
import org.sonarqube.ws.Common;
import static java.util.Optional.ofNullable;
public class TextRangeResponseFormatter {
public void formatTextRange(IssueDto dto, Consumer<Common.TextRange> rangeConsumer) {
DbIssues.Locations locations = dto.parseLocations();
if (locations == null) {
return;
}
formatTextRange(locations, rangeConsumer);
}
public void formatTextRange(DbIssues.Locations locations, Consumer<Common.TextRange> rangeConsumer) {
if (locations.hasTextRange()) {
DbCommons.TextRange textRange = locations.getTextRange();
rangeConsumer.accept(convertTextRange(textRange).build());
}
}
public List<Common.Flow> formatFlows(DbIssues.Locations locations, String issueComponent, Map<String, ComponentDto> componentsByUuid) {
return locations.getFlowList().stream().map(flow -> {
Common.Flow.Builder targetFlow = Common.Flow.newBuilder();
for (DbIssues.Location flowLocation : flow.getLocationList()) {
targetFlow.addLocations(formatLocation(flowLocation, issueComponent, componentsByUuid));
}
if (flow.hasDescription()) {
targetFlow.setDescription(flow.getDescription());
}
if (flow.hasType()) {
convertFlowType(flow.getType()).ifPresent(targetFlow::setType);
}
return targetFlow.build();
}).toList();
}
private static Optional<Common.FlowType> convertFlowType(DbIssues.FlowType flowType) {
switch (flowType) {
case DATA:
return Optional.of(Common.FlowType.DATA);
case EXECUTION:
return Optional.of(Common.FlowType.EXECUTION);
case UNDEFINED:
// we should only get this value if no type was set (since it's the default value of the enum), in which case this method shouldn't be called.
default:
throw new IllegalArgumentException("Unrecognized flow type: " + flowType);
}
}
public Common.Location formatLocation(DbIssues.Location source, String issueComponent, Map<String, ComponentDto> componentsByUuid) {
Common.Location.Builder target = Common.Location.newBuilder();
if (source.hasMsg()) {
target.setMsg(source.getMsg());
target.addAllMsgFormattings(MessageFormattingUtils.dbMessageFormattingListToWs(source.getMsgFormattingList()));
}
if (source.hasTextRange()) {
DbCommons.TextRange sourceRange = source.getTextRange();
Common.TextRange.Builder targetRange = convertTextRange(sourceRange);
target.setTextRange(targetRange);
}
if (source.hasComponentId()) {
ofNullable(componentsByUuid.get(source.getComponentId())).ifPresent(c -> target.setComponent(c.getKey()));
} else {
target.setComponent(issueComponent);
}
return target.build();
}
private static Common.TextRange.Builder convertTextRange(DbCommons.TextRange sourceRange) {
Common.TextRange.Builder targetRange = Common.TextRange.newBuilder();
if (sourceRange.hasStartLine()) {
targetRange.setStartLine(sourceRange.getStartLine());
}
if (sourceRange.hasStartOffset()) {
targetRange.setStartOffset(sourceRange.getStartOffset());
}
if (sourceRange.hasEndLine()) {
targetRange.setEndLine(sourceRange.getEndLine());
}
if (sourceRange.hasEndOffset()) {
targetRange.setEndOffset(sourceRange.getEndOffset());
}
return targetRange;
}
}
| 4,546 | 37.863248 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/TransitionAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
@ServerSide
public class TransitionAction extends Action {
public static final String DO_TRANSITION_KEY = "do_transition";
public static final String TRANSITION_PARAMETER = "transition";
private final TransitionService transitionService;
public TransitionAction(TransitionService transitionService) {
super(DO_TRANSITION_KEY);
this.transitionService = transitionService;
}
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
transition(properties);
return true;
}
@Override
public boolean execute(Map<String, Object> properties, Context context) {
DefaultIssue issue = context.issue();
String transition = transition(properties);
return canExecuteTransition(issue, transition) && transitionService.doTransition(context.issue(), context.issueChangeContext(), transition(properties));
}
@Override
public boolean shouldRefreshMeasures() {
return true;
}
private boolean canExecuteTransition(DefaultIssue issue, String transitionKey) {
return transitionService.listTransitions(issue)
.stream()
.map(Transition::key)
.collect(Collectors.toSet())
.contains(transitionKey);
}
private static String transition(Map<String, Object> properties) {
String param = (String) properties.get(TRANSITION_PARAMETER);
checkArgument(!isNullOrEmpty(param), "Missing parameter : 'transition'");
return param;
}
}
| 2,745 | 33.759494 | 156 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/TransitionService.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Collections;
import java.util.List;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
/**
* This service is a kind of overlay of {@link IssueWorkflow} that also deals with permission checking
*/
public class TransitionService {
private final UserSession userSession;
private final IssueWorkflow workflow;
public TransitionService(UserSession userSession, IssueWorkflow workflow) {
this.userSession = userSession;
this.workflow = workflow;
}
public List<Transition> listTransitions(DefaultIssue issue) {
if (issue.isFromExternalRuleEngine()){
return Collections.emptyList();
}
String projectUuid = requireNonNull(issue.projectUuid());
return workflow.outTransitions(issue)
.stream()
.filter(transition -> (userSession.isLoggedIn() && isBlank(transition.requiredProjectPermission()))
|| userSession.hasComponentUuidPermission(transition.requiredProjectPermission(), projectUuid))
.toList();
}
public boolean doTransition(DefaultIssue defaultIssue, IssueChangeContext issueChangeContext, String transitionKey) {
checkArgument(!defaultIssue.isFromExternalRuleEngine(), "Transition is not allowed on issues imported from external rule engines");
return workflow.doManualTransition(defaultIssue, transitionKey, issueChangeContext);
}
public void checkTransitionPermission(String transitionKey, DefaultIssue defaultIssue) {
String projectUuid = requireNonNull(defaultIssue.projectUuid());
workflow.outTransitions(defaultIssue)
.stream()
.filter(transition -> transition.key().equals(transitionKey) && isNotBlank(transition.requiredProjectPermission()))
.forEach(transition -> userSession.checkComponentUuidPermission(transition.requiredProjectPermission(), projectUuid));
}
}
| 3,104 | 40.959459 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/WebIssueStorage.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.sonar.api.issue.Issue;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.BatchSession;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeMapper;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.index.IssueIndexer;
import org.sonar.server.rule.ServerRuleFinder;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.emptyList;
/**
* Save issues into database. It is executed :
* <ul>
* <li>once at the end of scan, even on multi-module projects</li>
* <li>on each server-side action initiated by UI or web service</li>
* </ul>
*/
@ServerSide
public class WebIssueStorage extends IssueStorage {
private final System2 system2;
private final ServerRuleFinder ruleFinder;
private final DbClient dbClient;
private final IssueIndexer indexer;
private final UuidFactory uuidFactory;
public WebIssueStorage(System2 system2, DbClient dbClient, ServerRuleFinder ruleFinder, IssueIndexer indexer, UuidFactory uuidFactory) {
this.system2 = system2;
this.dbClient = dbClient;
this.ruleFinder = ruleFinder;
this.indexer = indexer;
this.uuidFactory = uuidFactory;
}
protected DbClient getDbClient() {
return dbClient;
}
public Collection<IssueDto> save(DbSession dbSession, Iterable<DefaultIssue> issues) {
// Batch session can not be used for updates. It does not return the number of updated rows,
// required for detecting conflicts.
long now = system2.now();
Map<Boolean, List<DefaultIssue>> issuesNewOrUpdated = StreamSupport.stream(issues.spliterator(), true).collect(Collectors.groupingBy(DefaultIssue::isNew));
List<DefaultIssue> issuesToInsert = firstNonNull(issuesNewOrUpdated.get(true), emptyList());
List<DefaultIssue> issuesToUpdate = firstNonNull(issuesNewOrUpdated.get(false), emptyList());
Collection<IssueDto> inserted = insert(dbSession, issuesToInsert, now);
Collection<IssueDto> updated = update(issuesToUpdate, now);
doAfterSave(dbSession, Stream.concat(inserted.stream(), updated.stream())
.collect(Collectors.toSet()));
return Stream.concat(inserted.stream(), updated.stream())
.collect(Collectors.toSet());
}
private void doAfterSave(DbSession dbSession, Collection<IssueDto> issues) {
indexer.commitAndIndexIssues(dbSession, issues);
}
/**
* @return the keys of the inserted issues
*/
private Collection<IssueDto> insert(DbSession session, Iterable<DefaultIssue> issuesToInsert, long now) {
List<IssueDto> inserted = newArrayList();
int count = 0;
IssueChangeMapper issueChangeMapper = session.getMapper(IssueChangeMapper.class);
for (DefaultIssue issue : issuesToInsert) {
IssueDto issueDto = doInsert(session, now, issue);
inserted.add(issueDto);
insertChanges(issueChangeMapper, issue, uuidFactory);
if (count > BatchSession.MAX_BATCH_SIZE) {
session.commit();
count = 0;
}
count++;
}
session.commit();
return inserted;
}
private IssueDto doInsert(DbSession session, long now, DefaultIssue issue) {
ComponentDto component = component(session, issue);
ComponentDto project = project(session, issue);
String ruleUuid = getRuleUuid(issue).orElseThrow(() -> new IllegalStateException("Rule not found: " + issue.ruleKey()));
IssueDto dto = IssueDto.toDtoForServerInsert(issue, component, project, ruleUuid, now);
getDbClient().issueDao().insert(session, dto);
return dto;
}
ComponentDto component(DbSession session, DefaultIssue issue) {
return getDbClient().componentDao().selectOrFailByUuid(session, issue.componentUuid());
}
ComponentDto project(DbSession session, DefaultIssue issue) {
return getDbClient().componentDao().selectOrFailByUuid(session, issue.projectUuid());
}
/**
* @return the keys of the updated issues
*/
private Collection<IssueDto> update(List<DefaultIssue> issuesToUpdate, long now) {
Collection<IssueDto> updated = new ArrayList<>();
if (!issuesToUpdate.isEmpty()) {
try (DbSession dbSession = dbClient.openSession(false)) {
IssueChangeMapper issueChangeMapper = dbSession.getMapper(IssueChangeMapper.class);
for (DefaultIssue issue : issuesToUpdate) {
IssueDto issueDto = doUpdate(dbSession, now, issue);
updated.add(issueDto);
insertChanges(issueChangeMapper, issue, uuidFactory);
}
dbSession.commit();
}
}
return updated;
}
private IssueDto doUpdate(DbSession session, long now, DefaultIssue issue) {
IssueDto dto = IssueDto.toDtoForUpdate(issue, now);
getDbClient().issueDao().update(session, dto);
// Rule id does not exist in DefaultIssue
getRuleUuid(issue).ifPresent(dto::setRuleUuid);
return dto;
}
protected Optional<String> getRuleUuid(Issue issue) {
return ruleFinder.findDtoByKey(issue.ruleKey()).map(RuleDto::getUuid);
}
}
| 6,368 | 36.464706 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.issue;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 39.125 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AddCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Date;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.issue.IssuesWsParameters;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.requireNonNull;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TEXT;
public class AddCommentAction implements IssuesWsAction {
private final System2 system2;
private final UserSession userSession;
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final IssueUpdater issueUpdater;
private final IssueFieldsSetter issueFieldsSetter;
private final OperationResponseWriter responseWriter;
public AddCommentAction(System2 system2, UserSession userSession, DbClient dbClient, IssueFinder issueFinder, IssueUpdater issueUpdater, IssueFieldsSetter issueFieldsSetter,
OperationResponseWriter responseWriter) {
this.system2 = system2;
this.userSession = userSession;
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.issueUpdater = issueUpdater;
this.issueFieldsSetter = issueFieldsSetter;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(IssuesWsParameters.ACTION_ADD_COMMENT)
.setDescription("Add a comment.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified issue.")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.3", "the response returns the issue with all its details"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "add_comment-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_TEXT)
.setDescription("Comment text")
.setRequired(true)
.setExampleValue("Won't fix because it doesn't apply to the context");
}
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
AddCommentRequest wsRequest = toWsRequest(request);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issueDto = issueFinder.getByKey(dbSession, wsRequest.getIssue());
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(system2.now()), userSession.getUuid()).build();
DefaultIssue defaultIssue = issueDto.toDefaultIssue();
issueFieldsSetter.addComment(defaultIssue, wsRequest.getText(), context);
SearchResponseData preloadedSearchResponseData = issueUpdater.saveIssueAndPreloadSearchResponseData(dbSession, defaultIssue, context);
responseWriter.write(defaultIssue.key(), preloadedSearchResponseData, request, response);
}
}
private static AddCommentRequest toWsRequest(Request request) {
AddCommentRequest wsRequest = new AddCommentRequest(request.mandatoryParam(PARAM_ISSUE), request.mandatoryParam(PARAM_TEXT));
checkArgument(!isNullOrEmpty(wsRequest.getText()), "Cannot add empty comment to an issue");
return wsRequest;
}
private static class AddCommentRequest {
private final String issue;
private final String text;
private AddCommentRequest(String issue, String text) {
this.issue = requireNonNull(issue, "Issue key cannot be null");
this.text = requireNonNull(text, "Text cannot be null");
}
public String getIssue() {
return issue;
}
public String getText() {
return text;
}
}
}
| 5,661 | 41.571429 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AssignAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.base.Strings;
import com.google.common.io.Resources;
import java.util.Date;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Strings.emptyToNull;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_ASSIGN;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNEE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
public class AssignAction implements IssuesWsAction {
private static final String ASSIGN_TO_ME_VALUE = "_me";
private final System2 system2;
private final UserSession userSession;
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final OperationResponseWriter responseWriter;
public AssignAction(System2 system2, UserSession userSession, DbClient dbClient, IssueFinder issueFinder, IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater,
OperationResponseWriter responseWriter) {
this.system2 = system2;
this.userSession = userSession;
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_ASSIGN)
.setDescription("Assign/Unassign an issue. Requires authentication and Browse permission on project")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "assign-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_ASSIGNEE)
.setDescription("Login of the assignee. When not set, it will unassign the issue. Use '%s' to assign to current user", ASSIGN_TO_ME_VALUE)
.setExampleValue("admin");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
String assignee = getAssignee(request);
String key = request.mandatoryParam(PARAM_ISSUE);
SearchResponseData preloadedResponseData = assign(key, assignee);
responseWriter.write(key, preloadedResponseData, request, response);
}
private SearchResponseData assign(String issueKey, @Nullable String login) {
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issueDto = issueFinder.getByKey(dbSession, issueKey);
DefaultIssue issue = issueDto.toDefaultIssue();
UserDto user = getUser(dbSession, login);
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(system2.now()), userSession.getUuid()).build();
if (issueFieldsSetter.assign(issue, user, context)) {
return issueUpdater.saveIssueAndPreloadSearchResponseData(dbSession, issue, context);
}
return new SearchResponseData(issueDto);
}
}
@CheckForNull
private String getAssignee(Request request) {
String assignee = emptyToNull(request.param(PARAM_ASSIGNEE));
return ASSIGN_TO_ME_VALUE.equals(assignee) ? userSession.getLogin() : assignee;
}
@CheckForNull
private UserDto getUser(DbSession dbSession, @Nullable String assignee) {
if (Strings.isNullOrEmpty(assignee)) {
return null;
}
return checkFound(dbClient.userDao().selectActiveUserByLogin(dbSession, assignee), "Unknown user: %s", assignee);
}
}
| 5,672 | 41.977273 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AuthorsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.issue.index.IssueQuery;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Issues.AuthorsResponse;
import static java.util.Optional.ofNullable;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class AuthorsAction implements IssuesWsAction {
private static final EnumSet<RuleType> ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS = EnumSet.complementOf(EnumSet.of(RuleType.SECURITY_HOTSPOT));
private static final String PARAM_PROJECT = "project";
private final UserSession userSession;
private final DbClient dbClient;
private final IssueIndex issueIndex;
private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
public AuthorsAction(UserSession userSession, DbClient dbClient, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueIndex = issueIndex;
this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction("authors")
.setSince("5.1")
.setDescription("Search SCM accounts which match a given query.<br/>" +
"Requires authentication."
+ "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
.setResponseExample(Resources.getResource(this.getClass(), "authors-example.json"))
.setChangelog(new Change("7.4", "The maximum size of 'ps' is set to 100"))
.setHandler(this);
action.createSearchQuery("luke", "authors");
action.createPageSize(10, 100);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(false)
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setSince("7.4");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
checkIfComponentNeedIssueSync(dbSession, request.param(PARAM_PROJECT));
Optional<EntityDto> entity = getEntity(dbSession, request.param(PARAM_PROJECT));
List<String> authors = getAuthors(dbSession, entity.orElse(null), request);
AuthorsResponse wsResponse = AuthorsResponse.newBuilder().addAllAuthors(authors).build();
writeProtobuf(wsResponse, request, response);
}
}
private void checkIfComponentNeedIssueSync(DbSession dbSession, @Nullable String projectKey) {
if (projectKey != null) {
issueIndexSyncProgressChecker.checkIfComponentNeedIssueSync(dbSession, projectKey);
} else {
issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(dbSession);
}
}
private Optional<EntityDto> getEntity(DbSession dbSession, @Nullable String projectKey) {
if (projectKey == null) {
return Optional.empty();
}
return Optional.of(dbClient.entityDao().selectByKey(dbSession, projectKey)
.filter(e -> !e.getQualifier().equals(Qualifiers.SUBVIEW))
.orElseThrow(() -> new NotFoundException("Entity not found: " + projectKey)));
}
private List<String> getAuthors(DbSession session, @Nullable EntityDto entity, Request request) {
IssueQuery.Builder issueQueryBuilder = IssueQuery.builder();
ofNullable(entity).ifPresent(p -> {
switch (p.getQualifier()) {
case Qualifiers.PROJECT -> issueQueryBuilder.projectUuids(Set.of(p.getUuid()));
case Qualifiers.VIEW -> issueQueryBuilder.viewUuids(Set.of(p.getUuid()));
case Qualifiers.APP -> {
BranchDto appMainBranch = dbClient.branchDao().selectMainBranchByProjectUuid(session, entity.getUuid())
.orElseThrow(() -> new IllegalStateException("Couldn't find main branch for APP " + entity.getUuid()));
issueQueryBuilder.viewUuids(Set.of(appMainBranch.getUuid()));
}
default -> throw new IllegalArgumentException(String.format("Component of type '%s' is not supported", p.getQualifier()));
}
});
return issueIndex.searchAuthors(
issueQueryBuilder
.types(ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS.stream().map(Enum::name).toList())
.build(),
request.param(TEXT_QUERY),
request.mandatoryParamAsInt(PAGE_SIZE));
}
}
| 6,190 | 42.598592 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/BasePullAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueQueryParams;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.ws.pull.ProtobufObjectGenerator;
import org.sonar.server.issue.ws.pull.PullActionIssuesRetriever;
import org.sonar.server.issue.ws.pull.PullActionResponseWriter;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.WsAction;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static org.sonar.api.web.UserRole.USER;
public abstract class BasePullAction implements WsAction {
protected static final String PROJECT_KEY_PARAM = "projectKey";
protected static final String BRANCH_NAME_PARAM = "branchName";
protected static final String LANGUAGES_PARAM = "languages";
protected static final String RULE_REPOSITORIES_PARAM = "ruleRepositories";
protected static final String RESOLVED_ONLY_PARAM = "resolvedOnly";
protected static final String CHANGED_SINCE_PARAM = "changedSince";
protected final String actionName;
protected final String issueType;
protected final String repositoryExample;
protected final String sinceVersion;
protected final String resourceExample;
private final ComponentFinder componentFinder;
private final DbClient dbClient;
private final UserSession userSession;
private final PullActionResponseWriter pullActionResponseWriter;
protected BasePullAction(System2 system2, ComponentFinder componentFinder, DbClient dbClient, UserSession userSession,
ProtobufObjectGenerator protobufObjectGenerator, String actionName, String issueType,
String repositoryExample, String sinceVersion, String resourceExample) {
this.componentFinder = componentFinder;
this.dbClient = dbClient;
this.userSession = userSession;
this.pullActionResponseWriter = new PullActionResponseWriter(system2, protobufObjectGenerator);
this.actionName = actionName;
this.issueType = issueType;
this.repositoryExample = repositoryExample;
this.sinceVersion = sinceVersion;
this.resourceExample = resourceExample;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction(actionName)
.setHandler(this)
.setInternal(true)
.setResponseExample(getClass().getResource(resourceExample))
.setDescription(format("This endpoint fetches and returns all (unless filtered by optional params) the %s for a given branch. " +
"The %s returned are not paginated, so the response size can be big. Requires project 'Browse' permission.", issueType, issueType))
.setSince(sinceVersion);
action.createParam(PROJECT_KEY_PARAM)
.setRequired(true)
.setDescription(format("Project key for which %s are fetched.", issueType))
.setExampleValue("sonarqube");
action.createParam(BRANCH_NAME_PARAM)
.setRequired(true)
.setDescription(format("Branch name for which %s are fetched.", issueType))
.setExampleValue("develop");
action.createParam(LANGUAGES_PARAM)
.setDescription(format("Comma separated list of languages. If not present all %s regardless of their language are returned.", issueType))
.setExampleValue("java,cobol");
action.createParam(CHANGED_SINCE_PARAM)
.setDescription(format("Timestamp. If present only %s modified after given timestamp are returned (both open and closed). " +
"If not present all non-closed %s are returned.", issueType, issueType))
.setExampleValue(1_654_032_306_000L);
additionalParams(action);
}
protected void additionalParams(WebService.NewAction action) {
// define additional parameters if needed
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.mandatoryParam(PROJECT_KEY_PARAM);
String branchName = request.mandatoryParam(BRANCH_NAME_PARAM);
List<String> languages = request.paramAsStrings(LANGUAGES_PARAM);
String changedSince = request.param(CHANGED_SINCE_PARAM);
Long changedSinceTimestamp = changedSince != null ? Long.parseLong(changedSince) : null;
BasePullRequest wsRequest = new BasePullRequest(projectKey, branchName)
.languages(languages)
.changedSinceTimestamp(changedSinceTimestamp);
processAdditionalParams(request, wsRequest);
doHandle(wsRequest, response.stream().output());
}
protected void processAdditionalParams(Request request, BasePullRequest wsRequest) {
// process additional parameters if needed
}
private void doHandle(BasePullRequest wsRequest, OutputStream outputStream) throws IOException {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto projectDto = componentFinder.getProjectByKey(dbSession, wsRequest.projectKey);
userSession.checkEntityPermission(USER, projectDto);
BranchDto branchDto = componentFinder.getBranchOrPullRequest(dbSession, projectDto, wsRequest.branchName, null);
IssueQueryParams issueQueryParams = initializeQueryParams(branchDto, wsRequest.languages, wsRequest.repositories,
wsRequest.resolvedOnly, wsRequest.changedSinceTimestamp);
retrieveAndSendIssues(dbSession, issueQueryParams, outputStream);
}
}
protected abstract IssueQueryParams initializeQueryParams(BranchDto branchDto, @Nullable List<String> languages,
@Nullable List<String> ruleRepositories, boolean resolvedOnly, @Nullable Long changedSince);
private void retrieveAndSendIssues(DbSession dbSession, IssueQueryParams queryParams, OutputStream outputStream)
throws IOException {
pullActionResponseWriter.appendTimestampToResponse(outputStream);
var issuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams);
processNonClosedIssuesInBatches(dbSession, queryParams, outputStream, issuesRetriever);
if (queryParams.getChangedSince() != null) {
// in the "incremental mode" we need to send SonarLint also recently closed issues keys
List<String> closedIssues = issuesRetriever.retrieveClosedIssues(dbSession);
pullActionResponseWriter.appendClosedIssuesUuidsToResponse(closedIssues, outputStream);
}
}
private void processNonClosedIssuesInBatches(DbSession dbSession, IssueQueryParams queryParams, OutputStream outputStream,
PullActionIssuesRetriever issuesRetriever) {
int nextPage = 1;
Map<String, RuleDto> ruleCache = new HashMap<>();
do {
Set<String> issueKeysSnapshot = getIssueKeysSnapshot(queryParams, nextPage);
Consumer<List<IssueDto>> listConsumer = issueDtos -> {
populateRuleCache(dbSession, ruleCache, issueDtos);
pullActionResponseWriter.appendIssuesToResponse(issueDtos, ruleCache, outputStream);
};
Predicate<IssueDto> filter = issueDto -> filterNonClosedIssues(issueDto, queryParams);
issuesRetriever.processIssuesByBatch(dbSession, issueKeysSnapshot, listConsumer, filter);
if (issueKeysSnapshot.isEmpty()) {
nextPage = -1;
} else {
nextPage++;
}
} while (nextPage > 0);
}
private void populateRuleCache(DbSession dbSession, Map<String, RuleDto> ruleCache, List<IssueDto> issueDtos) {
Set<String> rulesToQueryFor = issueDtos.stream()
.map(IssueDto::getRuleUuid)
.filter(ruleUuid -> !ruleCache.containsKey(ruleUuid))
.collect(Collectors.toSet());
dbClient.ruleDao().selectByUuids(dbSession, rulesToQueryFor)
.forEach(ruleDto -> ruleCache.putIfAbsent(ruleDto.getUuid(), ruleDto));
}
protected abstract boolean filterNonClosedIssues(IssueDto issueDto, IssueQueryParams queryParams);
protected abstract Set<String> getIssueKeysSnapshot(IssueQueryParams queryParams, int page);
protected static class BasePullRequest {
private final String projectKey;
private final String branchName;
private List<String> languages = null;
private List<String> repositories = null;
private boolean resolvedOnly = false;
private Long changedSinceTimestamp = null;
public BasePullRequest(String projectKey, String branchName) {
this.projectKey = projectKey;
this.branchName = branchName;
}
public BasePullRequest languages(@Nullable List<String> languages) {
this.languages = languages;
return this;
}
public BasePullRequest repositories(@Nullable List<String> repositories) {
this.repositories = repositories == null ? emptyList() : repositories;
return this;
}
public BasePullRequest resolvedOnly(boolean resolvedOnly) {
this.resolvedOnly = resolvedOnly;
return this;
}
public BasePullRequest changedSinceTimestamp(@Nullable Long changedSinceTimestamp) {
this.changedSinceTimestamp = changedSinceTimestamp;
return this;
}
}
}
| 10,320 | 41.473251 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/BulkChangeAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.issue.DefaultTransitions;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.Action;
import org.sonar.server.issue.ActionContext;
import org.sonar.server.issue.AddTagsAction;
import org.sonar.server.issue.AssignAction;
import org.sonar.server.issue.IssueChangePostProcessor;
import org.sonar.server.issue.RemoveTagsAction;
import org.sonar.server.issue.WebIssueStorage;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationSerializer;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.pushapi.issues.IssueChangeEventService;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Issues;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Map.of;
import static java.util.Objects.requireNonNull;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.issue.DefaultTransitions.OPEN_AS_VULNERABILITY;
import static org.sonar.api.issue.DefaultTransitions.REOPEN;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_REVIEWED;
import static org.sonar.api.issue.DefaultTransitions.SET_AS_IN_REVIEW;
import static org.sonar.api.rule.Severity.BLOCKER;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
import static org.sonar.server.issue.AbstractChangeTagsAction.TAGS_PARAMETER;
import static org.sonar.server.issue.AssignAction.ASSIGNEE_PARAMETER;
import static org.sonar.server.issue.CommentAction.COMMENT_KEY;
import static org.sonar.server.issue.CommentAction.COMMENT_PROPERTY;
import static org.sonar.server.issue.SetSeverityAction.SET_SEVERITY_KEY;
import static org.sonar.server.issue.SetSeverityAction.SEVERITY_PARAMETER;
import static org.sonar.server.issue.SetTypeAction.SET_TYPE_KEY;
import static org.sonar.server.issue.SetTypeAction.TYPE_PARAMETER;
import static org.sonar.server.issue.TransitionAction.DO_TRANSITION_KEY;
import static org.sonar.server.issue.TransitionAction.TRANSITION_PARAMETER;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_BULK_CHANGE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ADD_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGN;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMMENT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_DO_TRANSITION;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_REMOVE_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SEND_NOTIFICATIONS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SET_SEVERITY;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SET_TYPE;
public class BulkChangeAction implements IssuesWsAction {
private static final Logger LOG = LoggerFactory.getLogger(BulkChangeAction.class);
private static final List<String> ACTIONS_TO_DISTRIBUTE = List.of(SET_SEVERITY_KEY, SET_TYPE_KEY, DO_TRANSITION_KEY);
private final System2 system2;
private final UserSession userSession;
private final DbClient dbClient;
private final WebIssueStorage issueStorage;
private final NotificationManager notificationService;
private final List<Action> actions;
private final IssueChangePostProcessor issueChangePostProcessor;
private final IssuesChangesNotificationSerializer notificationSerializer;
private final IssueChangeEventService issueChangeEventService;
public BulkChangeAction(System2 system2, UserSession userSession, DbClient dbClient, WebIssueStorage issueStorage,
NotificationManager notificationService, List<Action> actions,
IssueChangePostProcessor issueChangePostProcessor, IssuesChangesNotificationSerializer notificationSerializer,
IssueChangeEventService issueChangeEventService) {
this.system2 = system2;
this.userSession = userSession;
this.dbClient = dbClient;
this.issueStorage = issueStorage;
this.notificationService = notificationService;
this.actions = actions;
this.issueChangePostProcessor = issueChangePostProcessor;
this.notificationSerializer = notificationSerializer;
this.issueChangeEventService = issueChangeEventService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_BULK_CHANGE)
.setDescription("Bulk change on issues. Up to 500 issues can be updated. <br/>" +
"Requires authentication.")
.setSince("3.7")
.setChangelog(
new Change("8.2", "Security hotspots are no longer supported and will be ignored."),
new Change("8.2", format("transitions '%s', '%s' and '%s' are no more supported", SET_AS_IN_REVIEW, RESOLVE_AS_REVIEWED, OPEN_AS_VULNERABILITY)),
new Change("6.3", "'actions' parameter is ignored"))
.setHandler(this)
.setResponseExample(getClass().getResource("bulk_change-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUES)
.setDescription("Comma-separated list of issue keys")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01 + "," + UUID_EXAMPLE_02);
action.createParam(PARAM_ASSIGN)
.setDescription("To assign the list of issues to a specific user (login), or un-assign all the issues")
.setExampleValue("john.smith");
action.createParam(PARAM_SET_SEVERITY)
.setDescription("To change the severity of the list of issues")
.setExampleValue(BLOCKER)
.setPossibleValues(Severity.ALL);
action.createParam(PARAM_SET_TYPE)
.setDescription("To change the type of the list of issues")
.setExampleValue(BUG)
.setPossibleValues(RuleType.names())
.setSince("5.5");
action.createParam(PARAM_DO_TRANSITION)
.setDescription("Transition")
.setExampleValue(REOPEN)
.setPossibleValues(DefaultTransitions.ALL);
action.createParam(PARAM_ADD_TAGS)
.setDescription("Add tags")
.setExampleValue("security,java8");
action.createParam(PARAM_REMOVE_TAGS)
.setDescription("Remove tags")
.setExampleValue("security,java8");
action.createParam(PARAM_COMMENT)
.setDescription("Add a comment. "
+ "The comment will only be added to issues that are affected either by a change of type or a change of severity as a result of the same WS call.")
.setExampleValue("Here is my comment");
action.createParam(PARAM_SEND_NOTIFICATIONS)
.setSince("4.0")
.setBooleanPossibleValues()
.setDefaultValue("false");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
BulkChangeResult result = executeBulkChange(dbSession, request);
writeProtobuf(toWsResponse(result), request, response);
}
}
private BulkChangeResult executeBulkChange(DbSession dbSession, Request request) {
BulkChangeData bulkChangeData = new BulkChangeData(dbSession, request);
BulkChangeResult result = new BulkChangeResult(bulkChangeData.issues.size());
IssueChangeContext issueChangeContext = issueChangeContextByUserBuilder(new Date(system2.now()), userSession.getUuid()).build();
List<DefaultIssue> items = bulkChangeData.issues.stream()
.filter(bulkChange(issueChangeContext, bulkChangeData, result))
.toList();
issueStorage.save(dbSession, items);
refreshLiveMeasures(dbSession, bulkChangeData, result);
Set<String> assigneeUuids = items.stream().map(DefaultIssue::assignee).filter(Objects::nonNull).collect(Collectors.toSet());
Map<String, UserDto> userDtoByUuid = dbClient.userDao().selectByUuids(dbSession, assigneeUuids).stream().collect(toMap(UserDto::getUuid, u -> u));
String authorUuid = requireNonNull(userSession.getUuid(), "User uuid cannot be null");
UserDto author = dbClient.userDao().selectByUuid(dbSession, authorUuid);
checkState(author != null, "User with uuid '%s' does not exist");
sendNotification(items, bulkChangeData, userDtoByUuid, author);
distributeEvents(items, bulkChangeData);
return result;
}
private void refreshLiveMeasures(DbSession dbSession, BulkChangeData data, BulkChangeResult result) {
if (!data.shouldRefreshMeasures()) {
return;
}
Set<String> touchedComponentUuids = result.success.stream()
.map(DefaultIssue::componentUuid)
.collect(Collectors.toSet());
List<ComponentDto> touchedComponents = touchedComponentUuids.stream()
.map(data.componentsByUuid::get)
.toList();
List<DefaultIssue> changedIssues = data.issues.stream().filter(result.success::contains).toList();
issueChangePostProcessor.process(dbSession, changedIssues, touchedComponents, false);
}
private static Predicate<DefaultIssue> bulkChange(IssueChangeContext issueChangeContext, BulkChangeData bulkChangeData, BulkChangeResult result) {
return issue -> {
ActionContext actionContext = new ActionContext(issue, issueChangeContext, bulkChangeData.branchComponentByUuid.get(issue.projectUuid()));
bulkChangeData.getActionsWithoutComment().forEach(applyAction(actionContext, bulkChangeData, result));
addCommentIfNeeded(actionContext, bulkChangeData);
return result.success.contains(issue);
};
}
private static Consumer<Action> applyAction(ActionContext actionContext, BulkChangeData bulkChangeData, BulkChangeResult result) {
return action -> {
DefaultIssue issue = actionContext.issue();
try {
if (action.supports(issue) && action.execute(bulkChangeData.getProperties(action.key()), actionContext)) {
result.increaseSuccess(issue);
}
} catch (Exception e) {
result.increaseFailure();
LOG.error(format("An error occur when trying to apply the action : %s on issue : %s. This issue has been ignored. Error is '%s'",
action.key(), issue.key(), e.getMessage()), e);
}
};
}
private static void addCommentIfNeeded(ActionContext actionContext, BulkChangeData bulkChangeData) {
bulkChangeData.getCommentAction().ifPresent(action -> action.execute(bulkChangeData.getProperties(action.key()), actionContext));
}
private void sendNotification(Collection<DefaultIssue> issues, BulkChangeData bulkChangeData, Map<String, UserDto> userDtoByUuid, UserDto author) {
if (!bulkChangeData.sendNotification) {
return;
}
Set<ChangedIssue> changedIssues = issues.stream()
// should not happen but filter it out anyway to avoid NPE in oldestUpdateDate call below
.filter(issue -> issue.updateDate() != null)
.map(issue -> toNotification(bulkChangeData, userDtoByUuid, issue))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (changedIssues.isEmpty()) {
return;
}
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(
changedIssues,
new UserChange(oldestUpdateDate(issues), new User(author.getUuid(), author.getLogin(), author.getName())));
notificationService.scheduleForSending(notificationSerializer.serialize(builder));
}
private void distributeEvents(Collection<DefaultIssue> issues, BulkChangeData bulkChangeData) {
boolean anyActionToDistribute = bulkChangeData.availableActions
.stream()
.anyMatch(a -> ACTIONS_TO_DISTRIBUTE.contains(a.key()));
if (!anyActionToDistribute) {
return;
}
Set<DefaultIssue> changedIssues = issues.stream()
// should not happen but filter it out anyway to avoid NPE in oldestUpdateDate call below
.filter(issue -> issue.updateDate() != null)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (changedIssues.isEmpty()) {
return;
}
issueChangeEventService.distributeIssueChangeEvent(issues, bulkChangeData.branchComponentByUuid, bulkChangeData.branchesByProjectUuid);
}
@CheckForNull
private ChangedIssue toNotification(BulkChangeData bulkChangeData, Map<String, UserDto> userDtoByUuid, DefaultIssue issue) {
BranchDto branchDto = bulkChangeData.branchesByProjectUuid.get(issue.projectUuid());
if (!hasNotificationSupport(branchDto)) {
return null;
}
RuleDto ruleDefinitionDto = bulkChangeData.rulesByKey.get(issue.ruleKey());
ComponentDto projectDto = bulkChangeData.branchComponentByUuid.get(issue.projectUuid());
if (ruleDefinitionDto == null || projectDto == null) {
return null;
}
Optional<UserDto> assignee = Optional.ofNullable(issue.assignee()).map(userDtoByUuid::get);
return new ChangedIssue.Builder(issue.key())
.setNewStatus(issue.status())
.setNewResolution(issue.resolution())
.setAssignee(assignee.map(u -> new User(u.getUuid(), u.getLogin(), u.getName())).orElse(null))
.setRule(new IssuesChangesNotificationBuilder.Rule(ruleDefinitionDto.getKey(), RuleType.valueOfNullable(ruleDefinitionDto.getType()), ruleDefinitionDto.getName()))
.setProject(new Project.Builder(projectDto.uuid())
.setKey(projectDto.getKey())
.setProjectName(projectDto.name())
.setBranchName(branchDto.isMain() ? null : branchDto.getKey())
.build())
.build();
}
private static boolean hasNotificationSupport(@Nullable BranchDto branch) {
return branch != null && branch.getBranchType() != BranchType.PULL_REQUEST;
}
private static long oldestUpdateDate(Collection<DefaultIssue> issues) {
long res = Long.MAX_VALUE;
for (DefaultIssue issue : issues) {
long issueUpdateDate = issue.updateDate().getTime();
if (issueUpdateDate < res) {
res = issueUpdateDate;
}
}
return res;
}
private static Issues.BulkChangeWsResponse toWsResponse(BulkChangeResult result) {
return Issues.BulkChangeWsResponse.newBuilder()
.setTotal(result.countTotal())
.setSuccess(result.countSuccess())
.setIgnored((long) result.countTotal() - (result.countSuccess() + result.countFailures()))
.setFailures(result.countFailures())
.build();
}
private class BulkChangeData {
private final Map<String, Map<String, Object>> propertiesByActions;
private final boolean sendNotification;
private final Collection<DefaultIssue> issues;
private final Map<String, ComponentDto> branchComponentByUuid;
private final Map<String, BranchDto> branchesByProjectUuid;
private final Map<String, ComponentDto> componentsByUuid;
private final Map<RuleKey, RuleDto> rulesByKey;
private final List<Action> availableActions;
BulkChangeData(DbSession dbSession, Request request) {
this.sendNotification = request.mandatoryParamAsBoolean(PARAM_SEND_NOTIFICATIONS);
this.propertiesByActions = toPropertiesByActions(request);
List<String> issueKeys = request.mandatoryParamAsStrings(PARAM_ISSUES);
checkArgument(issueKeys.size() <= MAX_PAGE_SIZE, "Number of issues is limited to %s", MAX_PAGE_SIZE);
List<IssueDto> allIssues = dbClient.issueDao().selectByKeys(dbSession, issueKeys)
.stream()
.filter(issueDto -> SECURITY_HOTSPOT.getDbConstant() != issueDto.getType())
.toList();
List<ComponentDto> allBranches = getComponents(dbSession, allIssues.stream().map(IssueDto::getProjectUuid).collect(Collectors.toSet()));
this.branchComponentByUuid = getAuthorizedComponents(allBranches).stream().collect(toMap(ComponentDto::uuid, identity()));
this.branchesByProjectUuid = dbClient.branchDao().selectByUuids(dbSession, branchComponentByUuid.keySet()).stream()
.collect(toMap(BranchDto::getUuid, identity()));
this.issues = getAuthorizedIssues(allIssues);
this.componentsByUuid = getComponents(dbSession,
issues.stream().map(DefaultIssue::componentUuid).collect(Collectors.toSet())).stream()
.collect(toMap(ComponentDto::uuid, identity()));
this.rulesByKey = dbClient.ruleDao().selectByKeys(dbSession,
issues.stream().map(DefaultIssue::ruleKey).collect(Collectors.toSet())).stream()
.collect(toMap(RuleDto::getKey, identity()));
this.availableActions = actions.stream()
.filter(action -> propertiesByActions.containsKey(action.key()))
.filter(action -> action.verify(getProperties(action.key()), issues, userSession))
.toList();
}
private List<ComponentDto> getComponents(DbSession dbSession, Collection<String> componentUuids) {
return dbClient.componentDao().selectByUuids(dbSession, componentUuids);
}
private List<ComponentDto> getAuthorizedComponents(List<ComponentDto> projectDtos) {
return userSession.keepAuthorizedComponents(UserRole.USER, projectDtos);
}
private List<DefaultIssue> getAuthorizedIssues(List<IssueDto> allIssues) {
Set<String> branchUuids = branchComponentByUuid.values().stream().map(ComponentDto::uuid).collect(Collectors.toSet());
return allIssues.stream()
.filter(issue -> branchUuids.contains(issue.getProjectUuid()))
.map(IssueDto::toDefaultIssue)
.toList();
}
Map<String, Object> getProperties(String actionKey) {
return propertiesByActions.get(actionKey);
}
List<Action> getActionsWithoutComment() {
return availableActions.stream().filter(action -> !action.key().equals(COMMENT_KEY)).toList();
}
Optional<Action> getCommentAction() {
return availableActions.stream().filter(action -> action.key().equals(COMMENT_KEY)).findFirst();
}
private Map<String, Map<String, Object>> toPropertiesByActions(Request request) {
Map<String, Map<String, Object>> properties = new HashMap<>();
request.getParam(PARAM_ASSIGN, value -> properties.put(AssignAction.ASSIGN_KEY, new HashMap<>(of(ASSIGNEE_PARAMETER, value))));
request.getParam(PARAM_SET_SEVERITY, value -> properties.put(SET_SEVERITY_KEY, new HashMap<>(of(SEVERITY_PARAMETER, value))));
request.getParam(PARAM_SET_TYPE, value -> properties.put(SET_TYPE_KEY, new HashMap<>(of(TYPE_PARAMETER, value))));
request.getParam(PARAM_DO_TRANSITION, value -> properties.put(DO_TRANSITION_KEY, new HashMap<>(of(TRANSITION_PARAMETER, value))));
request.getParam(PARAM_ADD_TAGS, value -> properties.put(AddTagsAction.KEY, new HashMap<>(of(TAGS_PARAMETER, value))));
request.getParam(PARAM_REMOVE_TAGS, value -> properties.put(RemoveTagsAction.KEY, new HashMap<>(of(TAGS_PARAMETER, value))));
request.getParam(PARAM_COMMENT, value -> properties.put(COMMENT_KEY, new HashMap<>(of(COMMENT_PROPERTY, value))));
checkAtLeastOneActionIsDefined(properties.keySet());
return properties;
}
private void checkAtLeastOneActionIsDefined(Set<String> actions) {
long actionsDefined = actions.stream().filter(action -> !action.equals(COMMENT_KEY)).count();
checkArgument(actionsDefined > 0, "At least one action must be provided");
}
private boolean shouldRefreshMeasures() {
return availableActions.stream().anyMatch(Action::shouldRefreshMeasures);
}
}
private static class BulkChangeResult {
private final int total;
private final Set<DefaultIssue> success = new HashSet<>();
private int failures = 0;
BulkChangeResult(int total) {
this.total = total;
}
void increaseSuccess(DefaultIssue issue) {
this.success.add(issue);
}
void increaseFailure() {
this.failures++;
}
int countTotal() {
return total;
}
int countSuccess() {
return success.size();
}
int countFailures() {
return failures;
}
}
}
| 22,619 | 45.639175 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/ChangelogAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueChangeWSSupport;
import org.sonar.server.issue.IssueChangeWSSupport.Load;
import org.sonar.server.issue.IssueFinder;
import org.sonarqube.ws.Issues.ChangelogWsResponse;
import static java.util.Collections.singleton;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_CHANGELOG;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
public class ChangelogAction implements IssuesWsAction {
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final IssueChangeWSSupport issueChangeSupport;
public ChangelogAction(DbClient dbClient, IssueFinder issueFinder, IssueChangeWSSupport issueChangeSupport) {
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.issueChangeSupport = issueChangeSupport;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_CHANGELOG)
.setDescription("Display changelog of an issue.<br/>" +
"Requires the 'Browse' permission on the project of the specified issue.")
.setSince("4.1")
.setChangelog(
new Change("9.7", "'externalUser' and 'webhookSource' information added to the answer"),
new Change("6.3", "changes on effort is expressed with the raw value in minutes (instead of the duration previously)"))
.setHandler(this)
.setResponseExample(Resources.getResource(IssuesWs.class, "changelog-example.json"));
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issue = issueFinder.getByKey(dbSession, request.mandatoryParam(PARAM_ISSUE));
ChangelogWsResponse build = handle(dbSession, issue);
writeProtobuf(build, request, response);
}
}
public ChangelogWsResponse handle(DbSession dbSession, IssueDto issue) {
IssueChangeWSSupport.FormattingContext formattingContext = issueChangeSupport.newFormattingContext(dbSession, singleton(issue), Load.CHANGE_LOG);
ChangelogWsResponse.Builder builder = ChangelogWsResponse.newBuilder();
issueChangeSupport.formatChangelog(issue, formattingContext)
.forEach(builder::addChangelog);
return builder.build();
}
}
| 3,742 | 41.534091 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/ComponentTagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.issue.index.IssueQuery;
import org.sonar.server.issue.index.IssueQueryFactory;
import static java.util.Collections.singletonList;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.server.issue.index.IssueQueryFactory.ISSUE_TYPE_NAMES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_COMPONENT_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_UUID;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AFTER;
/**
* List issue tags matching a given query.
*/
public class ComponentTagsAction implements IssuesWsAction {
private final IssueIndex issueIndex;
private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
private final IssueQueryFactory queryService;
private final DbClient dbClient;
public ComponentTagsAction(IssueIndex issueIndex,
IssueIndexSyncProgressChecker issueIndexSyncProgressChecker,
IssueQueryFactory queryService, DbClient dbClient) {
this.issueIndex = issueIndex;
this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
this.queryService = queryService;
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction(ACTION_COMPONENT_TAGS)
.setHandler(this)
.setSince("5.1")
.setInternal(true)
.setDescription("List tags for the issues under a given component (including issues on the descendants of the component)"
+ "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
.setResponseExample(Resources.getResource(getClass(), "component-tags-example.json"));
action.createParam(PARAM_COMPONENT_UUID)
.setDescription("A component UUID")
.setRequired(true)
.setExampleValue("7d8749e8-3070-4903-9188-bdd82933bb92");
action.createParam(PARAM_CREATED_AFTER)
.setDescription("To retrieve tags on issues created after the given date (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided.")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PAGE_SIZE)
.setDescription("The maximum size of the list to return")
.setExampleValue("25")
.setDefaultValue("10");
}
@Override
public void handle(Request request, Response response) throws Exception {
String componentUuid = request.mandatoryParam(PARAM_COMPONENT_UUID);
checkIfAnyComponentsNeedIssueSync(componentUuid);
SearchRequest searchRequest = new SearchRequest()
.setComponentUuids(singletonList(componentUuid))
.setTypes(ISSUE_TYPE_NAMES)
.setResolved(false)
.setCreatedAfter(request.param(PARAM_CREATED_AFTER));
IssueQuery query = queryService.create(searchRequest);
int pageSize = request.mandatoryParamAsInt(PAGE_SIZE);
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject().name("tags").beginArray();
for (Map.Entry<String, Long> tag : issueIndex.countTags(query, pageSize).entrySet()) {
json.beginObject()
.prop("key", tag.getKey())
.prop("value", tag.getValue())
.endObject();
}
json.endArray().endObject();
}
}
private void checkIfAnyComponentsNeedIssueSync(String componentUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<ComponentDto> componentDto = dbClient.componentDao().selectByUuid(dbSession, componentUuid);
if (componentDto.isPresent()) {
issueIndexSyncProgressChecker.checkIfComponentNeedIssueSync(dbSession, componentDto.get().getKey());
} else {
issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(dbSession);
}
}
}
}
| 5,283 | 40.28125 | 127 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/DeleteCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Objects;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_DELETE_COMMENT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMMENT;
public class DeleteCommentAction implements IssuesWsAction {
private final UserSession userSession;
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final OperationResponseWriter responseWriter;
public DeleteCommentAction(UserSession userSession, DbClient dbClient, IssueFinder issueFinder, OperationResponseWriter responseWriter) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_DELETE_COMMENT)
.setDescription("Delete a comment.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified issue.")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.3", "the response returns the issue with all its details"),
new Change("6.3", "the 'key' parameter is renamed 'comment'"))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "delete_comment-example.json"))
.setPost(true);
action.createParam(PARAM_COMMENT)
.setDescription("Comment key")
.setSince("6.3")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
}
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
CommentData commentData = loadCommentData(dbSession, request);
deleteComment(dbSession, commentData);
IssueDto issueDto = commentData.getIssueDto();
responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
}
}
private CommentData loadCommentData(DbSession dbSession, Request request) {
return new CommentData(dbSession, request.mandatoryParam(PARAM_COMMENT));
}
private void deleteComment(DbSession dbSession, CommentData commentData) {
dbClient.issueChangeDao().deleteByKey(dbSession, commentData.getIssueChangeDto().getKey());
dbSession.commit();
}
private class CommentData {
private final IssueChangeDto issueChangeDto;
private final IssueDto issueDto;
CommentData(DbSession dbSession, String commentKey) {
this.issueChangeDto = dbClient.issueChangeDao().selectCommentByKey(dbSession, commentKey)
.orElseThrow(() -> new NotFoundException(format("Comment with key '%s' does not exist", commentKey)));
// Load issue now to quickly fail if user hasn't permission to see it
this.issueDto = issueFinder.getByKey(dbSession, issueChangeDto.getIssueKey());
checkArgument(Objects.equals(issueChangeDto.getUserUuid(), userSession.getUuid()), "You can only delete your own comments");
}
IssueChangeDto getIssueChangeDto() {
return issueChangeDto;
}
IssueDto getIssueDto() {
return issueDto;
}
}
}
| 5,045 | 40.360656 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/DoTransitionAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Date;
import org.sonar.api.issue.DefaultTransitions;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.issue.TransitionService;
import org.sonar.server.pushapi.issues.IssueChangeEventService;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static org.sonar.api.issue.DefaultTransitions.OPEN_AS_VULNERABILITY;
import static org.sonar.api.issue.DefaultTransitions.RESET_AS_TO_REVIEW;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_REVIEWED;
import static org.sonar.api.issue.DefaultTransitions.SET_AS_IN_REVIEW;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_DO_TRANSITION;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TRANSITION;
public class DoTransitionAction implements IssuesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final IssueChangeEventService issueChangeEventService;
private final IssueFinder issueFinder;
private final IssueUpdater issueUpdater;
private final TransitionService transitionService;
private final OperationResponseWriter responseWriter;
private final System2 system2;
public DoTransitionAction(DbClient dbClient, UserSession userSession, IssueChangeEventService issueChangeEventService,
IssueFinder issueFinder, IssueUpdater issueUpdater, TransitionService transitionService,
OperationResponseWriter responseWriter, System2 system2) {
this.dbClient = dbClient;
this.userSession = userSession;
this.issueChangeEventService = issueChangeEventService;
this.issueFinder = issueFinder;
this.issueUpdater = issueUpdater;
this.transitionService = transitionService;
this.responseWriter = responseWriter;
this.system2 = system2;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_DO_TRANSITION)
.setDescription("Do workflow transition on an issue. Requires authentication and Browse permission on project.<br/>" +
"The transitions '" + DefaultTransitions.WONT_FIX + "' and '" + DefaultTransitions.FALSE_POSITIVE + "' require the permission 'Administer Issues'.<br/>" +
"The transitions involving security hotspots require the permission 'Administer Security Hotspot'.")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("8.1", format("transitions '%s' and '%s' are no more supported", SET_AS_IN_REVIEW, OPEN_AS_VULNERABILITY)),
new Change("7.8", format("added '%s', %s, %s and %s transitions for security hotspots ", SET_AS_IN_REVIEW, RESOLVE_AS_REVIEWED, OPEN_AS_VULNERABILITY, RESET_AS_TO_REVIEW)),
new Change("7.3", "added transitions for security hotspots"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "do_transition-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_TRANSITION)
.setDescription("Transition")
.setRequired(true)
.setPossibleValues(DefaultTransitions.ALL);
}
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
String issue = request.mandatoryParam(PARAM_ISSUE);
try (DbSession dbSession = dbClient.openSession(false)) {
IssueDto issueDto = issueFinder.getByKey(dbSession, issue);
SearchResponseData preloadedSearchResponseData = doTransition(dbSession, issueDto, request.mandatoryParam(PARAM_TRANSITION));
responseWriter.write(issue, preloadedSearchResponseData, request, response);
}
}
private SearchResponseData doTransition(DbSession session, IssueDto issueDto, String transitionKey) {
DefaultIssue defaultIssue = issueDto.toDefaultIssue();
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(system2.now()), userSession.getUuid()).withRefreshMeasures().build();
transitionService.checkTransitionPermission(transitionKey, defaultIssue);
if (transitionService.doTransition(defaultIssue, context, transitionKey)) {
BranchDto branch = issueUpdater.getBranch(session, defaultIssue);
SearchResponseData response = issueUpdater.saveIssueAndPreloadSearchResponseData(session, defaultIssue, context, branch);
if (branch.getBranchType().equals(BRANCH) && response.getComponentByUuid(defaultIssue.projectUuid()) != null) {
issueChangeEventService.distributeIssueChangeEvent(defaultIssue, null, null, transitionKey, branch,
response.getComponentByUuid(defaultIssue.projectUuid()).getKey());
}
return response;
}
return new SearchResponseData(issueDto);
}
}
| 6,739 | 49.298507 | 180 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/EditCommentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Objects;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_EDIT_COMMENT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMMENT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TEXT;
public class EditCommentAction implements IssuesWsAction {
private final System2 system2;
private final UserSession userSession;
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final OperationResponseWriter responseWriter;
public EditCommentAction(System2 system2, UserSession userSession, DbClient dbClient, IssueFinder issueFinder, OperationResponseWriter responseWriter) {
this.system2 = system2;
this.userSession = userSession;
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_EDIT_COMMENT)
.setDescription("Edit a comment.<br/>" +
"Requires authentication and the following permission: 'Browse' on the project of the specified issue.")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.3", "the response returns the issue with all its details"),
new Change("6.3", format("the 'key' parameter has been renamed %s", PARAM_COMMENT)),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "edit_comment-example.json"))
.setPost(true);
action.createParam(PARAM_COMMENT)
.setDescription("Comment key")
.setSince("6.3")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_TEXT)
.setDescription("Comment text")
.setRequired(true)
.setExampleValue("Won't fix because it doesn't apply to the context");
}
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
CommentData commentData = loadCommentData(dbSession, toWsRequest(request));
updateComment(dbSession, commentData);
IssueDto issueDto = commentData.getIssueDto();
responseWriter.write(issueDto.getKey(), new SearchResponseData(issueDto), request, response);
}
}
private CommentData loadCommentData(DbSession dbSession, EditCommentRequest request) {
return new CommentData(dbSession, request);
}
private void updateComment(DbSession dbSession, CommentData commentData) {
commentData.getIssueChangeDto().setUpdatedAt(system2.now());
commentData.getIssueChangeDto().setChangeData(commentData.getRequest().getText());
dbClient.issueChangeDao().update(dbSession, commentData.getIssueChangeDto());
dbSession.commit();
}
private static EditCommentRequest toWsRequest(Request request) {
EditCommentRequest wsRequest = new EditCommentRequest(request.mandatoryParam(PARAM_COMMENT), request.mandatoryParam(PARAM_TEXT));
checkArgument(!isNullOrEmpty(wsRequest.getText()), "Cannot set empty comment to an issue");
return wsRequest;
}
private class CommentData {
private final IssueChangeDto issueChangeDto;
private final IssueDto issueDto;
private final EditCommentRequest request;
CommentData(DbSession dbSession, EditCommentRequest request) {
this.request = request;
this.issueChangeDto = dbClient.issueChangeDao().selectCommentByKey(dbSession, request.getComment())
.orElseThrow(() -> new NotFoundException(format("Comment with key '%s' does not exist", request.getComment())));
// Load issue now to quickly fail if user hasn't permission to see it
this.issueDto = issueFinder.getByKey(dbSession, issueChangeDto.getIssueKey());
checkArgument(Objects.equals(issueChangeDto.getUserUuid(), userSession.getUuid()), "You can only edit your own comments");
}
IssueChangeDto getIssueChangeDto() {
return issueChangeDto;
}
IssueDto getIssueDto() {
return issueDto;
}
EditCommentRequest getRequest() {
return request;
}
}
public static class EditCommentRequest {
private final String comment;
private final String text;
public EditCommentRequest(String comment, String text) {
this.comment = requireNonNull(comment, "Comment key cannot be null");
this.text = requireNonNull(text, "Text cannot be null");
}
public String getComment() {
return comment;
}
public String getText() {
return text;
}
}
}
| 6,591 | 39.195122 | 154 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/IssueUpdater.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.IssueChangePostProcessor;
import org.sonar.server.issue.WebIssueStorage;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationSerializer;
import org.sonar.server.notification.NotificationManager;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
public class IssueUpdater {
private final DbClient dbClient;
private final WebIssueStorage issueStorage;
private final NotificationManager notificationService;
private final IssueChangePostProcessor issueChangePostProcessor;
private final IssuesChangesNotificationSerializer notificationSerializer;
public IssueUpdater(DbClient dbClient, WebIssueStorage issueStorage, NotificationManager notificationService,
IssueChangePostProcessor issueChangePostProcessor, IssuesChangesNotificationSerializer notificationSerializer) {
this.dbClient = dbClient;
this.issueStorage = issueStorage;
this.notificationService = notificationService;
this.issueChangePostProcessor = issueChangePostProcessor;
this.notificationSerializer = notificationSerializer;
}
public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue, IssueChangeContext context) {
BranchDto branch = getBranch(dbSession, issue);
return saveIssueAndPreloadSearchResponseData(dbSession, issue, context, branch);
}
public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue, IssueChangeContext context, BranchDto branch) {
Optional<RuleDto> rule = getRuleByKey(dbSession, issue.getRuleKey());
ComponentDto branchComponent = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid());
ComponentDto component = getComponent(dbSession, issue, issue.componentUuid());
IssueDto issueDto = doSaveIssue(dbSession, issue, context, rule.orElse(null), branchComponent, branch);
SearchResponseData result = new SearchResponseData(issueDto);
rule.ifPresent(r -> result.addRules(singletonList(r)));
result.addComponents(singleton(branchComponent));
result.addComponents(singleton(component));
if (context.refreshMeasures()) {
List<DefaultIssue> changedIssues = result.getIssues().stream().map(IssueDto::toDefaultIssue).toList();
boolean isChangeFromWebhook = isNotEmpty(context.getWebhookSource());
issueChangePostProcessor.process(dbSession, changedIssues, singleton(component), isChangeFromWebhook);
}
return result;
}
public BranchDto getBranch(DbSession dbSession, DefaultIssue issue) {
String issueKey = issue.key();
String componentUuid = issue.componentUuid();
checkState(componentUuid != null, "Component uuid for issue key '%s' cannot be null", issueKey);
Optional<ComponentDto> componentDto = dbClient.componentDao().selectByUuid(dbSession, componentUuid);
checkState(componentDto.isPresent(), "Component not found for issue with key '%s'", issueKey);
BranchDto branchDto = dbClient.branchDao().selectByUuid(dbSession, componentDto.get().branchUuid()).orElse(null);
checkState(branchDto != null, "Branch not found for issue with key '%s'", issueKey);
return branchDto;
}
private IssueDto doSaveIssue(DbSession session, DefaultIssue issue, IssueChangeContext context,
@Nullable RuleDto ruleDto, ComponentDto project, BranchDto branchDto) {
IssueDto issueDto = issueStorage.save(session, singletonList(issue)).iterator().next();
Date updateDate = issue.updateDate();
if (
// since this method is called after an update of the issue, date should never be null
updateDate == null
// name of rule is displayed in notification, rule must therefor be present
|| ruleDto == null
// notification are not supported on PRs
|| !hasNotificationSupport(branchDto)
|| context.getWebhookSource() != null) {
return issueDto;
}
Optional<UserDto> assignee = Optional.ofNullable(issue.assignee())
.map(assigneeUuid -> dbClient.userDao().selectByUuid(session, assigneeUuid));
UserDto author = Optional.ofNullable(context.userUuid())
.map(authorUuid -> dbClient.userDao().selectByUuid(session, authorUuid))
.orElseThrow(() -> new IllegalStateException("Can not find dto for change author " + context.userUuid()));
IssuesChangesNotificationBuilder notificationBuilder = new IssuesChangesNotificationBuilder(singleton(
new ChangedIssue.Builder(issue.key())
.setNewResolution(issue.resolution())
.setNewStatus(issue.status())
.setAssignee(assignee.map(assigneeDto -> new User(assigneeDto.getUuid(), assigneeDto.getLogin(), assigneeDto.getName())).orElse(null))
.setRule(new Rule(ruleDto.getKey(), RuleType.valueOfNullable(ruleDto.getType()), ruleDto.getName()))
.setProject(new Project.Builder(project.uuid())
.setKey(project.getKey())
.setProjectName(project.name())
.setBranchName(branchDto.isMain() ? null : branchDto.getKey())
.build())
.build()),
new UserChange(updateDate.getTime(), new User(author.getUuid(), author.getLogin(), author.getName())));
notificationService.scheduleForSending(notificationSerializer.serialize(notificationBuilder));
return issueDto;
}
private static boolean hasNotificationSupport(BranchDto branch) {
return branch.getBranchType() != PULL_REQUEST;
}
private ComponentDto getComponent(DbSession dbSession, DefaultIssue issue, @Nullable String componentUuid) {
String issueKey = issue.key();
checkState(componentUuid != null, "Issue '%s' has no component", issueKey);
ComponentDto component = dbClient.componentDao().selectByUuid(dbSession, componentUuid).orElse(null);
checkState(component != null, "Component uuid '%s' for issue key '%s' cannot be found", componentUuid, issueKey);
return component;
}
private Optional<RuleDto> getRuleByKey(DbSession session, RuleKey ruleKey) {
Optional<RuleDto> rule = dbClient.ruleDao().selectByKey(session, ruleKey);
return (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED) ? rule : Optional.empty();
}
}
| 8,320 | 50.04908 | 154 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/IssueWsModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.issue.IssueChangeWSSupport;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.issue.TaintChecker;
import org.sonar.server.issue.TextRangeResponseFormatter;
import org.sonar.server.issue.TransitionService;
import org.sonar.server.issue.WebIssueStorage;
import org.sonar.server.issue.index.IssueQueryFactory;
import org.sonar.server.issue.workflow.FunctionExecutor;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.issue.ws.pull.PullActionProtobufObjectGenerator;
import org.sonar.server.issue.ws.pull.PullActionResponseWriter;
import org.sonar.server.issue.ws.pull.PullTaintActionProtobufObjectGenerator;
import org.sonar.server.qualitygate.changeevent.QGChangeEventListenersImpl;
public class IssueWsModule extends Module {
@Override
protected void configureModule() {
add(
IssueUpdater.class,
IssueFinder.class,
TransitionService.class,
WebIssueStorage.class,
IssueFieldsSetter.class,
FunctionExecutor.class,
IssueWorkflow.class,
IssueQueryFactory.class,
IssuesWs.class,
AvatarResolverImpl.class,
IssueChangeWSSupport.class,
SearchResponseLoader.class,
TextRangeResponseFormatter.class,
UserResponseFormatter.class,
SearchResponseFormat.class,
OperationResponseWriter.class,
AddCommentAction.class,
EditCommentAction.class,
DeleteCommentAction.class,
AssignAction.class,
DoTransitionAction.class,
SearchAction.class,
SetSeverityAction.class,
TagsAction.class,
SetTagsAction.class,
SetTypeAction.class,
ComponentTagsAction.class,
ReindexAction.class,
AuthorsAction.class,
ChangelogAction.class,
BulkChangeAction.class,
QGChangeEventListenersImpl.class,
TaintChecker.class,
PullAction.class,
PullTaintAction.class,
PullActionResponseWriter.class,
PullActionProtobufObjectGenerator.class,
PullTaintActionProtobufObjectGenerator.class);
}
}
| 3,064 | 35.927711 | 77 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/IssuesWs.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.api.server.ws.WebService;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.CONTROLLER_ISSUES;
public class IssuesWs implements WebService {
private final IssuesWsAction[] actions;
public IssuesWs(IssuesWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER_ISSUES);
controller.setDescription("Read and update issues.");
controller.setSince("3.6");
for (IssuesWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,507 | 31.782609 | 81 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/IssuesWsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.server.ws.WsAction;
public interface IssuesWsAction extends WsAction {
// Marker interface
}
| 992 | 35.777778 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/OperationResponseWriter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.server.ws.WsUtils;
import org.sonarqube.ws.Issues;
import static java.util.Collections.singletonList;
import static org.sonar.server.issue.ws.SearchAdditionalField.ALL_ADDITIONAL_FIELDS;
public class OperationResponseWriter {
private final SearchResponseLoader loader;
private final SearchResponseFormat format;
public OperationResponseWriter(SearchResponseLoader loader, SearchResponseFormat format) {
this.loader = loader;
this.format = format;
}
public void write(String issueKey, SearchResponseData preloadedResponseData, Request request, Response response) {
SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(singletonList(issueKey));
SearchResponseData data = loader.load(preloadedResponseData, collector, ALL_ADDITIONAL_FIELDS, null);
Issues.Operation responseBody = format.formatOperation(data);
WsUtils.writeProtobuf(responseBody, request, response);
}
}
| 1,912 | 38.040816 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/PullAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueQueryParams;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.TaintChecker;
import org.sonar.server.issue.ws.pull.PullActionProtobufObjectGenerator;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Common.RuleType;
import static java.lang.Boolean.parseBoolean;
import static java.util.Optional.ofNullable;
import static org.sonarqube.ws.WsUtils.checkArgument;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_PULL;
public class PullAction extends BasePullAction implements IssuesWsAction {
private static final String ISSUE_TYPE = "issues";
private static final String REPOSITORY_EXAMPLE = "java";
private static final String RESOURCE_EXAMPLE = "pull-example.proto";
private static final String SINCE_VERSION = "9.5";
private final DbClient dbClient;
private final TaintChecker taintChecker;
public PullAction(System2 system2, ComponentFinder componentFinder, DbClient dbClient, UserSession userSession,
PullActionProtobufObjectGenerator protobufObjectGenerator, TaintChecker taintChecker) {
super(system2, componentFinder, dbClient, userSession, protobufObjectGenerator, ACTION_PULL,
ISSUE_TYPE, REPOSITORY_EXAMPLE, SINCE_VERSION, RESOURCE_EXAMPLE);
this.dbClient = dbClient;
this.taintChecker = taintChecker;
}
@Override
protected void additionalParams(WebService.NewAction action) {
action.createParam(RULE_REPOSITORIES_PARAM)
.setDescription("Comma separated list of rule repositories. If not present all issues regardless of" +
" their rule repository are returned.")
.setExampleValue(repositoryExample);
action.createParam(RESOLVED_ONLY_PARAM)
.setDescription("If true only issues with resolved status are returned")
.setExampleValue("true");
}
@Override
protected void processAdditionalParams(Request request, BasePullRequest wsRequest) {
boolean resolvedOnly = parseBoolean(request.param(RESOLVED_ONLY_PARAM));
List<String> ruleRepositories = request.paramAsStrings(RULE_REPOSITORIES_PARAM);
if (ruleRepositories != null && !ruleRepositories.isEmpty()) {
validateRuleRepositories(ruleRepositories);
}
wsRequest
.repositories(ruleRepositories)
.resolvedOnly(resolvedOnly);
}
@Override
protected Set<String> getIssueKeysSnapshot(IssueQueryParams issueQueryParams, int page) {
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<Long> changedSinceDate = ofNullable(issueQueryParams.getChangedSince());
if (changedSinceDate.isPresent()) {
return dbClient.issueDao().selectIssueKeysByComponentUuidAndChangedSinceDate(dbSession, issueQueryParams.getBranchUuid(),
changedSinceDate.get(), issueQueryParams.getRuleRepositories(), taintChecker.getTaintRepositories(),
issueQueryParams.getLanguages(), page);
}
return dbClient.issueDao().selectIssueKeysByComponentUuid(dbSession, issueQueryParams.getBranchUuid(),
issueQueryParams.getRuleRepositories(), taintChecker.getTaintRepositories(),
issueQueryParams.getLanguages(), page);
}
}
@Override
protected IssueQueryParams initializeQueryParams(BranchDto branchDto, @Nullable List<String> languages,
@Nullable List<String> ruleRepositories, boolean resolvedOnly, @Nullable Long changedSince) {
return new IssueQueryParams(branchDto.getUuid(), languages, ruleRepositories, taintChecker.getTaintRepositories(), resolvedOnly, changedSince);
}
@Override
protected boolean filterNonClosedIssues(IssueDto issueDto, IssueQueryParams queryParams) {
return issueDto.getType() != RuleType.SECURITY_HOTSPOT_VALUE &&
(!queryParams.isResolvedOnly() || issueDto.getStatus().equals("RESOLVED"));
}
private void validateRuleRepositories(List<String> ruleRepositories) {
checkArgument(ruleRepositories
.stream()
.noneMatch(taintChecker.getTaintRepositories()::contains),
"Incorrect rule repositories list: it should only include repositories that define Issues, and no Taint Vulnerabilities");
}
}
| 5,365 | 42.626016 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/PullTaintAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueQueryParams;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.TaintChecker;
import org.sonar.server.issue.ws.pull.PullTaintActionProtobufObjectGenerator;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Common.RuleType;
import static java.util.Collections.emptyList;
import static java.util.Optional.ofNullable;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_PULL_TAINT;
public class PullTaintAction extends BasePullAction implements IssuesWsAction {
private static final String ISSUE_TYPE = "taint vulnerabilities";
private static final String RESOURCE_EXAMPLE = "pull-taint-example.proto";
private static final String SINCE_VERSION = "9.6";
private final DbClient dbClient;
private final TaintChecker taintChecker;
public PullTaintAction(System2 system2, ComponentFinder componentFinder, DbClient dbClient, UserSession userSession,
PullTaintActionProtobufObjectGenerator protobufObjectGenerator, TaintChecker taintChecker) {
super(system2, componentFinder, dbClient, userSession, protobufObjectGenerator, ACTION_PULL_TAINT,
ISSUE_TYPE, "", SINCE_VERSION, RESOURCE_EXAMPLE);
this.dbClient = dbClient;
this.taintChecker = taintChecker;
}
@Override
protected Set<String> getIssueKeysSnapshot(IssueQueryParams issueQueryParams, int page) {
Optional<Long> changedSinceDate = ofNullable(issueQueryParams.getChangedSince());
try (DbSession dbSession = dbClient.openSession(false)) {
if (changedSinceDate.isPresent()) {
return dbClient.issueDao().selectIssueKeysByComponentUuidAndChangedSinceDate(dbSession, issueQueryParams.getBranchUuid(),
changedSinceDate.get(), issueQueryParams.getRuleRepositories(), emptyList(),
issueQueryParams.getLanguages(), page);
}
return dbClient.issueDao().selectIssueKeysByComponentUuid(dbSession, issueQueryParams.getBranchUuid(),
issueQueryParams.getRuleRepositories(),
emptyList(), issueQueryParams.getLanguages(), page);
}
}
@Override
protected IssueQueryParams initializeQueryParams(BranchDto branchDto, @Nullable List<String> languages,
@Nullable List<String> ruleRepositories, boolean resolvedOnly, @Nullable Long changedSince) {
return new IssueQueryParams(branchDto.getUuid(), languages, taintChecker.getTaintRepositories(), emptyList(), false, changedSince);
}
@Override
protected boolean filterNonClosedIssues(IssueDto issueDto, IssueQueryParams queryParams) {
return issueDto.getType() != RuleType.SECURITY_HOTSPOT_VALUE;
}
}
| 3,776 | 42.413793 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/ReindexAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.index.IssueIndexer;
import org.sonar.server.user.UserSession;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
/**
* Implementation of the {@code reindex} action for the Issues WebService.
*/
public class ReindexAction implements IssuesWsAction {
private static final String ACTION = "reindex";
private final DbClient dbClient;
private final IssueIndexer issueIndexer;
private final UserSession userSession;
public ReindexAction(DbClient dbClient, IssueIndexer indexer, UserSession userSession) {
this.dbClient = dbClient;
this.issueIndexer = indexer;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION)
.setPost(true)
.setDescription("Reindex issues for a project.<br> " +
"Require 'Administer System' permission.")
.setSince("9.8")
.setHandler(this);
action
.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
String projectKey = request.mandatoryParam(PARAM_PROJECT);
ProjectDto projectDto;
try (DbSession dbSession = dbClient.openSession(false)) {
projectDto = dbClient.projectDao().selectProjectByKey(dbSession, projectKey).orElseThrow(() -> new NotFoundException("project not found"));
}
issueIndexer.indexProject(projectDto.getUuid());
response.noContent();
}
}
| 2,917 | 34.156627 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.issue.index.IssueQuery;
import org.sonar.server.issue.index.IssueQueryFactory;
import org.sonar.server.issue.index.IssueScope;
import org.sonar.server.security.SecurityStandards.SQCategory;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Issues.SearchWsResponse;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static org.sonar.api.issue.Issue.RESOLUTIONS;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED;
import static org.sonar.api.issue.Issue.STATUS_IN_REVIEW;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.api.server.ws.WebService.Param.FACETS;
import static org.sonar.api.utils.Paging.forPageIndex;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
import static org.sonar.server.issue.index.IssueIndex.FACET_ASSIGNED_TO_ME;
import static org.sonar.server.issue.index.IssueIndex.FACET_PROJECTS;
import static org.sonar.server.issue.index.IssueQueryFactory.ISSUE_STATUSES;
import static org.sonar.server.issue.index.IssueQueryFactory.UNKNOWN;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_INSECURE_INTERACTION;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_POROUS_DEFENSES;
import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_RISKY_RESOURCE;
import static org.sonar.server.security.SecurityStandards.UNKNOWN_STANDARD;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_SEARCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ADDITIONAL_FIELDS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASC;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNED;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNEES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_AUTHOR;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_BRANCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CODE_VARIANTS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_KEYS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AFTER;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AT;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_BEFORE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_IN_LAST;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CWE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_DIRECTORIES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_FILES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_IN_NEW_CODE_PERIOD;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_LANGUAGES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ON_COMPONENT_ONLY;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_ASVS_40;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_ASVS_LEVEL;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_TOP_10;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_TOP_10_2021;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PCI_DSS_32;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PCI_DSS_40;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PULL_REQUEST;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RESOLUTIONS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RESOLVED;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RULES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SANS_TOP_25;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SCOPES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SEVERITIES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SONARSOURCE_SECURITY;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_STATUSES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TIMEZONE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TYPES;
public class SearchAction implements IssuesWsAction {
private static final String LOGIN_MYSELF = "__me__";
private static final Set<String> ISSUE_SCOPES = Arrays.stream(IssueScope.values()).map(Enum::name).collect(Collectors.toSet());
private static final EnumSet<RuleType> ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS = EnumSet.complementOf(EnumSet.of(RuleType.SECURITY_HOTSPOT));
static final List<String> SUPPORTED_FACETS = List.of(
FACET_PROJECTS,
PARAM_FILES,
FACET_ASSIGNED_TO_ME,
PARAM_SEVERITIES,
PARAM_STATUSES,
PARAM_RESOLUTIONS,
PARAM_RULES,
PARAM_ASSIGNEES,
PARAM_AUTHOR,
PARAM_DIRECTORIES,
PARAM_SCOPES,
PARAM_LANGUAGES,
PARAM_TAGS,
PARAM_TYPES,
PARAM_PCI_DSS_32,
PARAM_PCI_DSS_40,
PARAM_OWASP_ASVS_40,
PARAM_OWASP_TOP_10,
PARAM_OWASP_TOP_10_2021,
PARAM_SANS_TOP_25,
PARAM_CWE,
PARAM_CREATED_AT,
PARAM_SONARSOURCE_SECURITY,
PARAM_CODE_VARIANTS
);
private static final String INTERNAL_PARAMETER_DISCLAIMER = "This parameter is mostly used by the Issues page, please prefer usage of the componentKeys parameter. ";
private static final Set<String> FACETS_REQUIRING_PROJECT = newHashSet(PARAM_FILES, PARAM_DIRECTORIES);
private final UserSession userSession;
private final IssueIndex issueIndex;
private final IssueQueryFactory issueQueryFactory;
private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
private final SearchResponseLoader searchResponseLoader;
private final SearchResponseFormat searchResponseFormat;
private final System2 system2;
private final DbClient dbClient;
public SearchAction(UserSession userSession, IssueIndex issueIndex, IssueQueryFactory issueQueryFactory, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker,
SearchResponseLoader searchResponseLoader, SearchResponseFormat searchResponseFormat, System2 system2, DbClient dbClient) {
this.userSession = userSession;
this.issueIndex = issueIndex;
this.issueQueryFactory = issueQueryFactory;
this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
this.searchResponseLoader = searchResponseLoader;
this.searchResponseFormat = searchResponseFormat;
this.system2 = system2;
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction(ACTION_SEARCH)
.setHandler(this)
.setDescription("Search for issues.<br>Requires the 'Browse' permission on the specified project(s). <br>"
+ "For applications, it also requires 'Browse' permission on its child projects."
+ "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
.setSince("3.6")
.setChangelog(
new Change("10.1", "Add the 'codeVariants' parameter, facet and response field"),
new Change("10.0", "Parameter 'sansTop25' is deprecated"),
new Change("10.0", "The value 'sansTop25' for the parameter 'facets' has been deprecated"),
new Change("10.0", format("Deprecated value 'ASSIGNEE' in parameter '%s' is dropped", Param.SORT)),
new Change("10.0", format("Parameter 'sinceLeakPeriod' is removed, please use '%s' instead", PARAM_IN_NEW_CODE_PERIOD)),
new Change("9.8", "Add message formatting to issue and locations response"),
new Change("9.8", "response fields 'total', 's', 'ps' have been deprecated, please use 'paging' object instead"),
new Change("9.7", "Issues flows in the response may contain a description and a type"),
new Change("9.6", "Response field 'fromHotspot' dropped."),
new Change("9.6", "Added facets 'pciDss-3.2' and 'pciDss-4.0"),
new Change("9.6", "Added parameters 'pciDss-3.2' and 'pciDss-4.0"),
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("9.6", "New possible value for 'additionalFields' parameter: 'ruleDescriptionContextKey'"),
new Change("9.6", "Facet 'moduleUuids' is dropped."),
new Change("9.4", format("Parameter 'sinceLeakPeriod' is deprecated, please use '%s' instead", PARAM_IN_NEW_CODE_PERIOD)),
new Change("9.2", "Response field 'quickFixAvailable' added"),
new Change("9.1", "Deprecated parameters 'authors', 'facetMode' and 'moduleUuids' were dropped"),
new Change("8.6", "Parameter 'timeZone' added"),
new Change("8.5", "Facet 'fileUuids' is dropped in favour of the new facet 'files'" +
"Note that they are not strictly identical, the latter returns the file paths."),
new Change("8.5", "Internal parameter 'fileUuids' has been dropped"),
new Change("8.4", "parameters 'componentUuids', 'projectKeys' has been dropped."),
new Change("8.2", "'REVIEWED', 'TO_REVIEW' status param values are no longer supported"),
new Change("8.2", "Security hotspots are no longer returned as type 'SECURITY_HOTSPOT' is not supported anymore, use dedicated api/hotspots"),
new Change("8.2", "response field 'fromHotspot' has been deprecated and is no more populated"),
new Change("8.2", "Status 'IN_REVIEW' for Security Hotspots has been deprecated"),
new Change("7.8", format("added new Security Hotspots statuses : %s, %s and %s", STATUS_TO_REVIEW, STATUS_IN_REVIEW, STATUS_REVIEWED)),
new Change("7.8", "Security hotspots are returned by default"),
new Change("7.7", format("Value 'authors' in parameter '%s' is deprecated, please use '%s' instead", FACETS, PARAM_AUTHOR)),
new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT_KEYS)),
new Change("7.4", "The facet 'projectUuids' is dropped in favour of the new facet 'projects'. " +
"Note that they are not strictly identical, the latter returns the project keys."),
new Change("7.4", "Parameter 'facetMode' does not accept anymore deprecated value 'debt'"),
new Change("7.3", "response field 'fromHotspot' added to issues that are security hotspots"),
new Change("7.3", "added facets 'sansTop25', 'owaspTop10' and 'cwe'"),
new Change("7.2", "response field 'externalRuleEngine' added to issues that have been imported from an external rule engine"),
new Change("7.2", format("value 'ASSIGNEE' in parameter '%s' is deprecated, it won't have any effect", Param.SORT)),
new Change("6.5", "parameters 'projects', 'projectUuids', 'moduleUuids', 'directories', 'fileUuids' are marked as internal"),
new Change("6.3", "response field 'email' is renamed 'avatar'"),
new Change("5.5", "response fields 'reporter' and 'actionPlan' are removed (drop of action plan and manual issue features)"),
new Change("5.5", "parameters 'reporters', 'actionPlans' and 'planned' are dropped and therefore ignored (drop of action plan and manual issue features)"),
new Change("5.5", "response field 'debt' is renamed 'effort'"))
.setResponseExample(getClass().getResource("search-example.json"));
action.addPagingParams(100, MAX_PAGE_SIZE);
action.createParam(FACETS)
.setDescription("Comma-separated list of the facets to be computed. No facet is computed by default.")
.setPossibleValues(SUPPORTED_FACETS);
action.addSortParams(IssueQuery.SORTS, null, true);
action.createParam(PARAM_ADDITIONAL_FIELDS)
.setSince("5.2")
.setDescription("Comma-separated list of the optional fields to be returned in response. Action plans are dropped in 5.5, it is not returned in the response.")
.setPossibleValues(SearchAdditionalField.possibleValues());
addComponentRelatedParams(action);
action.createParam(PARAM_ISSUES)
.setDescription("Comma-separated list of issue keys")
.setExampleValue("5bccd6e8-f525-43a2-8d76-fcb13dde79ef");
action.createParam(PARAM_SEVERITIES)
.setDescription("Comma-separated list of severities")
.setExampleValue(Severity.BLOCKER + "," + Severity.CRITICAL)
.setPossibleValues(Severity.ALL);
action.createParam(PARAM_STATUSES)
.setDescription("Comma-separated list of statuses")
.setExampleValue(STATUS_OPEN + "," + STATUS_REOPENED)
.setPossibleValues(ISSUE_STATUSES);
action.createParam(PARAM_RESOLUTIONS)
.setDescription("Comma-separated list of resolutions")
.setExampleValue(RESOLUTION_FIXED + "," + RESOLUTION_REMOVED)
.setPossibleValues(RESOLUTIONS);
action.createParam(PARAM_RESOLVED)
.setDescription("To match resolved or unresolved issues")
.setBooleanPossibleValues();
action.createParam(PARAM_RULES)
.setDescription("Comma-separated list of coding rule keys. Format is <repository>:<rule>")
.setExampleValue("java:S1144");
action.createParam(PARAM_TAGS)
.setDescription("Comma-separated list of tags.")
.setExampleValue("security,convention");
action.createParam(PARAM_TYPES)
.setDescription("Comma-separated list of types.")
.setSince("5.5")
.setPossibleValues(ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS)
.setExampleValue(format("%s,%s", RuleType.CODE_SMELL, RuleType.BUG));
action.createParam(PARAM_OWASP_ASVS_LEVEL)
.setDescription("Level of OWASP ASVS categories.")
.setSince("9.7")
.setPossibleValues(1, 2, 3);
action.createParam(PARAM_PCI_DSS_32)
.setDescription("Comma-separated list of PCI DSS v3.2 categories.")
.setSince("9.6")
.setExampleValue("4,6.5.8,10.1");
action.createParam(PARAM_PCI_DSS_40)
.setDescription("Comma-separated list of PCI DSS v4.0 categories.")
.setSince("9.6")
.setExampleValue("4,6.5.8,10.1");
action.createParam(PARAM_OWASP_ASVS_40)
.setDescription("Comma-separated list of OWASP ASVS v4.0 categories.")
.setSince("9.7")
.setExampleValue("6,10.1.1");
action.createParam(PARAM_OWASP_TOP_10)
.setDescription("Comma-separated list of OWASP Top 10 2017 lowercase categories.")
.setSince("7.3")
.setPossibleValues("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
action.createParam(PARAM_OWASP_TOP_10_2021)
.setDescription("Comma-separated list of OWASP Top 10 2021 lowercase categories.")
.setSince("9.4")
.setPossibleValues("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
action.createParam(PARAM_SANS_TOP_25)
.setDescription("Comma-separated list of SANS Top 25 categories.")
.setDeprecatedSince("10.0")
.setSince("7.3")
.setPossibleValues(SANS_TOP_25_INSECURE_INTERACTION, SANS_TOP_25_RISKY_RESOURCE, SANS_TOP_25_POROUS_DEFENSES);
action.createParam(PARAM_CWE)
.setDescription("Comma-separated list of CWE identifiers. Use '" + UNKNOWN_STANDARD + "' to select issues not associated to any CWE.")
.setExampleValue("12,125," + UNKNOWN_STANDARD);
action.createParam(PARAM_SONARSOURCE_SECURITY)
.setDescription("Comma-separated list of SonarSource security categories. Use '" + SQCategory.OTHERS.getKey() + "' to select issues not associated" +
" with any category")
.setSince("7.8")
.setPossibleValues(Arrays.stream(SQCategory.values()).map(SQCategory::getKey).toList());
action.createParam(PARAM_AUTHOR)
.setDescription("SCM accounts. To set several values, the parameter must be called once for each value.")
.setExampleValue("author=torvalds@linux-foundation.org&author=linux@fondation.org");
action.createParam(PARAM_ASSIGNEES)
.setDescription("Comma-separated list of assignee logins. The value '__me__' can be used as a placeholder for user who performs the request")
.setExampleValue("admin,usera,__me__");
action.createParam(PARAM_ASSIGNED)
.setDescription("To retrieve assigned or unassigned issues")
.setBooleanPossibleValues();
action.createParam(PARAM_SCOPES)
.setDescription("Comma-separated list of scopes. Available since 8.5")
.setPossibleValues(IssueScope.MAIN.name(), IssueScope.TEST.name())
.setExampleValue(format("%s,%s", IssueScope.MAIN.name(), IssueScope.TEST.name()));
action.createParam(PARAM_LANGUAGES)
.setDescription("Comma-separated list of languages. Available since 4.4")
.setExampleValue("java,js");
action.createParam(PARAM_CREATED_AT)
.setDescription("Datetime to retrieve issues created during a specific analysis")
.setExampleValue("2017-10-19T13:00:00+0200");
action.createParam(PARAM_CREATED_AFTER)
.setDescription("To retrieve issues created after the given date (inclusive). <br>" +
"Either a date (use '" + PARAM_TIMEZONE + "' attribute or it will default to server timezone) or datetime can be provided. <br>" +
"If this parameter is set, createdInLast must not be set")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_CREATED_BEFORE)
.setDescription("To retrieve issues created before the given date (exclusive). <br>" +
"Either a date (use '" + PARAM_TIMEZONE + "' attribute or it will default to server timezone) or datetime can be provided.")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_CREATED_IN_LAST)
.setDescription("To retrieve issues created during a time span before the current time (exclusive). " +
"Accepted units are 'y' for year, 'm' for month, 'w' for week and 'd' for day. " +
"If this parameter is set, createdAfter must not be set")
.setExampleValue("1m2w (1 month 2 weeks)");
action.createParam(PARAM_IN_NEW_CODE_PERIOD)
.setDescription("To retrieve issues created in the new code period.<br>" +
"If this parameter is set to a truthy value, createdAfter must not be set and one component uuid or key must be provided.")
.setBooleanPossibleValues()
.setSince("9.4");
action.createParam(PARAM_TIMEZONE)
.setDescription(
"To resolve dates passed to '" + PARAM_CREATED_AFTER + "' or '" + PARAM_CREATED_BEFORE + "' (does not apply to datetime) and to compute creation date histogram")
.setRequired(false)
.setExampleValue("'Europe/Paris', 'Z' or '+02:00'")
.setSince("8.6");
action.createParam(PARAM_CODE_VARIANTS)
.setDescription("Comma-separated list of code variants.")
.setExampleValue("windows,linux")
.setSince("10.1");
}
private static void addComponentRelatedParams(WebService.NewAction action) {
action.createParam(PARAM_ON_COMPONENT_ONLY)
.setDescription("Return only issues at a component's level, not on its descendants (modules, directories, files, etc). " +
"This parameter is only considered when componentKeys is set.")
.setBooleanPossibleValues()
.setDefaultValue("false");
action.createParam(PARAM_COMPONENT_KEYS)
.setDescription("Comma-separated list of component keys. Retrieve issues associated to a specific list of components (and all its descendants). " +
"A component can be a portfolio, project, module, directory or file.")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_PROJECTS)
.setDescription("To retrieve issues associated to a specific list of projects (comma-separated list of project keys). " +
INTERNAL_PARAMETER_DISCLAIMER +
"If this parameter is set, projectUuids must not be set.")
.setInternal(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_DIRECTORIES)
.setDescription("To retrieve issues associated to a specific list of directories (comma-separated list of directory paths). " +
"This parameter is only meaningful when a module is selected. " +
INTERNAL_PARAMETER_DISCLAIMER)
.setInternal(true)
.setSince("5.1")
.setExampleValue("src/main/java/org/sonar/server/");
action.createParam(PARAM_FILES)
.setDescription("To retrieve issues associated to a specific list of files (comma-separated list of file paths). " +
INTERNAL_PARAMETER_DISCLAIMER)
.setInternal(true)
.setExampleValue("src/main/java/org/sonar/server/Test.java");
action.createParam(PARAM_BRANCH)
.setDescription("Branch key. Not available in the community edition.")
.setExampleValue(KEY_BRANCH_EXAMPLE_001)
.setSince("6.6");
action.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id. Not available in the community edition.")
.setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001)
.setSince("7.1");
}
@Override
public final void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
SearchRequest searchRequest = toSearchWsRequest(dbSession, request);
checkIfNeedIssueSync(dbSession, searchRequest);
SearchWsResponse searchWsResponse = doHandle(searchRequest);
writeProtobuf(searchWsResponse, request, response);
}
}
private SearchWsResponse doHandle(SearchRequest request) {
// prepare the Elasticsearch request
SearchOptions options = createSearchOptionsFromRequest(request);
EnumSet<SearchAdditionalField> additionalFields = SearchAdditionalField.getFromRequest(request);
IssueQuery query = issueQueryFactory.create(request);
Set<String> facetsRequiringProjectParameter = options.getFacets().stream()
.filter(FACETS_REQUIRING_PROJECT::contains)
.collect(Collectors.toSet());
checkArgument(facetsRequiringProjectParameter.isEmpty() ||
(!query.projectUuids().isEmpty()), "Facet(s) '%s' require to also filter by project",
String.join(",", facetsRequiringProjectParameter));
// execute request
SearchResponse result = issueIndex.search(query, options);
result.getHits();
List<String> issueKeys = Arrays.stream(result.getHits().getHits())
.map(SearchHit::getId)
.toList();
// load the additional information to be returned in response
SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(issueKeys);
collectLoggedInUser(collector);
collectRequestParams(collector, request);
Facets facets = new Facets(result, Optional.ofNullable(query.timeZone()).orElse(system2.getDefaultTimeZone().toZoneId()));
if (!options.getFacets().isEmpty()) {
// add missing values to facets. For example if assignee "john" and facet on "assignees" are requested, then
// "john" should always be listed in the facet. If it is not present, then it is added with value zero.
// This is a constraint from webapp UX.
completeFacets(facets, request, query);
collectFacets(collector, facets);
}
SearchResponseData preloadedData = new SearchResponseData();
preloadedData.addRules(List.copyOf(query.rules()));
SearchResponseData data = searchResponseLoader.load(preloadedData, collector, additionalFields, facets);
// FIXME allow long in Paging
Paging paging = forPageIndex(options.getPage()).withPageSize(options.getLimit()).andTotal((int) getTotalHits(result).value);
return searchResponseFormat.formatSearch(additionalFields, data, paging, facets);
}
private static TotalHits getTotalHits(SearchResponse response) {
return ofNullable(response.getHits().getTotalHits()).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results"));
}
private static SearchOptions createSearchOptionsFromRequest(SearchRequest request) {
SearchOptions options = new SearchOptions();
options.setPage(request.getPage(), request.getPageSize());
List<String> facets = request.getFacets();
if (facets == null || facets.isEmpty()) {
return options;
}
options.addFacets(facets);
return options;
}
private void completeFacets(Facets facets, SearchRequest request, IssueQuery query) {
addMandatoryValuesToFacet(facets, PARAM_SEVERITIES, Severity.ALL);
addMandatoryValuesToFacet(facets, PARAM_STATUSES, ISSUE_STATUSES);
addMandatoryValuesToFacet(facets, PARAM_RESOLUTIONS, concat(singletonList(""), RESOLUTIONS));
addMandatoryValuesToFacet(facets, FACET_PROJECTS, query.projectUuids());
addMandatoryValuesToFacet(facets, PARAM_FILES, query.files());
List<String> assignees = Lists.newArrayList("");
List<String> assigneesFromRequest = request.getAssigneeUuids();
if (assigneesFromRequest != null) {
assignees.addAll(assigneesFromRequest);
assignees.remove(LOGIN_MYSELF);
}
addMandatoryValuesToFacet(facets, PARAM_ASSIGNEES, assignees);
addMandatoryValuesToFacet(facets, FACET_ASSIGNED_TO_ME, singletonList(userSession.getUuid()));
addMandatoryValuesToFacet(facets, PARAM_RULES, query.ruleUuids());
addMandatoryValuesToFacet(facets, PARAM_SCOPES, ISSUE_SCOPES);
addMandatoryValuesToFacet(facets, PARAM_LANGUAGES, request.getLanguages());
addMandatoryValuesToFacet(facets, PARAM_TAGS, request.getTags());
setTypesFacet(facets);
addMandatoryValuesToFacet(facets, PARAM_PCI_DSS_32, request.getPciDss32());
addMandatoryValuesToFacet(facets, PARAM_PCI_DSS_40, request.getPciDss40());
addMandatoryValuesToFacet(facets, PARAM_OWASP_ASVS_40, request.getOwaspAsvs40());
addMandatoryValuesToFacet(facets, PARAM_OWASP_TOP_10, request.getOwaspTop10());
addMandatoryValuesToFacet(facets, PARAM_OWASP_TOP_10_2021, request.getOwaspTop10For2021());
addMandatoryValuesToFacet(facets, PARAM_SANS_TOP_25, request.getSansTop25());
addMandatoryValuesToFacet(facets, PARAM_CWE, request.getCwe());
addMandatoryValuesToFacet(facets, PARAM_SONARSOURCE_SECURITY, request.getSonarsourceSecurity());
addMandatoryValuesToFacet(facets, PARAM_CODE_VARIANTS, request.getCodeVariants());
}
private static void setTypesFacet(Facets facets) {
Map<String, Long> typeFacet = facets.get(PARAM_TYPES);
if (typeFacet != null) {
typeFacet.remove(RuleType.SECURITY_HOTSPOT.name());
}
addMandatoryValuesToFacet(facets, PARAM_TYPES, ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS.stream().map(Enum::name).toList());
}
private static void addMandatoryValuesToFacet(Facets facets, String facetName, @Nullable Iterable<String> mandatoryValues) {
Map<String, Long> buckets = facets.get(facetName);
if (buckets != null && mandatoryValues != null) {
for (String mandatoryValue : mandatoryValues) {
buckets.putIfAbsent(mandatoryValue, 0L);
}
}
}
private void collectLoggedInUser(SearchResponseLoader.Collector collector) {
if (userSession.isLoggedIn()) {
collector.addUserUuids(singletonList(userSession.getUuid()));
}
}
private static void collectFacets(SearchResponseLoader.Collector collector, Facets facets) {
collector.addProjectUuids(facets.getBucketKeys(FACET_PROJECTS));
collector.addRuleIds(facets.getBucketKeys(PARAM_RULES));
collector.addUserUuids(facets.getBucketKeys(PARAM_ASSIGNEES));
}
private static void collectRequestParams(SearchResponseLoader.Collector collector, SearchRequest request) {
collector.addUserUuids(request.getAssigneeUuids());
}
private SearchRequest toSearchWsRequest(DbSession dbSession, Request request) {
return new SearchRequest()
.setAdditionalFields(request.paramAsStrings(PARAM_ADDITIONAL_FIELDS))
.setAsc(request.mandatoryParamAsBoolean(PARAM_ASC))
.setAssigned(request.paramAsBoolean(PARAM_ASSIGNED))
.setAssigneesUuid(getLogins(dbSession, request.paramAsStrings(PARAM_ASSIGNEES)))
.setAuthors(request.multiParam(PARAM_AUTHOR))
.setComponentKeys(request.paramAsStrings(PARAM_COMPONENT_KEYS))
.setCreatedAfter(request.param(PARAM_CREATED_AFTER))
.setCreatedAt(request.param(PARAM_CREATED_AT))
.setCreatedBefore(request.param(PARAM_CREATED_BEFORE))
.setCreatedInLast(request.param(PARAM_CREATED_IN_LAST))
.setDirectories(request.paramAsStrings(PARAM_DIRECTORIES))
.setFacets(request.paramAsStrings(FACETS))
.setFiles(request.paramAsStrings(PARAM_FILES))
.setInNewCodePeriod(request.paramAsBoolean(PARAM_IN_NEW_CODE_PERIOD))
.setIssues(request.paramAsStrings(PARAM_ISSUES))
.setScopes(request.paramAsStrings(PARAM_SCOPES))
.setLanguages(request.paramAsStrings(PARAM_LANGUAGES))
.setOnComponentOnly(request.paramAsBoolean(PARAM_ON_COMPONENT_ONLY))
.setBranch(request.param(PARAM_BRANCH))
.setPullRequest(request.param(PARAM_PULL_REQUEST))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setProjectKeys(request.paramAsStrings(PARAM_PROJECTS))
.setResolutions(request.paramAsStrings(PARAM_RESOLUTIONS))
.setResolved(request.paramAsBoolean(PARAM_RESOLVED))
.setRules(request.paramAsStrings(PARAM_RULES))
.setSort(request.param(Param.SORT))
.setSeverities(request.paramAsStrings(PARAM_SEVERITIES))
.setStatuses(request.paramAsStrings(PARAM_STATUSES))
.setTags(request.paramAsStrings(PARAM_TAGS))
.setTypes(allRuleTypesExceptHotspotsIfEmpty(request.paramAsStrings(PARAM_TYPES)))
.setPciDss32(request.paramAsStrings(PARAM_PCI_DSS_32))
.setPciDss40(request.paramAsStrings(PARAM_PCI_DSS_40))
.setOwaspAsvsLevel(request.paramAsInt(PARAM_OWASP_ASVS_LEVEL))
.setOwaspAsvs40(request.paramAsStrings(PARAM_OWASP_ASVS_40))
.setOwaspTop10(request.paramAsStrings(PARAM_OWASP_TOP_10))
.setOwaspTop10For2021(request.paramAsStrings(PARAM_OWASP_TOP_10_2021))
.setSansTop25(request.paramAsStrings(PARAM_SANS_TOP_25))
.setCwe(request.paramAsStrings(PARAM_CWE))
.setSonarsourceSecurity(request.paramAsStrings(PARAM_SONARSOURCE_SECURITY))
.setTimeZone(request.param(PARAM_TIMEZONE))
.setCodeVariants(request.paramAsStrings(PARAM_CODE_VARIANTS));
}
private void checkIfNeedIssueSync(DbSession dbSession, SearchRequest searchRequest) {
List<String> components = searchRequest.getComponentKeys();
if (components != null && !components.isEmpty()) {
issueIndexSyncProgressChecker.checkIfAnyComponentsNeedIssueSync(dbSession, components);
} else {
// component keys not provided - asking for global
issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(dbSession);
}
}
private static List<String> allRuleTypesExceptHotspotsIfEmpty(@Nullable List<String> types) {
if (types == null || types.isEmpty()) {
return ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS.stream().map(Enum::name).toList();
}
return types;
}
private List<String> getLogins(DbSession dbSession, @Nullable List<String> assigneeLogins) {
List<String> userLogins = new ArrayList<>();
for (String login : ofNullable(assigneeLogins).orElse(emptyList())) {
if (LOGIN_MYSELF.equals(login)) {
if (userSession.getLogin() == null) {
userLogins.add(UNKNOWN);
} else {
userLogins.add(userSession.getLogin());
}
} else {
userLogins.add(login);
}
}
List<UserDto> userDtos = dbClient.userDao().selectByLogins(dbSession, userLogins);
List<String> assigneeUuid = userDtos.stream().map(UserDto::getUuid).toList();
if ((assigneeLogins != null) && firstNonNull(assigneeUuid, emptyList()).isEmpty()) {
assigneeUuid = List.of("non-existent-uuid");
}
return assigneeUuid;
}
}
| 34,840 | 54.128165 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchAdditionalField.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.server.issue.SearchRequest;
public enum SearchAdditionalField {
ACTIONS("actions"),
COMMENTS("comments"),
LANGUAGES("languages"),
RULES("rules"),
TRANSITIONS("transitions"),
USERS("users"),
RULE_DESCRIPTION_CONTEXT_KEY("ruleDescriptionContextKey");
public static final String ALL_ALIAS = "_all";
static final EnumSet<SearchAdditionalField> ALL_ADDITIONAL_FIELDS = EnumSet.allOf(SearchAdditionalField.class);
private static final Map<String, SearchAdditionalField> BY_LABELS = new HashMap<>();
static {
for (SearchAdditionalField f : values()) {
BY_LABELS.put(f.label, f);
}
}
private final String label;
SearchAdditionalField(String label) {
this.label = label;
}
@CheckForNull
public static SearchAdditionalField findByLabel(String label) {
return BY_LABELS.get(label);
}
public static Collection<String> possibleValues() {
List<String> possibles = Lists.newArrayList(ALL_ALIAS);
possibles.addAll(BY_LABELS.keySet());
return possibles;
}
public static EnumSet<SearchAdditionalField> getFromRequest(SearchRequest request) {
List<String> labels = request.getAdditionalFields();
if (labels == null) {
return EnumSet.noneOf(SearchAdditionalField.class);
}
EnumSet<SearchAdditionalField> fields = EnumSet.noneOf(SearchAdditionalField.class);
for (String label : labels) {
if (label.equals(ALL_ALIAS)) {
return EnumSet.allOf(SearchAdditionalField.class);
}
fields.add(findByLabel(label));
}
return fields;
}
}
| 2,651 | 31.341463 | 113 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseData.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.workflow.Transition;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* All the data required to write response of api/issues/search
*/
public class SearchResponseData {
private final List<IssueDto> issues;
private Long effortTotal = null;
private final Map<String, UserDto> usersByUuid = new HashMap<>();
private final List<RuleDto> rules = new ArrayList<>();
private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
private final ListMultimap<String, IssueChangeDto> commentsByIssueKey = ArrayListMultimap.create();
private final ListMultimap<String, String> actionsByIssueKey = ArrayListMultimap.create();
private final ListMultimap<String, Transition> transitionsByIssueKey = ArrayListMultimap.create();
private final Set<String> updatableComments = new HashSet<>();
private final Map<String, BranchDto> branchesByUuid = new HashMap<>();
private final Map<String, ProjectDto> projectsByUuid = new HashMap<>();
public SearchResponseData() {
this.issues = List.of();
}
public SearchResponseData(IssueDto issue) {
checkNotNull(issue);
this.issues = List.of(issue);
}
public SearchResponseData(List<IssueDto> issues) {
checkNotNull(issues);
this.issues = issues;
}
public List<IssueDto> getIssues() {
return issues;
}
public Collection<ComponentDto> getComponents() {
return componentsByUuid.values();
}
@CheckForNull
ComponentDto getComponentByUuid(String uuid) {
return componentsByUuid.get(uuid);
}
public Map<String, ComponentDto> getComponentsByUuid() {
return componentsByUuid;
}
public List<UserDto> getUsers() {
return new ArrayList<>(usersByUuid.values());
}
public List<RuleDto> getRules() {
return rules;
}
@CheckForNull
List<IssueChangeDto> getCommentsForIssueKey(String issueKey) {
if (commentsByIssueKey.containsKey(issueKey)) {
return commentsByIssueKey.get(issueKey);
}
return null;
}
@CheckForNull
List<String> getActionsForIssueKey(String issueKey) {
if (actionsByIssueKey.containsKey(issueKey)) {
return actionsByIssueKey.get(issueKey);
}
return null;
}
@CheckForNull
List<Transition> getTransitionsForIssueKey(String issueKey) {
if (transitionsByIssueKey.containsKey(issueKey)) {
return transitionsByIssueKey.get(issueKey);
}
return null;
}
void addUsers(@Nullable List<UserDto> users) {
if (users != null) {
users.forEach(u -> usersByUuid.put(u.getUuid(), u));
}
}
public void addRules(@Nullable List<RuleDto> rules) {
if (rules != null) {
this.rules.addAll(rules);
}
}
public void setComments(@Nullable List<IssueChangeDto> comments) {
for (IssueChangeDto comment : comments) {
commentsByIssueKey.put(comment.getIssueKey(), comment);
}
}
public void addComponents(@Nullable Collection<ComponentDto> dtos) {
if (dtos != null) {
for (ComponentDto dto : dtos) {
componentsByUuid.put(dto.uuid(), dto);
}
}
}
public void addBranches(List<BranchDto> branchDtos) {
for (BranchDto branch : branchDtos) {
branchesByUuid.put(branch.getUuid(), branch);
}
}
public BranchDto getBranch(String branchUuid) {
return branchesByUuid.get(branchUuid);
}
public void addProjects(List<ProjectDto> projectDtos) {
for (ProjectDto projectDto : projectDtos) {
projectsByUuid.put(projectDto.getUuid(), projectDto);
}
}
public ProjectDto getProject(String projectUuid) {
return projectsByUuid.get(projectUuid);
}
void addActions(String issueKey, Iterable<String> actions) {
actionsByIssueKey.putAll(issueKey, actions);
}
void addTransitions(String issueKey, List<Transition> transitions) {
transitionsByIssueKey.putAll(issueKey, transitions);
}
void addUpdatableComment(String commentKey) {
updatableComments.add(commentKey);
}
boolean isUpdatableComment(String commentKey) {
return updatableComments.contains(commentKey);
}
@CheckForNull
Long getEffortTotal() {
return effortTotal;
}
void setEffortTotal(@Nullable Long effortTotal) {
this.effortTotal = effortTotal;
}
@CheckForNull
UserDto getUserByUuid(@Nullable String userUuid) {
return usersByUuid.get(userUuid);
}
}
| 5,839 | 28.2 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseFormat.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
import org.sonar.api.utils.Paging;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.markdown.Markdown;
import org.sonar.server.es.Facets;
import org.sonar.server.issue.TextRangeResponseFormatter;
import org.sonar.server.issue.index.IssueScope;
import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.ws.MessageFormattingUtils;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Common.Comment;
import org.sonarqube.ws.Common.User;
import org.sonarqube.ws.Issues;
import org.sonarqube.ws.Issues.Actions;
import org.sonarqube.ws.Issues.Comments;
import org.sonarqube.ws.Issues.Component;
import org.sonarqube.ws.Issues.Issue;
import org.sonarqube.ws.Issues.Operation;
import org.sonarqube.ws.Issues.SearchWsResponse;
import org.sonarqube.ws.Issues.Transitions;
import org.sonarqube.ws.Issues.Users;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.base.Strings.nullToEmpty;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE;
import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX;
import static org.sonar.server.issue.index.IssueIndex.FACET_ASSIGNED_TO_ME;
import static org.sonar.server.issue.index.IssueIndex.FACET_PROJECTS;
import static org.sonar.server.issue.ws.SearchAdditionalField.ACTIONS;
import static org.sonar.server.issue.ws.SearchAdditionalField.ALL_ADDITIONAL_FIELDS;
import static org.sonar.server.issue.ws.SearchAdditionalField.COMMENTS;
import static org.sonar.server.issue.ws.SearchAdditionalField.RULE_DESCRIPTION_CONTEXT_KEY;
import static org.sonar.server.issue.ws.SearchAdditionalField.TRANSITIONS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNEES;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RULES;
public class SearchResponseFormat {
private final Durations durations;
private final Languages languages;
private final TextRangeResponseFormatter textRangeFormatter;
private final UserResponseFormatter userFormatter;
public SearchResponseFormat(Durations durations, Languages languages, TextRangeResponseFormatter textRangeFormatter, UserResponseFormatter userFormatter) {
this.durations = durations;
this.languages = languages;
this.textRangeFormatter = textRangeFormatter;
this.userFormatter = userFormatter;
}
SearchWsResponse formatSearch(Set<SearchAdditionalField> fields, SearchResponseData data, Paging paging, Facets facets) {
SearchWsResponse.Builder response = SearchWsResponse.newBuilder();
formatPaging(paging, response);
ofNullable(data.getEffortTotal()).ifPresent(response::setEffortTotal);
response.addAllIssues(createIssues(fields, data));
response.addAllComponents(formatComponents(data));
formatFacets(data, facets, response);
if (fields.contains(SearchAdditionalField.RULES)) {
response.setRules(formatRules(data));
}
if (fields.contains(SearchAdditionalField.USERS)) {
response.setUsers(formatUsers(data));
}
if (fields.contains(SearchAdditionalField.LANGUAGES)) {
response.setLanguages(formatLanguages());
}
return response.build();
}
Operation formatOperation(SearchResponseData data) {
Operation.Builder response = Operation.newBuilder();
if (data.getIssues().size() == 1) {
IssueDto dto = data.getIssues().get(0);
response.setIssue(createIssue(ALL_ADDITIONAL_FIELDS, data, dto));
}
response.addAllComponents(formatComponents(data));
response.addAllRules(formatRules(data).getRulesList());
response.addAllUsers(formatUsers(data).getUsersList());
return response.build();
}
private static void formatPaging(Paging paging, SearchWsResponse.Builder response) {
response.setP(paging.pageIndex());
response.setPs(paging.pageSize());
response.setTotal(paging.total());
response.setPaging(formatPaging(paging));
}
private static Common.Paging.Builder formatPaging(Paging paging) {
return Common.Paging.newBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total());
}
private List<Issues.Issue> createIssues(Collection<SearchAdditionalField> fields, SearchResponseData data) {
return data.getIssues().stream()
.map(dto -> createIssue(fields, data, dto))
.toList();
}
private Issue createIssue(Collection<SearchAdditionalField> fields, SearchResponseData data, IssueDto dto) {
Issue.Builder issueBuilder = Issue.newBuilder();
addMandatoryFieldsToIssueBuilder(issueBuilder, dto, data);
addAdditionalFieldsToIssueBuilder(fields, data, dto, issueBuilder);
return issueBuilder.build();
}
private void addMandatoryFieldsToIssueBuilder(Issue.Builder issueBuilder, IssueDto dto, SearchResponseData data) {
issueBuilder.setKey(dto.getKey());
issueBuilder.setType(Common.RuleType.forNumber(dto.getType()));
ComponentDto component = data.getComponentByUuid(dto.getComponentUuid());
issueBuilder.setComponent(component.getKey());
setBranchOrPr(component, issueBuilder, data);
ComponentDto branch = data.getComponentByUuid(dto.getProjectUuid());
if (branch != null) {
issueBuilder.setProject(branch.getKey());
}
issueBuilder.setRule(dto.getRuleKey().toString());
if (dto.isExternal()) {
issueBuilder.setExternalRuleEngine(engineNameFrom(dto.getRuleKey()));
}
if (dto.getType() != RuleType.SECURITY_HOTSPOT.getDbConstant()) {
issueBuilder.setSeverity(Common.Severity.valueOf(dto.getSeverity()));
}
ofNullable(data.getUserByUuid(dto.getAssigneeUuid())).ifPresent(assignee -> issueBuilder.setAssignee(assignee.getLogin()));
ofNullable(emptyToNull(dto.getResolution())).ifPresent(issueBuilder::setResolution);
issueBuilder.setStatus(dto.getStatus());
issueBuilder.setMessage(nullToEmpty(dto.getMessage()));
issueBuilder.addAllMessageFormattings(MessageFormattingUtils.dbMessageFormattingToWs(dto.parseMessageFormattings()));
issueBuilder.addAllTags(dto.getTags());
issueBuilder.addAllCodeVariants(dto.getCodeVariants());
Long effort = dto.getEffort();
if (effort != null) {
String effortValue = durations.encode(Duration.create(effort));
issueBuilder.setDebt(effortValue);
issueBuilder.setEffort(effortValue);
}
ofNullable(dto.getLine()).ifPresent(issueBuilder::setLine);
ofNullable(emptyToNull(dto.getChecksum())).ifPresent(issueBuilder::setHash);
completeIssueLocations(dto, issueBuilder, data);
issueBuilder.setAuthor(nullToEmpty(dto.getAuthorLogin()));
ofNullable(dto.getIssueCreationDate()).map(DateUtils::formatDateTime).ifPresent(issueBuilder::setCreationDate);
ofNullable(dto.getIssueUpdateDate()).map(DateUtils::formatDateTime).ifPresent(issueBuilder::setUpdateDate);
ofNullable(dto.getIssueCloseDate()).map(DateUtils::formatDateTime).ifPresent(issueBuilder::setCloseDate);
Optional.of(dto.isQuickFixAvailable())
.ifPresentOrElse(issueBuilder::setQuickFixAvailable, () -> issueBuilder.setQuickFixAvailable(false));
issueBuilder.setScope(UNIT_TEST_FILE.equals(component.qualifier()) ? IssueScope.TEST.name() : IssueScope.MAIN.name());
}
private static void addAdditionalFieldsToIssueBuilder(Collection<SearchAdditionalField> fields, SearchResponseData data, IssueDto dto, Issue.Builder issueBuilder) {
if (fields.contains(ACTIONS)) {
issueBuilder.setActions(createIssueActions(data, dto));
}
if (fields.contains(TRANSITIONS)) {
issueBuilder.setTransitions(createIssueTransition(data, dto));
}
if (fields.contains(COMMENTS)) {
issueBuilder.setComments(createIssueComments(data, dto));
}
if (fields.contains(RULE_DESCRIPTION_CONTEXT_KEY)) {
dto.getOptionalRuleDescriptionContextKey().ifPresent(issueBuilder::setRuleDescriptionContextKey);
}
}
private static String engineNameFrom(RuleKey ruleKey) {
checkState(ruleKey.repository().startsWith(EXTERNAL_RULE_REPO_PREFIX));
return ruleKey.repository().replace(EXTERNAL_RULE_REPO_PREFIX, "");
}
private void completeIssueLocations(IssueDto dto, Issue.Builder issueBuilder, SearchResponseData data) {
DbIssues.Locations locations = dto.parseLocations();
if (locations == null) {
return;
}
textRangeFormatter.formatTextRange(locations, issueBuilder::setTextRange);
issueBuilder.addAllFlows(textRangeFormatter.formatFlows(locations, issueBuilder.getComponent(), data.getComponentsByUuid()));
}
private static Transitions createIssueTransition(SearchResponseData data, IssueDto dto) {
Transitions.Builder wsTransitions = Transitions.newBuilder();
List<Transition> transitions = data.getTransitionsForIssueKey(dto.getKey());
if (transitions != null) {
for (Transition transition : transitions) {
wsTransitions.addTransitions(transition.key());
}
}
return wsTransitions.build();
}
private static Actions createIssueActions(SearchResponseData data, IssueDto dto) {
Actions.Builder wsActions = Actions.newBuilder();
List<String> actions = data.getActionsForIssueKey(dto.getKey());
if (actions != null) {
wsActions.addAllActions(actions);
}
return wsActions.build();
}
private static Comments createIssueComments(SearchResponseData data, IssueDto dto) {
Comments.Builder wsComments = Comments.newBuilder();
List<IssueChangeDto> comments = data.getCommentsForIssueKey(dto.getKey());
if (comments != null) {
Comment.Builder wsComment = Comment.newBuilder();
for (IssueChangeDto comment : comments) {
String markdown = comment.getChangeData();
wsComment
.clear()
.setKey(comment.getKey())
.setUpdatable(data.isUpdatableComment(comment.getKey()))
.setCreatedAt(DateUtils.formatDateTime(new Date(comment.getIssueChangeCreationDate())));
ofNullable(data.getUserByUuid(comment.getUserUuid())).ifPresent(user -> wsComment.setLogin(user.getLogin()));
if (markdown != null) {
wsComment
.setHtmlText(Markdown.convertToHtml(markdown))
.setMarkdown(markdown);
}
wsComments.addComments(wsComment);
}
}
return wsComments.build();
}
private Common.Rules.Builder formatRules(SearchResponseData data) {
Common.Rules.Builder wsRules = Common.Rules.newBuilder();
List<RuleDto> rules = firstNonNull(data.getRules(), emptyList());
for (RuleDto rule : rules) {
wsRules.addRules(formatRule(rule));
}
return wsRules;
}
private Common.Rule.Builder formatRule(RuleDto rule) {
Common.Rule.Builder builder = Common.Rule.newBuilder()
.setKey(rule.getKey().toString())
.setName(nullToEmpty(rule.getName()))
.setStatus(Common.RuleStatus.valueOf(rule.getStatus().name()));
builder.setLang(nullToEmpty(rule.getLanguage()));
Language lang = languages.get(rule.getLanguage());
if (lang != null) {
builder.setLangName(lang.getName());
}
return builder;
}
private static List<Issues.Component> formatComponents(SearchResponseData data) {
Collection<ComponentDto> components = data.getComponents();
List<Issues.Component> result = new ArrayList<>();
for (ComponentDto dto : components) {
Component.Builder builder = Component.newBuilder()
.setKey(dto.getKey())
.setQualifier(dto.qualifier())
.setName(nullToEmpty(dto.name()))
.setLongName(nullToEmpty(dto.longName()))
.setEnabled(dto.isEnabled());
setBranchOrPr(dto, builder, data);
ofNullable(emptyToNull(dto.path())).ifPresent(builder::setPath);
result.add(builder.build());
}
return result;
}
private static void setBranchOrPr(ComponentDto componentDto, Component.Builder builder, SearchResponseData data) {
String branchUuid = componentDto.getCopyComponentUuid() != null ? componentDto.getCopyComponentUuid() : componentDto.branchUuid();
BranchDto branchDto = data.getBranch(branchUuid);
if (branchDto.isMain()) {
return;
}
if (branchDto.getBranchType() == BranchType.BRANCH) {
builder.setBranch(branchDto.getKey());
} else if (branchDto.getBranchType() == BranchType.PULL_REQUEST) {
builder.setPullRequest(branchDto.getKey());
}
}
private static void setBranchOrPr(ComponentDto componentDto, Issue.Builder builder, SearchResponseData data) {
String branchUuid = componentDto.getCopyComponentUuid() != null ? componentDto.getCopyComponentUuid() : componentDto.branchUuid();
BranchDto branchDto = data.getBranch(branchUuid);
if (branchDto.isMain()) {
return;
}
if (branchDto.getBranchType() == BranchType.BRANCH) {
builder.setBranch(branchDto.getKey());
} else if (branchDto.getBranchType() == BranchType.PULL_REQUEST) {
builder.setPullRequest(branchDto.getKey());
}
}
private Users.Builder formatUsers(SearchResponseData data) {
Users.Builder wsUsers = Users.newBuilder();
List<UserDto> users = data.getUsers();
if (users != null) {
User.Builder builder = User.newBuilder();
for (UserDto user : users) {
wsUsers.addUsers(userFormatter.formatUser(builder, user));
}
}
return wsUsers;
}
private Issues.Languages.Builder formatLanguages() {
Issues.Languages.Builder wsLangs = Issues.Languages.newBuilder();
Issues.Language.Builder wsLang = Issues.Language.newBuilder();
for (Language lang : languages.all()) {
wsLang
.clear()
.setKey(lang.getKey())
.setName(lang.getName());
wsLangs.addLanguages(wsLang);
}
return wsLangs;
}
private static void formatFacets(SearchResponseData data, Facets facets, SearchWsResponse.Builder wsSearch) {
Common.Facets.Builder wsFacets = Common.Facets.newBuilder();
SearchAction.SUPPORTED_FACETS.stream()
.filter(f -> !f.equals(FACET_PROJECTS))
.filter(f -> !f.equals(FACET_ASSIGNED_TO_ME))
.filter(f -> !f.equals(PARAM_ASSIGNEES))
.filter(f -> !f.equals(PARAM_RULES))
.forEach(f -> computeStandardFacet(wsFacets, facets, f));
computeAssigneesFacet(wsFacets, facets, data);
computeAssignedToMeFacet(wsFacets, facets, data);
computeRulesFacet(wsFacets, facets, data);
computeProjectsFacet(wsFacets, facets, data);
wsSearch.setFacets(wsFacets.build());
}
private static void computeStandardFacet(Common.Facets.Builder wsFacets, Facets facets, String facetKey) {
LinkedHashMap<String, Long> facet = facets.get(facetKey);
if (facet == null) {
return;
}
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(facetKey);
facet.forEach((value, count) -> wsFacet.addValuesBuilder()
.setVal(value)
.setCount(count)
.build());
wsFacet.build();
}
private static void computeAssigneesFacet(Common.Facets.Builder wsFacets, Facets facets, SearchResponseData data) {
LinkedHashMap<String, Long> facet = facets.get(PARAM_ASSIGNEES);
if (facet == null) {
return;
}
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(PARAM_ASSIGNEES);
facet
.forEach((userUuid, count) -> {
UserDto user = data.getUserByUuid(userUuid);
wsFacet.addValuesBuilder()
.setVal(user == null ? "" : user.getLogin())
.setCount(count)
.build();
});
wsFacet.build();
}
private static void computeAssignedToMeFacet(Common.Facets.Builder wsFacets, Facets facets, SearchResponseData data) {
LinkedHashMap<String, Long> facet = facets.get(FACET_ASSIGNED_TO_ME);
if (facet == null) {
return;
}
Map.Entry<String, Long> entry = facet.entrySet().iterator().next();
UserDto user = data.getUserByUuid(entry.getKey());
checkState(user != null, "User with uuid '%s' has not been found", entry.getKey());
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(FACET_ASSIGNED_TO_ME);
wsFacet.addValuesBuilder()
.setVal(user.getLogin())
.setCount(entry.getValue())
.build();
}
private static void computeRulesFacet(Common.Facets.Builder wsFacets, Facets facets, SearchResponseData data) {
LinkedHashMap<String, Long> facet = facets.get(PARAM_RULES);
if (facet == null) {
return;
}
Map<String, RuleKey> ruleUuidsByRuleKeys = data.getRules().stream().collect(Collectors.toMap(RuleDto::getUuid, RuleDto::getKey));
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(PARAM_RULES);
facet.forEach((ruleUuid, count) -> wsFacet.addValuesBuilder()
.setVal(ruleUuidsByRuleKeys.get(ruleUuid).toString())
.setCount(count)
.build());
wsFacet.build();
}
private static void computeProjectsFacet(Common.Facets.Builder wsFacets, Facets facets, SearchResponseData datas) {
LinkedHashMap<String, Long> facet = facets.get(FACET_PROJECTS);
if (facet == null) {
return;
}
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(FACET_PROJECTS);
facet.forEach((uuid, count) -> {
ProjectDto project = datas.getProject(uuid);
requireNonNull(project, format("Project has not been found for uuid '%s'", uuid));
wsFacet.addValuesBuilder()
.setVal(project.getKey())
.setCount(count)
.build();
});
wsFacet.build();
}
}
| 19,456 | 40.309979 | 166 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SearchResponseLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.collect.ImmutableSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.rules.RuleType;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.Facets;
import org.sonar.server.issue.TransitionService;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.issue.IssuesWsParameters;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Sets.difference;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Stream.concat;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
import static org.sonar.server.issue.AssignAction.ASSIGN_KEY;
import static org.sonar.server.issue.CommentAction.COMMENT_KEY;
import static org.sonar.server.issue.SetSeverityAction.SET_SEVERITY_KEY;
import static org.sonar.server.issue.SetTypeAction.SET_TYPE_KEY;
import static org.sonar.server.issue.ws.SearchAdditionalField.ACTIONS;
import static org.sonar.server.issue.ws.SearchAdditionalField.COMMENTS;
import static org.sonar.server.issue.ws.SearchAdditionalField.TRANSITIONS;
/**
* Loads all the information required for the response of api/issues/search.
*/
public class SearchResponseLoader {
private final UserSession userSession;
private final DbClient dbClient;
private final TransitionService transitionService;
public SearchResponseLoader(UserSession userSession, DbClient dbClient, TransitionService transitionService) {
this.userSession = userSession;
this.dbClient = dbClient;
this.transitionService = transitionService;
}
/**
* The issue keys are given by the multi-criteria search in Elasticsearch index.
* <p>
* It will only retrieve from DB data which is not already provided by the specified preloaded {@link SearchResponseData}.<br/>
* The returned {@link SearchResponseData} is <strong>not</strong> the one specified as argument.
* </p>
*/
public SearchResponseData load(SearchResponseData preloadedResponseData, Collector collector, Set<SearchAdditionalField> fields, @Nullable Facets facets) {
try (DbSession dbSession = dbClient.openSession(false)) {
SearchResponseData result = new SearchResponseData(loadIssues(preloadedResponseData, collector, dbSession));
collector.collect(result.getIssues());
loadRules(preloadedResponseData, collector, dbSession, result);
// order is important - loading of comments complete the list of users: loadComments() is before loadUsers()
loadComments(collector, dbSession, fields, result);
loadUsers(preloadedResponseData, collector, dbSession, result);
loadComponents(preloadedResponseData, collector, dbSession, result);
// for all loaded components in result we "join" branches to know to which branch components belong
loadBranches(dbSession, result);
loadProjects(collector, dbSession, result);
loadActionsAndTransitions(result, fields);
completeTotalEffortFromFacet(facets, result);
return result;
}
}
private List<IssueDto> loadIssues(SearchResponseData preloadedResponseData, Collector collector, DbSession dbSession) {
List<IssueDto> preloadedIssues = preloadedResponseData.getIssues();
Set<String> preloadedIssueKeys = preloadedIssues.stream().map(IssueDto::getKey).collect(Collectors.toSet());
ImmutableSet<String> issueKeys = ImmutableSet.copyOf(collector.getIssueKeys());
Set<String> issueKeysToLoad = copyOf(difference(issueKeys, preloadedIssueKeys));
if (issueKeysToLoad.isEmpty()) {
return issueKeys.stream()
.map(new KeyToIssueFunction(preloadedIssues)).filter(Objects::nonNull)
.toList();
}
List<IssueDto> loadedIssues = dbClient.issueDao().selectByKeys(dbSession, issueKeysToLoad);
List<IssueDto> unorderedIssues = concat(preloadedIssues.stream(), loadedIssues.stream())
.toList();
return issueKeys.stream()
.map(new KeyToIssueFunction(unorderedIssues)).filter(Objects::nonNull)
.toList();
}
private void loadUsers(SearchResponseData preloadedResponseData, Collector collector, DbSession dbSession, SearchResponseData result) {
Set<String> usersUuidToLoad = collector.getUserUuids();
List<UserDto> preloadedUsers = firstNonNull(preloadedResponseData.getUsers(), emptyList());
result.addUsers(preloadedUsers);
preloadedUsers.forEach(userDto -> usersUuidToLoad.remove(userDto.getUuid()));
result.addUsers(dbClient.userDao().selectByUuids(dbSession, usersUuidToLoad));
}
private void loadComponents(SearchResponseData preloadedResponseData, Collector collector, DbSession dbSession, SearchResponseData result) {
Collection<ComponentDto> preloadedComponents = preloadedResponseData.getComponents();
Set<String> preloadedComponentUuids = preloadedComponents.stream().map(ComponentDto::uuid).collect(Collectors.toSet());
Set<String> componentUuidsToLoad = copyOf(difference(collector.getComponentUuids(), preloadedComponentUuids));
result.addComponents(preloadedComponents);
if (!componentUuidsToLoad.isEmpty()) {
result.addComponents(dbClient.componentDao().selectByUuids(dbSession, componentUuidsToLoad));
}
// always load components and branches, because some issue fields still relate to component ids/keys.
// They should be dropped but are kept for backward-compatibility (see SearchResponseFormat)
result.addComponents(dbClient.componentDao().selectSubProjectsByComponentUuids(dbSession, collector.getComponentUuids()));
loadBranchComponents(collector, dbSession, result);
}
private void loadProjects(Collector collector, DbSession dbSession, SearchResponseData result) {
List<ProjectDto> projects = dbClient.projectDao().selectByUuids(dbSession, collector.getProjectUuids());
result.addProjects(projects);
}
private void loadBranches(DbSession dbSession, SearchResponseData result) {
Set<String> branchUuids = result.getComponents().stream()
.map(c -> c.getCopyComponentUuid() != null ? c.getCopyComponentUuid() : c.branchUuid())
.collect(Collectors.toSet());
List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, branchUuids);
result.addBranches(branchDtos);
}
private void loadBranchComponents(Collector collector, DbSession dbSession, SearchResponseData result) {
Collection<ComponentDto> loadedComponents = result.getComponents();
for (ComponentDto component : loadedComponents) {
collector.addBranchUuid(component.branchUuid());
}
Set<String> loadedBranchUuids = loadedComponents.stream().filter(cpt -> cpt.uuid().equals(cpt.branchUuid())).map(ComponentDto::uuid).collect(Collectors.toSet());
Set<String> branchUuidsToLoad = copyOf(difference(collector.getBranchUuids(), loadedBranchUuids));
if (!branchUuidsToLoad.isEmpty()) {
List<ComponentDto> branchComponents = dbClient.componentDao().selectByUuids(dbSession, collector.getBranchUuids());
result.addComponents(branchComponents);
}
}
private void loadRules(SearchResponseData preloadedResponseData, Collector collector, DbSession dbSession, SearchResponseData result) {
List<RuleDto> preloadedRules = firstNonNull(preloadedResponseData.getRules(), emptyList());
result.addRules(preloadedRules);
Set<String> ruleUuidsToLoad = collector.getRuleUuids();
preloadedRules.stream().map(RuleDto::getUuid).toList()
.forEach(ruleUuidsToLoad::remove);
List<RuleDto> rules = dbClient.ruleDao().selectByUuids(dbSession, ruleUuidsToLoad);
result.addRules(rules);
updateNamesOfAdHocRules(result.getRules());
}
private static void updateNamesOfAdHocRules(List<RuleDto> rules) {
rules.stream()
.filter(RuleDto::isAdHoc)
.filter(r -> r.getAdHocName() != null)
.forEach(r -> r.setName(r.getAdHocName()));
}
private void loadComments(Collector collector, DbSession dbSession, Set<SearchAdditionalField> fields, SearchResponseData result) {
if (fields.contains(COMMENTS)) {
List<IssueChangeDto> comments = dbClient.issueChangeDao().selectByTypeAndIssueKeys(dbSession, collector.getIssueKeys(), IssueChangeDto.TYPE_COMMENT);
result.setComments(comments);
comments.stream()
.filter(c -> c.getUserUuid() != null)
.forEach(comment -> loadComment(collector, result, comment));
}
}
private void loadComment(Collector collector, SearchResponseData result, IssueChangeDto comment) {
collector.addUserUuids(singletonList(comment.getUserUuid()));
if (canEditOrDelete(comment)) {
result.addUpdatableComment(comment.getKey());
}
}
private boolean canEditOrDelete(IssueChangeDto dto) {
return userSession.isLoggedIn() && requireNonNull(userSession.getUuid(), "User uuid should not be null").equals(dto.getUserUuid());
}
private void loadActionsAndTransitions(SearchResponseData result, Set<SearchAdditionalField> fields) {
if (fields.contains(ACTIONS) || fields.contains(TRANSITIONS)) {
Map<String, ComponentDto> componentsByProjectUuid = result.getComponents()
.stream()
.filter(ComponentDto::isRootProject)
.collect(Collectors.toMap(ComponentDto::branchUuid, Function.identity()));
for (IssueDto issueDto : result.getIssues()) {
// so that IssueDto can be used.
if (fields.contains(ACTIONS)) {
ComponentDto branch = componentsByProjectUuid.get(issueDto.getProjectUuid());
result.addActions(issueDto.getKey(), listAvailableActions(issueDto, branch));
}
if (fields.contains(TRANSITIONS) && !issueDto.isExternal()) {
// TODO workflow and action engines must not depend on org.sonar.api.issue.Issue but on a generic interface
DefaultIssue issue = issueDto.toDefaultIssue();
result.addTransitions(issue.key(), transitionService.listTransitions(issue));
}
}
}
}
private Set<String> listAvailableActions(IssueDto issue, ComponentDto branch) {
Set<String> availableActions = newHashSet();
String login = userSession.getLogin();
if (login == null) {
return Collections.emptySet();
}
RuleType ruleType = RuleType.valueOf(issue.getType());
availableActions.add(COMMENT_KEY);
availableActions.add("set_tags");
if (issue.getResolution() != null) {
return availableActions;
}
availableActions.add(ASSIGN_KEY);
if (ruleType != RuleType.SECURITY_HOTSPOT && userSession.hasComponentPermission(ISSUE_ADMIN, branch)) {
availableActions.add(SET_TYPE_KEY);
availableActions.add(SET_SEVERITY_KEY);
}
return availableActions;
}
private static void completeTotalEffortFromFacet(@Nullable Facets facets, SearchResponseData result) {
if (facets != null) {
Map<String, Long> effortFacet = facets.get(IssuesWsParameters.FACET_MODE_EFFORT);
if (effortFacet != null) {
result.setEffortTotal(effortFacet.get(Facets.TOTAL));
}
}
}
/**
* Collects the keys of all the data to be loaded (users, rules, ...)
*/
public static class Collector {
private final Set<String> componentUuids = new HashSet<>();
private final Set<String> branchUuids = new HashSet<>();
private final Set<String> projectUuids = new HashSet<>();
private final List<String> issueKeys;
private final Set<String> ruleUuids = new HashSet<>();
private final Set<String> userUuids = new HashSet<>();
public Collector(List<String> issueKeys) {
this.issueKeys = issueKeys;
}
void collect(List<IssueDto> issues) {
for (IssueDto issue : issues) {
componentUuids.add(issue.getComponentUuid());
branchUuids.add(issue.getProjectUuid());
Optional.ofNullable(issue.getRuleUuid()).ifPresent(ruleUuids::add);
String issueAssigneeUuid = issue.getAssigneeUuid();
if (issueAssigneeUuid != null) {
userUuids.add(issueAssigneeUuid);
}
collectComponentsFromIssueLocations(issue);
}
}
private void collectComponentsFromIssueLocations(IssueDto issue) {
DbIssues.Locations locations = issue.parseLocations();
if (locations != null) {
for (DbIssues.Flow flow : locations.getFlowList()) {
for (DbIssues.Location location : flow.getLocationList()) {
if (location.hasComponentId()) {
componentUuids.add(location.getComponentId());
}
}
}
}
}
void addProjectUuids(@Nullable Collection<String> uuids) {
if (uuids != null) {
this.projectUuids.addAll(uuids);
}
}
void addBranchUuid(String uuid) {
this.branchUuids.add(uuid);
}
void addRuleIds(@Nullable Collection<String> ruleUuids) {
if (ruleUuids != null) {
this.ruleUuids.addAll(ruleUuids);
}
}
void addUserUuids(@Nullable Collection<String> userUuids) {
if (userUuids != null) {
this.userUuids.addAll(userUuids);
}
}
public Set<String> getProjectUuids() {
return projectUuids;
}
public List<String> getIssueKeys() {
return issueKeys;
}
public Set<String> getComponentUuids() {
return componentUuids;
}
public Set<String> getBranchUuids() {
return branchUuids;
}
public Set<String> getRuleUuids() {
return ruleUuids;
}
Set<String> getUserUuids() {
return userUuids;
}
}
private static class KeyToIssueFunction implements Function<String, IssueDto> {
private final Map<String, IssueDto> map = new HashMap<>();
private KeyToIssueFunction(Collection<IssueDto> unordered) {
for (IssueDto dto : unordered) {
map.put(dto.getKey(), dto);
}
}
@Nullable
@Override
public IssueDto apply(String issueKey) {
return map.get(issueKey);
}
}
}
| 15,593 | 40.253968 | 165 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SetSeverityAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Date;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.pushapi.issues.IssueChangeEventService;
import org.sonar.server.user.UserSession;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_SET_SEVERITY;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SEVERITY;
public class SetSeverityAction implements IssuesWsAction {
private final UserSession userSession;
private final DbClient dbClient;
private final IssueChangeEventService issueChangeEventService;
private final IssueFinder issueFinder;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final OperationResponseWriter responseWriter;
public SetSeverityAction(UserSession userSession, DbClient dbClient, IssueChangeEventService issueChangeEventService,
IssueFinder issueFinder, IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater,
OperationResponseWriter responseWriter) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueChangeEventService = issueChangeEventService;
this.issueFinder = issueFinder;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_SET_SEVERITY)
.setDescription("Change severity.<br/>" +
"Requires the following permissions:" +
"<ul>" +
" <li>'Authentication'</li>" +
" <li>'Browse' rights on project of the specified issue</li>" +
" <li>'Administer Issues' rights on project of the specified issue</li>" +
"</ul>")
.setSince("3.6")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "set_severity-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_SEVERITY)
.setDescription("New severity")
.setRequired(true)
.setPossibleValues(Severity.ALL);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
String issueKey = request.mandatoryParam(PARAM_ISSUE);
String severity = request.mandatoryParam(PARAM_SEVERITY);
try (DbSession session = dbClient.openSession(false)) {
SearchResponseData preloadedSearchResponseData = setType(session, issueKey, severity);
responseWriter.write(issueKey, preloadedSearchResponseData, request, response);
}
}
private SearchResponseData setType(DbSession session, String issueKey, String severity) {
IssueDto issueDto = issueFinder.getByKey(session, issueKey);
DefaultIssue issue = issueDto.toDefaultIssue();
userSession.checkComponentUuidPermission(ISSUE_ADMIN, issue.projectUuid());
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(), userSession.getUuid()).withRefreshMeasures().build();
if (issueFieldsSetter.setManualSeverity(issue, severity, context)) {
BranchDto branch = issueUpdater.getBranch(session, issue);
SearchResponseData response = issueUpdater.saveIssueAndPreloadSearchResponseData(session, issue, context, branch);
if (branch.getBranchType().equals(BRANCH) && response.getComponentByUuid(issue.projectUuid()) != null) {
issueChangeEventService.distributeIssueChangeEvent(issue, severity, null, null,
branch, response.getComponentByUuid(issue.projectUuid()).getKey());
}
return response;
}
return new SearchResponseData(issueDto);
}
}
| 5,837 | 43.907692 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SetTagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.base.MoreObjects;
import com.google.common.io.Resources;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.user.UserSession;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_SET_TAGS;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TAGS;
/**
* Set tags on an issue
*/
public class SetTagsAction implements IssuesWsAction {
private final UserSession userSession;
private final DbClient dbClient;
private final IssueFinder issueFinder;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final OperationResponseWriter responseWriter;
public SetTagsAction(UserSession userSession, DbClient dbClient, IssueFinder issueFinder, IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater,
OperationResponseWriter responseWriter) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueFinder = issueFinder;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.responseWriter = responseWriter;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction(ACTION_SET_TAGS)
.setPost(true)
.setSince("5.1")
.setDescription("Set tags on an issue. <br/>" +
"Requires authentication and Browse permission on project")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."),
new Change("6.4", "response contains issue information instead of list of tags"))
.setResponseExample(Resources.getResource(this.getClass(), "set_tags-example.json"))
.setHandler(this);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setSince("6.3")
.setExampleValue(Uuids.UUID_EXAMPLE_01)
.setRequired(true);
action.createParam(PARAM_TAGS)
.setDescription("Comma-separated list of tags. All tags are removed if parameter is empty or not set.")
.setExampleValue("security,cwe,misra-c");
}
@Override
public void handle(Request request, Response response) throws Exception {
String key = request.mandatoryParam(PARAM_ISSUE);
List<String> tags = MoreObjects.firstNonNull(request.paramAsStrings(PARAM_TAGS), Collections.emptyList());
SearchResponseData preloadedSearchResponseData = setTags(key, tags);
responseWriter.write(key, preloadedSearchResponseData, request, response);
}
private SearchResponseData setTags(String issueKey, List<String> tags) {
userSession.checkLoggedIn();
try (DbSession session = dbClient.openSession(false)) {
IssueDto issueDto = issueFinder.getByKey(session, issueKey);
DefaultIssue issue = issueDto.toDefaultIssue();
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(), userSession.getUuid()).build();
if (issueFieldsSetter.setTags(issue, tags, context)) {
return issueUpdater.saveIssueAndPreloadSearchResponseData(session, issue, context);
}
return new SearchResponseData(issueDto);
}
}
}
| 5,024 | 42.318966 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/SetTypeAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.Date;
import java.util.EnumSet;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueFinder;
import org.sonar.server.pushapi.issues.IssueChangeEventService;
import org.sonar.server.user.UserSession;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_SET_TYPE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUE;
import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TYPE;
public class SetTypeAction implements IssuesWsAction {
private static final EnumSet<RuleType> ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS = EnumSet.complementOf(EnumSet.of(RuleType.SECURITY_HOTSPOT));
private final UserSession userSession;
private final DbClient dbClient;
private final IssueChangeEventService issueChangeEventService;
private final IssueFinder issueFinder;
private final IssueFieldsSetter issueFieldsSetter;
private final IssueUpdater issueUpdater;
private final OperationResponseWriter responseWriter;
private final System2 system2;
public SetTypeAction(UserSession userSession, DbClient dbClient, IssueChangeEventService issueChangeEventService, IssueFinder issueFinder,
IssueFieldsSetter issueFieldsSetter, IssueUpdater issueUpdater, OperationResponseWriter responseWriter, System2 system2) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueChangeEventService = issueChangeEventService;
this.issueFinder = issueFinder;
this.issueFieldsSetter = issueFieldsSetter;
this.issueUpdater = issueUpdater;
this.responseWriter = responseWriter;
this.system2 = system2;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_SET_TYPE)
.setDescription("Change type of issue, for instance from 'code smell' to 'bug'.<br/>" +
"Requires the following permissions:" +
"<ul>" +
" <li>'Authentication'</li>" +
" <li>'Browse' rights on project of the specified issue</li>" +
" <li>'Administer Issues' rights on project of the specified issue</li>" +
"</ul>")
.setSince("5.5")
.setChangelog(
new Change("9.6", "Response field 'ruleDescriptionContextKey' added"),
new Change("8.8", "The response field components.uuid is removed"),
new Change("6.5", "the database ids of the components are removed from the response"),
new Change("6.5", "the response field components.uuid is deprecated. Use components.key instead."))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "set_type-example.json"))
.setPost(true);
action.createParam(PARAM_ISSUE)
.setDescription("Issue key")
.setRequired(true)
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_TYPE)
.setDescription("New type")
.setRequired(true)
.setPossibleValues(ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
String issueKey = request.mandatoryParam(PARAM_ISSUE);
RuleType ruleType = RuleType.valueOf(request.mandatoryParam(PARAM_TYPE));
try (DbSession session = dbClient.openSession(false)) {
SearchResponseData preloadedSearchResponseData = setType(session, issueKey, ruleType);
responseWriter.write(issueKey, preloadedSearchResponseData, request, response);
}
}
private SearchResponseData setType(DbSession session, String issueKey, RuleType ruleType) {
IssueDto issueDto = issueFinder.getByKey(session, issueKey);
DefaultIssue issue = issueDto.toDefaultIssue();
userSession.checkComponentUuidPermission(ISSUE_ADMIN, issue.projectUuid());
IssueChangeContext context = issueChangeContextByUserBuilder(new Date(system2.now()), userSession.getUuid()).withRefreshMeasures().build();
if (issueFieldsSetter.setType(issue, ruleType, context)) {
BranchDto branch = issueUpdater.getBranch(session, issue);
SearchResponseData response = issueUpdater.saveIssueAndPreloadSearchResponseData(session, issue, context, branch);
if (branch.getBranchType().equals(BRANCH) && response.getComponentByUuid(issue.projectUuid()) != null) {
issueChangeEventService.distributeIssueChangeEvent(issue, null, ruleType.name(), null, branch,
response.getComponentByUuid(issue.projectUuid()).getKey());
}
return response;
}
return new SearchResponseData(issueDto);
}
}
| 6,188 | 44.844444 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/TagsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import com.google.common.io.Resources;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.issue.index.IssueQuery;
import org.sonarqube.ws.Issues;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.server.issue.index.IssueQueryFactory.ISSUE_TYPE_NAMES;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* List issue tags matching a given query.
*
* @since 5.1
*/
public class TagsAction implements IssuesWsAction {
private static final String PARAM_PROJECT = "project";
private static final String PARAM_BRANCH = "branch";
private static final String PARAM_ALL = "all";
private final IssueIndex issueIndex;
private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
private final DbClient dbClient;
private final ComponentFinder componentFinder;
public TagsAction(IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, DbClient dbClient, ComponentFinder componentFinder) {
this.issueIndex = issueIndex;
this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
this.dbClient = dbClient;
this.componentFinder = componentFinder;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction("tags")
.setHandler(this)
.setSince("5.1")
.setDescription("List tags matching a given query")
.setResponseExample(Resources.getResource(getClass(), "tags-example.json"))
.setChangelog(new Change("7.4", "Result doesn't include rules tags anymore"),
new Change("9.4", "Max page size increased to 500"));
action.createSearchQuery("misra", "tags");
action.createPageSize(10, 500);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(false)
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setSince("7.4");
action.createParam(PARAM_BRANCH)
.setDescription("Branch key")
.setRequired(false)
.setExampleValue(KEY_BRANCH_EXAMPLE_001)
.setSince("9.2");
action.createParam(PARAM_ALL)
.setDescription("Indicator to search for all tags or only for tags in the main branch of a project")
.setRequired(false)
.setDefaultValue(Boolean.FALSE)
.setPossibleValues(Boolean.TRUE, Boolean.FALSE)
.setSince("9.2");
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
String projectKey = request.param(PARAM_PROJECT);
String branchKey = request.param(PARAM_BRANCH);
boolean all = request.mandatoryParamAsBoolean(PARAM_ALL);
checkIfAnyComponentsNeedIssueSync(dbSession, projectKey);
Optional<EntityDto> entity = getEntity(dbSession, projectKey);
Optional<BranchDto> branch = branchKey == null ? Optional.empty() : entity.flatMap(p -> dbClient.branchDao().selectByBranchKey(dbSession, p.getUuid(), branchKey));
List<String> tags = searchTags(entity.orElse(null), branch.orElse(null), request, all, dbSession);
Issues.TagsResponse.Builder tagsResponseBuilder = Issues.TagsResponse.newBuilder();
tags.forEach(tagsResponseBuilder::addTags);
writeProtobuf(tagsResponseBuilder.build(), request, response);
}
}
private Optional<EntityDto> getEntity(DbSession dbSession, @Nullable String entityKey) {
if (entityKey == null) {
return Optional.empty();
}
return Optional.of(componentFinder.getEntityByKey(dbSession, entityKey))
.filter(e -> !e.getQualifier().equals(Qualifiers.SUBVIEW));
}
private void checkIfAnyComponentsNeedIssueSync(DbSession session, @Nullable String projectKey) {
if (projectKey != null) {
issueIndexSyncProgressChecker.checkIfComponentNeedIssueSync(session, projectKey);
} else {
issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(session);
}
}
private List<String> searchTags(@Nullable EntityDto entity, @Nullable BranchDto branch, Request request, boolean all, DbSession dbSession) {
IssueQuery.Builder issueQueryBuilder = IssueQuery.builder()
.types(ISSUE_TYPE_NAMES);
if (entity != null) {
switch (entity.getQualifier()) {
case Qualifiers.PROJECT -> issueQueryBuilder.projectUuids(Set.of(entity.getUuid()));
case Qualifiers.VIEW, Qualifiers.APP -> issueQueryBuilder.viewUuids(Set.of(entity.getUuid()));
default -> throw new IllegalArgumentException(String.format("Entity of type '%s' is not supported", entity.getQualifier()));
}
if (branch != null && !branch.isMain()) {
issueQueryBuilder.branchUuid(branch.getUuid());
issueQueryBuilder.mainBranch(false);
} else if (Qualifiers.APP.equals(entity.getQualifier())) {
dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, entity.getUuid())
.ifPresent(b -> issueQueryBuilder.branchUuid(b.getUuid()));
}
}
if (all) {
issueQueryBuilder.mainBranch(null);
}
return issueIndex.searchTags(
issueQueryBuilder.build(),
request.param(TEXT_QUERY),
request.mandatoryParamAsInt(PAGE_SIZE));
}
}
| 6,900 | 41.079268 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/UserResponseFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolver;
import org.sonarqube.ws.Common;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.base.Strings.nullToEmpty;
import static java.util.Optional.ofNullable;
public class UserResponseFormatter {
private final AvatarResolver avatarResolver;
public UserResponseFormatter(AvatarResolver avatarResolver) {
this.avatarResolver = avatarResolver;
}
public Common.User formatUser(Common.User.Builder builder, UserDto user) {
builder
.clear()
.setLogin(user.getLogin())
.setName(nullToEmpty(user.getName()))
.setActive(user.isActive());
ofNullable(emptyToNull(user.getEmail())).ifPresent(email -> builder.setAvatar(avatarResolver.create(user)));
return builder.build();
}
}
| 1,713 | 35.468085 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.issue.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 39.25 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/ProtobufObjectGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws.pull;
import com.google.protobuf.AbstractMessageLite;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonarqube.ws.Issues;
public interface ProtobufObjectGenerator {
AbstractMessageLite generateTimestampMessage(long timestamp);
AbstractMessageLite generateIssueMessage(IssueDto issueDto, RuleDto ruleDto);
AbstractMessageLite generateClosedIssueMessage(String uuid);
default Issues.TextRange buildTextRange(DbIssues.Locations mainLocation) {
int startLine = mainLocation.getTextRange().getStartLine();
int endLine = mainLocation.getTextRange().getEndLine();
int startOffset = mainLocation.getTextRange().getStartOffset();
int endOffset = mainLocation.getTextRange().getEndOffset();
return Issues.TextRange.newBuilder()
.setHash(mainLocation.getChecksum())
.setStartLine(startLine)
.setEndLine(endLine)
.setStartLineOffset(startOffset)
.setEndLineOffset(endOffset).build();
}
}
| 1,892 | 37.632653 | 79 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/PullActionIssuesRetriever.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws.pull;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueQueryParams;
import static org.sonar.db.issue.IssueDao.DEFAULT_PAGE_SIZE;
public class PullActionIssuesRetriever {
private final DbClient dbClient;
private final IssueQueryParams issueQueryParams;
public PullActionIssuesRetriever(DbClient dbClient, IssueQueryParams queryParams) {
this.dbClient = dbClient;
this.issueQueryParams = queryParams;
}
public void processIssuesByBatch(DbSession dbSession, Set<String> issueKeysSnapshot, Consumer<List<IssueDto>> listConsumer, Predicate<? super IssueDto> filter) {
boolean hasMoreIssues = !issueKeysSnapshot.isEmpty();
long offset = 0;
List<IssueDto> issueDtos = new ArrayList<>();
while (hasMoreIssues) {
Set<String> page = paginate(issueKeysSnapshot, offset);
List<IssueDto> nextOpenIssues = nextOpenIssues(dbSession, page)
.stream()
.filter(filter)
.toList();
issueDtos.addAll(nextOpenIssues);
offset += page.size();
hasMoreIssues = offset < issueKeysSnapshot.size();
}
listConsumer.accept(issueDtos);
}
public List<String> retrieveClosedIssues(DbSession dbSession) {
return dbClient.issueDao().selectRecentlyClosedIssues(dbSession, issueQueryParams);
}
private List<IssueDto> nextOpenIssues(DbSession dbSession, Set<String> issueKeysSnapshot) {
return dbClient.issueDao().selectByBranch(dbSession, issueKeysSnapshot, issueQueryParams);
}
private static Set<String> paginate(Set<String> issueKeys, long offset) {
return issueKeys
.stream()
.skip(offset)
.limit(DEFAULT_PAGE_SIZE)
.collect(Collectors.toSet());
}
}
| 2,811 | 33.716049 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/PullActionProtobufObjectGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws.pull;
import org.sonar.api.server.ServerSide;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonarqube.ws.Common;
import static org.sonarqube.ws.Issues.IssueLite;
import static org.sonarqube.ws.Issues.IssuesPullQueryTimestamp;
import static org.sonarqube.ws.Issues.Location;
import static org.sonarqube.ws.Issues.TextRange;
@ServerSide
public class PullActionProtobufObjectGenerator implements ProtobufObjectGenerator {
@Override
public IssuesPullQueryTimestamp generateTimestampMessage(long timestamp) {
IssuesPullQueryTimestamp.Builder responseBuilder = IssuesPullQueryTimestamp.newBuilder();
responseBuilder.setQueryTimestamp(timestamp);
return responseBuilder.build();
}
@Override
public IssueLite generateIssueMessage(IssueDto issueDto, RuleDto ruleDto) {
IssueLite.Builder issueBuilder = IssueLite.newBuilder();
DbIssues.Locations mainLocation = issueDto.parseLocations();
Location.Builder locationBuilder = Location.newBuilder();
if (issueDto.getMessage() != null) {
locationBuilder.setMessage(issueDto.getMessage());
}
if (issueDto.getFilePath() != null) {
locationBuilder.setFilePath(issueDto.getFilePath());
}
if (mainLocation != null) {
TextRange textRange = buildTextRange(mainLocation);
locationBuilder.setTextRange(textRange);
}
Location location = locationBuilder.build();
issueBuilder.setKey(issueDto.getKey());
issueBuilder.setCreationDate(issueDto.getCreatedAt());
issueBuilder.setResolved(issueDto.getStatus().equals(org.sonar.api.issue.Issue.STATUS_RESOLVED));
issueBuilder.setRuleKey(issueDto.getRuleKey().toString());
if (issueDto.isManualSeverity() && issueDto.getSeverity() != null) {
issueBuilder.setUserSeverity(Common.Severity.valueOf(issueDto.getSeverity()));
}
issueBuilder.setType(Common.RuleType.forNumber(issueDto.getType()));
issueBuilder.setClosed(false);
issueBuilder.setMainLocation(location);
return issueBuilder.build();
}
@Override
public IssueLite generateClosedIssueMessage(String uuid) {
IssueLite.Builder issueBuilder = IssueLite.newBuilder();
issueBuilder.setKey(uuid);
issueBuilder.setClosed(true);
return issueBuilder.build();
}
}
| 3,192 | 37.46988 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/PullActionResponseWriter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws.pull;
import com.google.protobuf.AbstractMessageLite;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.rule.RuleDto;
@ServerSide
public class PullActionResponseWriter {
private final System2 system2;
private final ProtobufObjectGenerator protobufObjectGenerator;
public PullActionResponseWriter(System2 system2, ProtobufObjectGenerator protobufObjectGenerator) {
this.system2 = system2;
this.protobufObjectGenerator = protobufObjectGenerator;
}
public void appendTimestampToResponse(OutputStream outputStream) throws IOException {
AbstractMessageLite messageLite = protobufObjectGenerator.generateTimestampMessage(system2.now());
messageLite.writeDelimitedTo(outputStream);
}
public void appendIssuesToResponse(List<IssueDto> issueDtos, Map<String, RuleDto> ruleCache, OutputStream outputStream) {
try {
for (IssueDto issueDto : issueDtos) {
RuleDto ruleDto = ruleCache.get(issueDto.getRuleUuid());
AbstractMessageLite messageLite = protobufObjectGenerator.generateIssueMessage(issueDto, ruleDto);
messageLite.writeDelimitedTo(outputStream);
}
outputStream.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void appendClosedIssuesUuidsToResponse(List<String> closedIssuesUuids,
OutputStream outputStream) throws IOException {
for (String uuid : closedIssuesUuids) {
AbstractMessageLite messageLite = protobufObjectGenerator.generateClosedIssueMessage(uuid);
messageLite.writeDelimitedTo(outputStream);
}
}
}
| 2,625 | 36.514286 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/PullTaintActionProtobufObjectGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.ws.pull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.MessageFormattingUtils;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Issues;
import static org.sonar.db.protobuf.DbIssues.Locations;
import static org.sonarqube.ws.Issues.TaintVulnerabilityLite;
import static org.sonarqube.ws.Issues.TaintVulnerabilityPullQueryTimestamp;
@ServerSide
public class PullTaintActionProtobufObjectGenerator implements ProtobufObjectGenerator {
private final DbClient dbClient;
private final UserSession userSession;
private Map<String, ComponentDto> componentsMap;
public PullTaintActionProtobufObjectGenerator(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public TaintVulnerabilityPullQueryTimestamp generateTimestampMessage(long timestamp) {
refreshComponents();
TaintVulnerabilityPullQueryTimestamp.Builder responseBuilder = TaintVulnerabilityPullQueryTimestamp.newBuilder();
responseBuilder.setQueryTimestamp(timestamp);
return responseBuilder.build();
}
@Override
public TaintVulnerabilityLite generateIssueMessage(IssueDto issueDto, RuleDto ruleDto) {
TaintVulnerabilityLite.Builder taintBuilder = TaintVulnerabilityLite.newBuilder();
Locations locations = issueDto.parseLocations();
if (componentsMap == null) {
refreshComponents();
}
Issues.Location.Builder locationBuilder = Issues.Location.newBuilder();
if (issueDto.getMessage() != null) {
locationBuilder.setMessage(issueDto.getMessage());
locationBuilder.addAllMessageFormattings(MessageFormattingUtils.dbMessageFormattingToWs(issueDto.parseMessageFormattings()));
}
if (issueDto.getFilePath() != null) {
locationBuilder.setFilePath(issueDto.getFilePath());
}
if (locations != null) {
Issues.TextRange textRange = buildTextRange(locations);
locationBuilder.setTextRange(textRange);
getFlows(taintBuilder, locations, issueDto);
}
taintBuilder.setAssignedToSubscribedUser(issueDto.getAssigneeUuid() != null &&
issueDto.getAssigneeUuid().equals(userSession.getUuid()));
taintBuilder.setKey(issueDto.getKey());
taintBuilder.setCreationDate(issueDto.getCreatedAt());
taintBuilder.setResolved(issueDto.getStatus().equals(org.sonar.api.issue.Issue.STATUS_RESOLVED));
taintBuilder.setRuleKey(issueDto.getRuleKey().toString());
if (issueDto.getSeverity() != null) {
taintBuilder.setSeverity(Common.Severity.valueOf(issueDto.getSeverity()));
}
taintBuilder.setType(Common.RuleType.forNumber(issueDto.getType()));
taintBuilder.setClosed(false);
taintBuilder.setMainLocation(locationBuilder.build());
issueDto.getOptionalRuleDescriptionContextKey().ifPresent(taintBuilder::setRuleDescriptionContextKey);
return taintBuilder.build();
}
@Override
public TaintVulnerabilityLite generateClosedIssueMessage(String uuid) {
TaintVulnerabilityLite.Builder taintBuilder = TaintVulnerabilityLite.newBuilder();
taintBuilder.setKey(uuid);
taintBuilder.setClosed(true);
return taintBuilder.build();
}
private void getFlows(TaintVulnerabilityLite.Builder taintBuilder, Locations locations, IssueDto issueDto) {
List<Issues.Flow> flows = new ArrayList<>();
for (DbIssues.Flow f : locations.getFlowList()) {
Set<String> componentUuids = new HashSet<>();
Issues.Flow.Builder builder = Issues.Flow.newBuilder();
List<Issues.Location> flowLocations = new ArrayList<>();
getComponentUuids(f, componentUuids);
for (DbIssues.Location l : f.getLocationList()) {
Issues.Location.Builder flowLocationBuilder = Issues.Location
.newBuilder()
.setMessage(l.getMsg())
.setTextRange(buildTextRange(l));
if (l.hasComponentId() && componentsMap.containsKey(l.getComponentId())) {
flowLocationBuilder.setFilePath(componentsMap.get(l.getComponentId()).path());
} else {
flowLocationBuilder.setFilePath(issueDto.getFilePath());
}
flowLocations.add(flowLocationBuilder.build());
}
builder.addAllLocations(flowLocations);
flows.add(builder.build());
taintBuilder.addAllFlows(flows);
}
}
private void getComponentUuids(DbIssues.Flow f, Set<String> componentUuids) {
for (DbIssues.Location l : f.getLocationList()) {
if (l.hasComponentId() && !componentsMap.containsKey(l.getComponentId())) {
componentUuids.add(l.getComponentId());
}
}
if (!componentUuids.isEmpty()) {
componentsMap.putAll(getLocationComponents(componentUuids));
}
}
private static Issues.TextRange buildTextRange(DbIssues.Location location) {
int startLine = location.getTextRange().getStartLine();
int endLine = location.getTextRange().getEndLine();
int startOffset = location.getTextRange().getStartOffset();
int endOffset = location.getTextRange().getEndOffset();
return Issues.TextRange.newBuilder()
.setHash(location.getChecksum())
.setStartLine(startLine)
.setEndLine(endLine)
.setStartLineOffset(startOffset)
.setEndLineOffset(endOffset).build();
}
private void refreshComponents() {
componentsMap = new HashMap<>();
}
private Map<String, ComponentDto> getLocationComponents(Set<String> components) {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.componentDao().selectByUuids(dbSession, components)
.stream().collect(Collectors.toMap(ComponentDto::uuid, c -> c));
}
}
}
| 6,915 | 37.636872 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/pull/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.issue.ws.pull;
import javax.annotation.ParametersAreNonnullByDefault;
| 970 | 39.458333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/LanguageParamUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.language;
import java.util.Arrays;
import java.util.List;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
public class LanguageParamUtils {
private LanguageParamUtils() {
// Utility class
}
public static String getExampleValue(Languages languages) {
Language[] languageArray = languages.all();
if (languageArray.length > 0) {
return languageArray[0].getKey();
} else {
return "";
}
}
public static List<String> getOrderedLanguageKeys(Languages languages) {
Language[] all = languages.all();
return Arrays.stream(all)
.map(Language::getKey)
.sorted()
.toList();
}
}
| 1,543 | 29.88 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/LanguageValidation.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.language;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.sonar.api.Startable;
import org.sonar.api.resources.Language;
import org.sonar.server.plugins.ServerPluginRepository;
import org.springframework.beans.factory.annotation.Autowired;
public class LanguageValidation implements Startable {
private final ServerPluginRepository pluginRepository;
private final Language[] languages;
@Autowired(required = false)
public LanguageValidation(ServerPluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
this.languages = new Language[0];
}
@Autowired(required = false)
public LanguageValidation(ServerPluginRepository pluginRepository, Language... languages) {
this.pluginRepository = pluginRepository;
this.languages = languages;
}
public void start() {
Arrays.stream(languages).collect(Collectors.toMap(Language::getKey, x -> x, (x, y) -> {
String pluginX = pluginRepository.getPluginKey(x);
String pluginY = pluginRepository.getPluginKey(y);
throw new IllegalStateException(String.format("There are two languages declared with the same key '%s' declared "
+ "by the plugins '%s' and '%s'. Please uninstall one of the conflicting plugins.",
x.getKey(), pluginX, pluginY));
}));
}
@Override public void stop() {
// nothing to do
}
}
| 2,243 | 35.786885 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.language;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 39.25 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/LanguageWs.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.language.ws;
import org.sonar.api.server.ws.WebService;
/**
* @since 5.1
*/
public class LanguageWs implements WebService {
private final ListAction list;
public LanguageWs(ListAction list) {
this.list = list;
}
@Override
public void define(Context context) {
NewController languages = context.createController("api/languages")
.setDescription("Get the list of programming languages supported in this instance.")
.setSince("5.1");
list.define(languages);
languages.done();
}
}
| 1,395 | 28.702128 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/ListAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.language.ws;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.ws.WsAction;
/**
* @since 5.1
*/
public class ListAction implements WsAction {
private static final String MATCH_ALL = ".*";
private final Languages languages;
public ListAction(Languages languages) {
this.languages = languages;
}
@Override
public void handle(Request request, Response response) throws Exception {
String query = request.param(Param.TEXT_QUERY);
int pageSize = request.mandatoryParamAsInt("ps");
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject().name("languages").beginArray();
for (Language language : listMatchingLanguages(query, pageSize)) {
json.beginObject().prop("key", language.getKey()).prop("name", language.getName()).endObject();
}
json.endArray().endObject();
}
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction("list")
.setDescription("List supported programming languages")
.setSince("5.1")
.setHandler(this)
.setResponseExample(Resources.getResource(getClass(), "example-list.json"));
action.createParam(Param.TEXT_QUERY)
.setDescription("A pattern to match language keys/names against")
.setExampleValue("java");
action.createParam("ps")
.setDescription("The size of the list to return, 0 for all languages")
.setExampleValue("25")
.setDefaultValue("0");
}
private Collection<Language> listMatchingLanguages(@Nullable String query, int pageSize) {
Pattern pattern = Pattern.compile(query == null ? MATCH_ALL : Pattern.quote(query), Pattern.CASE_INSENSITIVE);
SortedMap<String, Language> languagesByName = Maps.newTreeMap();
for (Language lang : languages.all()) {
if (pattern.matcher(lang.getKey()).find() || pattern.matcher(lang.getName()).find()) {
languagesByName.put(lang.getName(), lang);
}
}
List<Language> result = Lists.newArrayList(languagesByName.values());
if (pageSize > 0 && pageSize < result.size()) {
result = result.subList(0, pageSize);
}
return result;
}
}
| 3,626 | 35.27 | 114 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/language/ws/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.language.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/management/ManagedInstanceChecker.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.management;
import org.sonar.server.exceptions.BadRequestException;
public class ManagedInstanceChecker {
private final ManagedInstanceService managedInstanceService;
public ManagedInstanceChecker(ManagedInstanceService managedInstanceService) {
this.managedInstanceService = managedInstanceService;
}
public void throwIfInstanceIsManaged() {
BadRequestException.checkRequest(!managedInstanceService.isInstanceExternallyManaged(), "Operation not allowed when the instance is externally managed.");
}
}
| 1,393 | 37.722222 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/management/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.management;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/ComponentIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.List;
import java.util.Set;
import org.sonar.db.component.ComponentDto;
/**
* Provides all components needed for the computation of live measures.
* The components needed for the computation are:
* 1) Components for which issues were modified
* 2) All ancestors of 1), up to the root
* 3) All immediate children of 1) and 2). The measures in these components won't be recomputed,
* but their measures are needed to recompute the measures for components in 1) and 2).
*/
public interface ComponentIndex {
/**
* Immediate children of a component that are relevant for the computation
*/
List<ComponentDto> getChildren(ComponentDto component);
/**
* Uuids of all components relevant for the computation
*/
Set<String> getAllUuids();
/**
* All components that need the measures recalculated, sorted depth first. It corresponds to the points 1) and 2) in the list mentioned in the javadoc of this class.
*/
List<ComponentDto> getSortedTree();
/**
* Branch being recomputed
*/
ComponentDto getBranch();
}
| 1,950 | 34.472727 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/ComponentIndexFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.List;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
public class ComponentIndexFactory {
private final DbClient dbClient;
public ComponentIndexFactory(DbClient dbClient) {
this.dbClient = dbClient;
}
public ComponentIndex create(DbSession dbSession, List<ComponentDto> touchedComponents) {
ComponentIndexImpl idx = new ComponentIndexImpl(dbClient);
idx.load(dbSession, touchedComponents);
return idx;
}
}
| 1,393 | 33.85 | 91 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/ComponentIndexImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static java.util.Collections.emptyList;
public class ComponentIndexImpl implements ComponentIndex {
private final DbClient dbClient;
private ComponentDto branchComponent;
private List<ComponentDto> sortedComponentsToRoot;
private Map<String, List<ComponentDto>> children;
public ComponentIndexImpl(DbClient dbClient) {
this.dbClient = dbClient;
}
/**
* Loads all the components required for the calculation of the new values of the live measures based on what components were modified:
* - All components between the touched components and the roots of their component trees
* - All immediate children of those components
*/
public void load(DbSession dbSession, List<ComponentDto> touchedComponents) {
sortedComponentsToRoot = loadTreeOfComponents(dbSession, touchedComponents);
branchComponent = findBranchComponent(sortedComponentsToRoot);
children = new HashMap<>();
List<ComponentDto> childComponents = loadChildren(dbSession, branchComponent.uuid(), sortedComponentsToRoot);
for (ComponentDto c : childComponents) {
List<String> uuidPathAsList = c.getUuidPathAsList();
String parentUuid = uuidPathAsList.get(uuidPathAsList.size() - 1);
children.computeIfAbsent(parentUuid, uuid -> new LinkedList<>()).add(c);
}
}
private static ComponentDto findBranchComponent(Collection<ComponentDto> components) {
return components.stream().filter(ComponentDto::isRootProject).findFirst()
.orElseThrow(() -> new IllegalStateException("No project found in " + components));
}
private List<ComponentDto> loadChildren(DbSession dbSession, String branchUuid, Collection<ComponentDto> components) {
return dbClient.componentDao().selectChildren(dbSession, branchUuid, components);
}
private List<ComponentDto> loadTreeOfComponents(DbSession dbSession, List<ComponentDto> touchedComponents) {
Set<String> componentUuids = new HashSet<>();
for (ComponentDto component : touchedComponents) {
componentUuids.add(component.uuid());
// ancestors, excluding self
componentUuids.addAll(component.getUuidPathAsList());
}
return dbClient.componentDao().selectByUuids(dbSession, componentUuids).stream()
.sorted(Comparator.comparing(ComponentDto::getUuidPath).reversed())
.toList();
}
@Override
public List<ComponentDto> getChildren(ComponentDto component) {
return children.getOrDefault(component.uuid(), emptyList());
}
@Override
public Set<String> getAllUuids() {
Set<String> all = new HashSet<>();
sortedComponentsToRoot.forEach(c -> all.add(c.uuid()));
for (Collection<ComponentDto> l : children.values()) {
for (ComponentDto c : l) {
all.add(c.uuid());
}
}
return all;
}
@Override
public List<ComponentDto> getSortedTree() {
return sortedComponentsToRoot;
}
@Override public ComponentDto getBranch() {
return branchComponent;
}
}
| 4,146 | 36.7 | 137 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/HotspotsCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.db.issue.HotspotGroupDto;
public class HotspotsCounter {
private final Map<String, Count> hotspotsByStatus = new HashMap<>();
HotspotsCounter(Collection<HotspotGroupDto> groups) {
for (HotspotGroupDto group : groups) {
if (group.getStatus() != null) {
hotspotsByStatus
.computeIfAbsent(group.getStatus(), k -> new Count())
.add(group);
}
}
}
public long countHotspotsByStatus(String status, boolean onlyInLeak) {
return value(hotspotsByStatus.get(status), onlyInLeak);
}
private static long value(@Nullable Count count, boolean onlyInLeak) {
if (count == null) {
return 0;
}
return onlyInLeak ? count.leak : count.absolute;
}
private static class Count {
private long absolute = 0L;
private long leak = 0L;
void add(HotspotGroupDto group) {
absolute += group.getCount();
if (group.isInLeak()) {
leak += group.getCount();
}
}
}
}
| 1,976 | 29.890625 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/IssueCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.db.issue.IssueGroupDto;
import org.sonar.db.rule.SeverityUtil;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
class IssueCounter {
private final Map<RuleType, HighestSeverity> highestSeverityOfUnresolved = new EnumMap<>(RuleType.class);
private final Map<RuleType, Effort> effortOfUnresolved = new EnumMap<>(RuleType.class);
private final Map<String, Count> unresolvedBySeverity = new HashMap<>();
private final Map<RuleType, Count> unresolvedByType = new EnumMap<>(RuleType.class);
private final Map<String, Count> byResolution = new HashMap<>();
private final Map<String, Count> byStatus = new HashMap<>();
private final Map<String, Count> hotspotsByStatus = new HashMap<>();
private final Count unresolved = new Count();
IssueCounter(Collection<IssueGroupDto> groups) {
for (IssueGroupDto group : groups) {
RuleType ruleType = RuleType.valueOf(group.getRuleType());
if (ruleType.equals(SECURITY_HOTSPOT)) {
if (group.getResolution() == null) {
unresolvedByType
.computeIfAbsent(SECURITY_HOTSPOT, k -> new Count())
.add(group);
}
if (group.getStatus() != null) {
hotspotsByStatus
.computeIfAbsent(group.getStatus(), k -> new Count())
.add(group);
}
continue;
}
if (group.getResolution() == null) {
highestSeverityOfUnresolved
.computeIfAbsent(ruleType, k -> new HighestSeverity())
.add(group);
effortOfUnresolved
.computeIfAbsent(ruleType, k -> new Effort())
.add(group);
unresolvedBySeverity
.computeIfAbsent(group.getSeverity(), k -> new Count())
.add(group);
unresolvedByType
.computeIfAbsent(ruleType, k -> new Count())
.add(group);
unresolved.add(group);
} else {
byResolution
.computeIfAbsent(group.getResolution(), k -> new Count())
.add(group);
}
if (group.getStatus() != null) {
byStatus
.computeIfAbsent(group.getStatus(), k -> new Count())
.add(group);
}
}
}
public Optional<String> getHighestSeverityOfUnresolved(RuleType ruleType, boolean onlyInLeak) {
return Optional.ofNullable(highestSeverityOfUnresolved.get(ruleType))
.map(hs -> hs.severity(onlyInLeak));
}
public double sumEffortOfUnresolved(RuleType type, boolean onlyInLeak) {
Effort effort = effortOfUnresolved.get(type);
if (effort == null) {
return 0.0;
}
return onlyInLeak ? effort.leak : effort.absolute;
}
public long countUnresolvedBySeverity(String severity, boolean onlyInLeak) {
return value(unresolvedBySeverity.get(severity), onlyInLeak);
}
public long countByResolution(String resolution, boolean onlyInLeak) {
return value(byResolution.get(resolution), onlyInLeak);
}
public long countUnresolvedByType(RuleType type, boolean onlyInLeak) {
return value(unresolvedByType.get(type), onlyInLeak);
}
public long countByStatus(String status, boolean onlyInLeak) {
return value(byStatus.get(status), onlyInLeak);
}
public long countUnresolved(boolean onlyInLeak) {
return value(unresolved, onlyInLeak);
}
public long countHotspotsByStatus(String status, boolean onlyInLeak) {
return value(hotspotsByStatus.get(status), onlyInLeak);
}
private static long value(@Nullable Count count, boolean onlyInLeak) {
if (count == null) {
return 0;
}
return onlyInLeak ? count.leak : count.absolute;
}
private static class Count {
private long absolute = 0L;
private long leak = 0L;
void add(IssueGroupDto group) {
absolute += group.getCount();
if (group.isInLeak()) {
leak += group.getCount();
}
}
}
private static class Effort {
private double absolute = 0.0;
private double leak = 0.0;
void add(IssueGroupDto group) {
absolute += group.getEffort();
if (group.isInLeak()) {
leak += group.getEffort();
}
}
}
private static class HighestSeverity {
private int absolute = SeverityUtil.getOrdinalFromSeverity(Severity.INFO);
private int leak = SeverityUtil.getOrdinalFromSeverity(Severity.INFO);
void add(IssueGroupDto group) {
int severity = SeverityUtil.getOrdinalFromSeverity(group.getSeverity());
absolute = Math.max(severity, absolute);
if (group.isInLeak()) {
leak = Math.max(severity, leak);
}
}
String severity(boolean inLeak) {
return SeverityUtil.getSeverityFromOrdinal(inLeak ? leak : absolute);
}
}
}
| 5,777 | 32.206897 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveMeasureComputer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.List;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.qualitygate.changeevent.QGChangeEvent;
/**
* Refresh and persist the measures of some files, directories, modules
* or projects. Measures include status of quality gate.
*
* Touching a file updates the related directory, module and project.
* Status of Quality gate is refreshed but webhooks are not triggered.
*
* Branches are supported.
*/
@ServerSide
public interface LiveMeasureComputer {
List<QGChangeEvent> refresh(DbSession dbSession, Collection<ComponentDto> components);
}
| 1,569 | 34.681818 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveMeasureComputerImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.Configuration;
import org.sonar.api.measures.Metric;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureComparator;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.es.Indexers;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.qualitygate.QualityGate;
import org.sonar.server.qualitygate.changeevent.QGChangeEvent;
import org.sonar.server.setting.ProjectConfigurationLoader;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.groupingBy;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
public class LiveMeasureComputerImpl implements LiveMeasureComputer {
private final DbClient dbClient;
private final MeasureUpdateFormulaFactory formulaFactory;
private final ComponentIndexFactory componentIndexFactory;
private final LiveQualityGateComputer qGateComputer;
private final ProjectConfigurationLoader projectConfigurationLoader;
private final Indexers projectIndexer;
private final LiveMeasureTreeUpdater treeUpdater;
public LiveMeasureComputerImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory, ComponentIndexFactory componentIndexFactory,
LiveQualityGateComputer qGateComputer, ProjectConfigurationLoader projectConfigurationLoader, Indexers projectIndexer, LiveMeasureTreeUpdater treeUpdater) {
this.dbClient = dbClient;
this.formulaFactory = formulaFactory;
this.componentIndexFactory = componentIndexFactory;
this.qGateComputer = qGateComputer;
this.projectConfigurationLoader = projectConfigurationLoader;
this.projectIndexer = projectIndexer;
this.treeUpdater = treeUpdater;
}
@Override
public List<QGChangeEvent> refresh(DbSession dbSession, Collection<ComponentDto> components) {
if (components.isEmpty()) {
return emptyList();
}
List<QGChangeEvent> result = new ArrayList<>();
Map<String, List<ComponentDto>> componentsByProjectUuid = components.stream().collect(groupingBy(ComponentDto::branchUuid));
for (List<ComponentDto> groupedComponents : componentsByProjectUuid.values()) {
Optional<QGChangeEvent> qgChangeEvent = refreshComponentsOnSameProject(dbSession, groupedComponents);
qgChangeEvent.ifPresent(result::add);
}
return result;
}
private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
ComponentIndex components = componentIndexFactory.create(dbSession, touchedComponents);
ComponentDto branchComponent = components.getBranch();
Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
if (lastAnalysis.isEmpty()) {
return Optional.empty();
}
BranchDto branch = loadBranch(dbSession, branchComponent);
ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
Configuration config = projectConfigurationLoader.loadBranchConfiguration(dbSession, branch);
QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
MeasureMatrix matrix = loadMeasureMatrix(dbSession, components.getAllUuids(), qualityGate);
treeUpdater.update(dbSession, lastAnalysis.get(), config, components, branch, matrix);
Metric.Level previousStatus = loadPreviousStatus(dbSession, branchComponent);
EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix, config);
persistAndIndex(dbSession, matrix, branch);
return Optional.of(new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
}
private MeasureMatrix loadMeasureMatrix(DbSession dbSession, Set<String> componentUuids, QualityGate qualityGate) {
Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
Map<String, MetricDto> metricsPerUuid = dbClient.metricDao().selectByKeys(dbSession, metricKeys).stream().collect(Collectors.toMap(MetricDto::getUuid, Function.identity()));
List<LiveMeasureDto> measures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerUuid.keySet());
return new MeasureMatrix(componentUuids, metricsPerUuid.values(), measures);
}
private void persistAndIndex(DbSession dbSession, MeasureMatrix matrix, BranchDto branch) {
// persist the measures that have been created or updated
matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE).forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
projectIndexer.commitAndIndexBranches(dbSession, singleton(branch), Indexers.BranchEvent.MEASURE_CHANGE);
}
@CheckForNull
private Metric.Level loadPreviousStatus(DbSession dbSession, ComponentDto branchComponent) {
Optional<LiveMeasureDto> measure = dbClient.liveMeasureDao().selectMeasure(dbSession, branchComponent.uuid(), ALERT_STATUS_KEY);
if (measure.isEmpty()) {
return null;
}
try {
return Metric.Level.valueOf(measure.get().getTextValue());
} catch (IllegalArgumentException e) {
LoggerFactory.getLogger(LiveMeasureComputerImpl.class).trace("Failed to parse value of metric '{}'", ALERT_STATUS_KEY, e);
return null;
}
}
private Set<String> getKeysOfAllInvolvedMetrics(QualityGate gate) {
Set<String> metricKeys = new HashSet<>();
for (Metric<?> metric : formulaFactory.getFormulaMetrics()) {
metricKeys.add(metric.getKey());
}
metricKeys.addAll(qGateComputer.getMetricsRelatedTo(gate));
return metricKeys;
}
private BranchDto loadBranch(DbSession dbSession, ComponentDto branchComponent) {
return dbClient.branchDao().selectByUuid(dbSession, branchComponent.uuid())
.orElseThrow(() -> new IllegalStateException("Branch not found: " + branchComponent.uuid()));
}
private ProjectDto loadProject(DbSession dbSession, String uuid) {
return dbClient.projectDao().selectByUuid(dbSession, uuid)
.orElseThrow(() -> new IllegalStateException("Project not found: " + uuid));
}
}
| 7,625 | 46.36646 | 177 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveMeasureModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import org.sonar.core.platform.Module;
public class LiveMeasureModule extends Module {
@Override
protected void configureModule() {
add(
MeasureUpdateFormulaFactoryImpl.class,
ComponentIndexFactory.class,
LiveMeasureTreeUpdaterImpl.class,
LiveMeasureComputerImpl.class,
LiveQualityGateComputerImpl.class);
}
}
| 1,234 | 34.285714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveMeasureTreeUpdater.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import org.sonar.api.config.Configuration;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.SnapshotDto;
public interface LiveMeasureTreeUpdater {
void update(DbSession dbSession, SnapshotDto lastAnalysis, Configuration config, ComponentIndex components, BranchDto branch, MeasureMatrix measures);
}
| 1,239 | 40.333333 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveMeasureTreeUpdaterImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.sonar.api.config.Configuration;
import org.sonar.api.measures.Metric;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.server.measure.DebtRatingGrid;
import org.sonar.server.measure.Rating;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
public class LiveMeasureTreeUpdaterImpl implements LiveMeasureTreeUpdater {
private final DbClient dbClient;
private final MeasureUpdateFormulaFactory formulaFactory;
public LiveMeasureTreeUpdaterImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory) {
this.dbClient = dbClient;
this.formulaFactory = formulaFactory;
}
@Override
public void update(DbSession dbSession, SnapshotDto lastAnalysis, Configuration config, ComponentIndex components, BranchDto branch, MeasureMatrix measures) {
long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
boolean shouldUseLeakFormulas = shouldUseLeakFormulas(lastAnalysis, branch);
// 1. set new measure from issues to each component from touched components to the root
updateMatrixWithIssues(dbSession, measures, components, config, shouldUseLeakFormulas, beginningOfLeak);
// 2. aggregate new measures up the component tree
updateMatrixWithHierarchy(measures, components, config, shouldUseLeakFormulas);
}
private void updateMatrixWithHierarchy(MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas) {
DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
components.getSortedTree().forEach(c -> {
for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
if (useLeakFormulas || !formula.isOnLeak()) {
context.change(c, formula);
try {
formula.computeHierarchy(context);
} catch (RuntimeException e) {
throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
+ context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
}
}
}
});
}
private void updateMatrixWithIssues(DbSession dbSession, MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas, long beginningOfLeak) {
DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
components.getSortedTree().forEach(c -> {
IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByComponent(dbSession, c, beginningOfLeak));
for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
// use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
if (useLeakFormulas || !formula.isOnLeak()) {
context.change(c, formula);
try {
formula.compute(context, issueCounter);
} catch (RuntimeException e) {
throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
+ context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
}
}
}
});
}
private static long getBeginningOfLeakPeriod(SnapshotDto lastAnalysis, BranchDto branch) {
if (isPR(branch)) {
return 0L;
} else if (REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode())) {
return -1;
} else {
return Optional.ofNullable(lastAnalysis.getPeriodDate()).orElse(Long.MAX_VALUE);
}
}
private static boolean isPR(BranchDto branch) {
return branch.getBranchType() == BranchType.PULL_REQUEST;
}
private static boolean shouldUseLeakFormulas(SnapshotDto lastAnalysis, BranchDto branch) {
return lastAnalysis.getPeriodDate() != null || isPR(branch) || REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode());
}
public static class FormulaContextImpl implements MeasureUpdateFormula.Context {
private final MeasureMatrix matrix;
private final ComponentIndex componentIndex;
private final DebtRatingGrid debtRatingGrid;
private ComponentDto currentComponent;
private MeasureUpdateFormula currentFormula;
public FormulaContextImpl(MeasureMatrix matrix, ComponentIndex componentIndex, DebtRatingGrid debtRatingGrid) {
this.matrix = matrix;
this.componentIndex = componentIndex;
this.debtRatingGrid = debtRatingGrid;
}
void change(ComponentDto component, MeasureUpdateFormula formula) {
this.currentComponent = component;
this.currentFormula = formula;
}
public List<Double> getChildrenValues() {
List<ComponentDto> children = componentIndex.getChildren(currentComponent);
return children.stream()
.flatMap(c -> matrix.getMeasure(c, currentFormula.getMetric().getKey()).stream())
.map(LiveMeasureDto::getValue)
.filter(Objects::nonNull)
.toList();
}
/**
* Some child components may not have the measures 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS' and 'SECURITY_HOTSPOTS_REVIEWED_STATUS' saved for them,
* so we may need to calculate them based on 'SECURITY_HOTSPOTS_REVIEWED' and 'SECURITY_HOTSPOTS'.
*/
@Override
public long getChildrenHotspotsReviewed() {
return getChildrenHotspotsReviewed(SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_HOTSPOTS_KEY);
}
/**
* Some child components may not have the measure 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'SECURITY_HOTSPOTS_KEY' has the same value.
*/
@Override
public long getChildrenHotspotsToReview() {
return componentIndex.getChildren(currentComponent)
.stream()
.map(c -> matrix.getMeasure(c, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, SECURITY_HOTSPOTS_KEY)))
.mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
.sum();
}
@Override
public long getChildrenNewHotspotsReviewed() {
return getChildrenHotspotsReviewed(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, NEW_SECURITY_HOTSPOTS_KEY);
}
/**
* Some child components may not have the measure 'NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'NEW_SECURITY_HOTSPOTS_KEY' has the same value.
*/
@Override
public long getChildrenNewHotspotsToReview() {
return componentIndex.getChildren(currentComponent)
.stream()
.map(c -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_KEY)))
.mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
.sum();
}
private long getChildrenHotspotsReviewed(String metricKey, String percMetricKey, String hotspotsMetricKey) {
return componentIndex.getChildren(currentComponent)
.stream()
.mapToLong(c -> getHotspotsReviewed(c, metricKey, percMetricKey, hotspotsMetricKey))
.sum();
}
private long getHotspotsReviewed(ComponentDto c, String metricKey, String percMetricKey, String hotspotsMetricKey) {
Optional<LiveMeasureDto> measure = matrix.getMeasure(c, metricKey);
return measure.map(lm -> Optional.ofNullable(lm.getValue()).orElse(0D).longValue())
.orElseGet(() -> matrix.getMeasure(c, percMetricKey)
.flatMap(percentage -> matrix.getMeasure(c, hotspotsMetricKey)
.map(hotspots -> {
double perc = Optional.ofNullable(percentage.getValue()).orElse(0D) / 100D;
double toReview = Optional.ofNullable(hotspots.getValue()).orElse(0D);
double reviewed = (toReview * perc) / (1D - perc);
return Math.round(reviewed);
}))
.orElse(0L));
}
@Override
public ComponentDto getComponent() {
return currentComponent;
}
@Override
public DebtRatingGrid getDebtRatingGrid() {
return debtRatingGrid;
}
@Override
public Optional<Double> getValue(Metric metric) {
Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
return measure.map(LiveMeasureDto::getValue);
}
@Override
public Optional<String> getText(Metric metric) {
Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
return measure.map(LiveMeasureDto::getTextValue);
}
@Override
public void setValue(double value) {
String metricKey = currentFormula.getMetric().getKey();
matrix.setValue(currentComponent, metricKey, value);
}
@Override
public void setValue(Rating value) {
String metricKey = currentFormula.getMetric().getKey();
matrix.setValue(currentComponent, metricKey, value);
}
}
}
| 10,897 | 42.943548 | 178 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveQualityGateComputer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Set;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.qualitygate.QualityGate;
@ServerSide
public interface LiveQualityGateComputer {
QualityGate loadQualityGate(DbSession dbSession, ProjectDto project, BranchDto branch);
EvaluatedQualityGate refreshGateStatus(ComponentDto project, QualityGate gate, MeasureMatrix measureMatrix, Configuration configuration);
Set<String> getMetricsRelatedTo(QualityGate gate);
}
| 1,596 | 37.02381 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/LiveQualityGateComputerImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.config.Configuration;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.server.qualitygate.Condition;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.qualitygate.QualityGate;
import org.sonar.server.qualitygate.QualityGateConverter;
import org.sonar.server.qualitygate.QualityGateEvaluator;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonar.server.qualitygate.QualityGateFinder.QualityGateData;
public class LiveQualityGateComputerImpl implements LiveQualityGateComputer {
private final DbClient dbClient;
private final QualityGateFinder qGateFinder;
private final QualityGateEvaluator evaluator;
public LiveQualityGateComputerImpl(DbClient dbClient, QualityGateFinder qGateFinder, QualityGateEvaluator evaluator) {
this.dbClient = dbClient;
this.qGateFinder = qGateFinder;
this.evaluator = evaluator;
}
@Override
public QualityGate loadQualityGate(DbSession dbSession, ProjectDto project, BranchDto branch) {
QualityGateData qg = qGateFinder.getEffectiveQualityGate(dbSession, project);
Collection<QualityGateConditionDto> conditionDtos = dbClient.gateConditionDao().selectForQualityGate(dbSession, qg.getUuid());
Set<String> metricUuids = conditionDtos.stream().map(QualityGateConditionDto::getMetricUuid).collect(Collectors.toSet());
Map<String, MetricDto> metricsByUuid = dbClient.metricDao().selectByUuids(dbSession, metricUuids).stream().collect(Collectors.toMap(MetricDto::getUuid, Function.identity()));
Stream<Condition> conditions = conditionDtos.stream().map(conditionDto -> {
String metricKey = metricsByUuid.get(conditionDto.getMetricUuid()).getKey();
Condition.Operator operator = Condition.Operator.fromDbValue(conditionDto.getOperator());
return new Condition(metricKey, operator, conditionDto.getErrorThreshold());
});
if (branch.getBranchType() == BranchType.PULL_REQUEST) {
conditions = conditions.filter(Condition::isOnLeakPeriod);
}
return new QualityGate(String.valueOf(qg.getUuid()), qg.getName(), conditions.collect(Collectors.toSet()));
}
@Override
public EvaluatedQualityGate refreshGateStatus(ComponentDto project, QualityGate gate, MeasureMatrix measureMatrix, Configuration configuration) {
QualityGateEvaluator.Measures measures = metricKey -> {
Optional<LiveMeasureDto> liveMeasureDto = measureMatrix.getMeasure(project, metricKey);
if (!liveMeasureDto.isPresent()) {
return Optional.empty();
}
MetricDto metric = measureMatrix.getMetricByUuid(liveMeasureDto.get().getMetricUuid());
return Optional.of(new LiveMeasure(liveMeasureDto.get(), metric));
};
EvaluatedQualityGate evaluatedGate = evaluator.evaluate(gate, measures, configuration);
measureMatrix.setValue(project, CoreMetrics.ALERT_STATUS_KEY, evaluatedGate.getStatus().name());
measureMatrix.setValue(project, CoreMetrics.QUALITY_GATE_DETAILS_KEY, QualityGateConverter.toJson(evaluatedGate));
return evaluatedGate;
}
@Override
public Set<String> getMetricsRelatedTo(QualityGate gate) {
Set<String> metricKeys = new HashSet<>();
metricKeys.add(CoreMetrics.ALERT_STATUS_KEY);
metricKeys.add(CoreMetrics.QUALITY_GATE_DETAILS_KEY);
metricKeys.addAll(evaluator.getMetricKeys(gate));
return metricKeys;
}
private static class LiveMeasure implements QualityGateEvaluator.Measure {
private final LiveMeasureDto dto;
private final MetricDto metric;
LiveMeasure(LiveMeasureDto dto, MetricDto metric) {
this.dto = dto;
this.metric = metric;
}
@Override
public Metric.ValueType getType() {
return Metric.ValueType.valueOf(metric.getValueType());
}
@Override
public OptionalDouble getValue() {
if (dto.getValue() == null) {
return OptionalDouble.empty();
}
return OptionalDouble.of(dto.getValue());
}
@Override
public Optional<String> getStringValue() {
return Optional.ofNullable(dto.getTextValue());
}
}
}
| 5,629 | 39.503597 | 178 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureMatrix.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import com.google.common.collect.ArrayTable;
import com.google.common.collect.Table;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.measure.Rating;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
/**
* Keep the measures in memory during refresh of live measures:
* <ul>
* <li>the values of last analysis, restricted to the needed metrics</li>
* <li>the refreshed values</li>
* </ul>
*/
class MeasureMatrix {
// component uuid -> metric key -> measure
private final Table<String, String, MeasureCell> table;
private final Map<String, MetricDto> metricsByKeys = new HashMap<>();
private final Map<String, MetricDto> metricsByUuids = new HashMap<>();
MeasureMatrix(Collection<ComponentDto> components, Collection<MetricDto> metrics, List<LiveMeasureDto> dbMeasures) {
this(components.stream().map(ComponentDto::uuid).collect(Collectors.toSet()), metrics, dbMeasures);
}
MeasureMatrix(Set<String> componentUuids, Collection<MetricDto> metrics, List<LiveMeasureDto> dbMeasures) {
for (MetricDto metric : metrics) {
this.metricsByKeys.put(metric.getKey(), metric);
this.metricsByUuids.put(metric.getUuid(), metric);
}
this.table = ArrayTable.create(componentUuids, metricsByKeys.keySet());
for (LiveMeasureDto dbMeasure : dbMeasures) {
table.put(dbMeasure.getComponentUuid(), metricsByUuids.get(dbMeasure.getMetricUuid()).getKey(), new MeasureCell(dbMeasure));
}
}
MetricDto getMetricByUuid(String uuid) {
return requireNonNull(metricsByUuids.get(uuid), () -> String.format("Metric with uuid %s not found", uuid));
}
private MetricDto getMetric(String key) {
return requireNonNull(metricsByKeys.get(key), () -> String.format("Metric with key %s not found", key));
}
Optional<LiveMeasureDto> getMeasure(ComponentDto component, String metricKey) {
checkArgument(table.containsColumn(metricKey), "Metric with key %s is not registered", metricKey);
MeasureCell cell = table.get(component.uuid(), metricKey);
return cell == null ? Optional.empty() : Optional.of(cell.measure);
}
void setValue(ComponentDto component, String metricKey, double value) {
changeCell(component, metricKey, m -> m.setValue(scale(getMetric(metricKey), value)));
}
void setValue(ComponentDto component, String metricKey, Rating value) {
changeCell(component, metricKey, m -> {
m.setData(value.name());
m.setValue((double) value.getIndex());
});
}
void setValue(ComponentDto component, String metricKey, @Nullable String data) {
changeCell(component, metricKey, m -> m.setData(data));
}
Stream<LiveMeasureDto> getChanged() {
return table.values().stream()
.filter(Objects::nonNull)
.filter(MeasureCell::isChanged)
.map(MeasureCell::getMeasure);
}
private void changeCell(ComponentDto component, String metricKey, Consumer<LiveMeasureDto> changer) {
MeasureCell cell = table.get(component.uuid(), metricKey);
if (cell == null) {
LiveMeasureDto measure = new LiveMeasureDto()
.setComponentUuid(component.uuid())
.setProjectUuid(component.branchUuid())
.setMetricUuid(metricsByKeys.get(metricKey).getUuid());
cell = new MeasureCell(measure);
table.put(component.uuid(), metricKey, cell);
}
changer.accept(cell.getMeasure());
}
/**
* Round a measure value by applying the scale defined on the metric.
* Example: scale(0.1234) returns 0.12 if metric scale is 2
*/
private static double scale(MetricDto metric, double value) {
if (metric.getDecimalScale() == null) {
return value;
}
BigDecimal bd = BigDecimal.valueOf(value);
return bd.setScale(metric.getDecimalScale(), RoundingMode.HALF_UP).doubleValue();
}
private static class MeasureCell {
private final LiveMeasureDto measure;
private final Double initialValue;
private final byte[] initialData;
private final String initialTextValue;
private MeasureCell(LiveMeasureDto measure) {
this.measure = measure;
this.initialValue = measure.getValue();
this.initialData = measure.getData();
this.initialTextValue = measure.getTextValue();
}
public LiveMeasureDto getMeasure() {
return measure;
}
public boolean isChanged() {
return !Objects.equals(initialValue, measure.getValue()) || !Arrays.equals(initialData, measure.getData()) || !Objects.equals(initialTextValue, measure.getTextValue());
}
}
}
| 5,919 | 36.232704 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureUpdateFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import org.sonar.api.measures.Metric;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.measure.DebtRatingGrid;
import org.sonar.server.measure.Rating;
import static java.util.Collections.emptyList;
class MeasureUpdateFormula {
private final Metric metric;
private final boolean onLeak;
private final BiConsumer<Context, MeasureUpdateFormula> hierarchyFormula;
private final BiConsumer<Context, IssueCounter> formula;
private final Collection<Metric> dependentMetrics;
/**
* @param hierarchyFormula Called in a second pass through all the components, after 'formula' is called. Used to calculate the aggregate values for each component.
* For many metrics, we sum the value of the children to the value of the component
* @param formula Used to calculate new values for a metric for each component, based on the issue counts
*/
MeasureUpdateFormula(Metric metric, boolean onLeak, BiConsumer<Context, MeasureUpdateFormula> hierarchyFormula, BiConsumer<Context, IssueCounter> formula) {
this(metric, onLeak, hierarchyFormula, formula, emptyList());
}
MeasureUpdateFormula(Metric metric, boolean onLeak, BiConsumer<Context, MeasureUpdateFormula> hierarchyFormula, BiConsumer<Context, IssueCounter> formula,
Collection<Metric> dependentMetrics) {
this.metric = metric;
this.onLeak = onLeak;
this.hierarchyFormula = hierarchyFormula;
this.formula = formula;
this.dependentMetrics = dependentMetrics;
}
Metric getMetric() {
return metric;
}
boolean isOnLeak() {
return onLeak;
}
Collection<Metric> getDependentMetrics() {
return dependentMetrics;
}
void compute(Context context, IssueCounter issues) {
formula.accept(context, issues);
}
void computeHierarchy(Context context) {
hierarchyFormula.accept(context, this);
}
interface Context {
List<Double> getChildrenValues();
long getChildrenHotspotsReviewed();
long getChildrenHotspotsToReview();
long getChildrenNewHotspotsReviewed();
long getChildrenNewHotspotsToReview();
ComponentDto getComponent();
DebtRatingGrid getDebtRatingGrid();
/**
* Value that was just refreshed, otherwise value as computed
* during last analysis.
* The metric must be declared in the formula dependencies
* (see {@link MeasureUpdateFormula#getDependentMetrics()}).
*/
Optional<Double> getValue(Metric metric);
Optional<String> getText(Metric metrc);
void setValue(double value);
void setValue(Rating value);
}
}
| 3,586 | 31.908257 | 166 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureUpdateFormulaFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.measures.Metric;
import org.sonar.api.server.ServerSide;
@ServerSide
public interface MeasureUpdateFormulaFactory {
List<MeasureUpdateFormula> getFormulas();
Set<Metric> getFormulaMetrics();
static Set<Metric> extractMetrics(List<MeasureUpdateFormula> formulas) {
return formulas.stream()
.flatMap(f -> Stream.concat(Stream.of(f.getMetric()), f.getDependentMetrics().stream()))
.collect(Collectors.toSet());
}
}
| 1,456 | 34.536585 | 94 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureUpdateFormulaFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.live;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.BiConsumer;
import org.sonar.api.issue.Issue;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.server.measure.Rating;
import static java.util.Arrays.asList;
import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS;
import static org.sonar.server.measure.Rating.RATING_BY_SEVERITY;
import static org.sonar.server.security.SecurityReviewRating.computePercent;
import static org.sonar.server.security.SecurityReviewRating.computeRating;
public class MeasureUpdateFormulaFactoryImpl implements MeasureUpdateFormulaFactory {
private static final List<MeasureUpdateFormula> FORMULAS = asList(
new MeasureUpdateFormula(CODE_SMELLS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.CODE_SMELL, false))),
new MeasureUpdateFormula(CoreMetrics.BUGS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.BUG, false))),
new MeasureUpdateFormula(CoreMetrics.VULNERABILITIES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.VULNERABILITY, false))),
new MeasureUpdateFormula(CoreMetrics.SECURITY_HOTSPOTS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.SECURITY_HOTSPOT, false))),
new MeasureUpdateFormula(CoreMetrics.VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolved(false))),
new MeasureUpdateFormula(CoreMetrics.BLOCKER_VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.BLOCKER, false))),
new MeasureUpdateFormula(CoreMetrics.CRITICAL_VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.CRITICAL, false))),
new MeasureUpdateFormula(CoreMetrics.MAJOR_VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.MAJOR, false))),
new MeasureUpdateFormula(CoreMetrics.MINOR_VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.MINOR, false))),
new MeasureUpdateFormula(CoreMetrics.INFO_VIOLATIONS, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.INFO, false))),
new MeasureUpdateFormula(CoreMetrics.FALSE_POSITIVE_ISSUES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countByResolution(Issue.RESOLUTION_FALSE_POSITIVE, false))),
new MeasureUpdateFormula(CoreMetrics.WONT_FIX_ISSUES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countByResolution(Issue.RESOLUTION_WONT_FIX, false))),
new MeasureUpdateFormula(CoreMetrics.OPEN_ISSUES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countByStatus(Issue.STATUS_OPEN, false))),
new MeasureUpdateFormula(CoreMetrics.REOPENED_ISSUES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countByStatus(Issue.STATUS_REOPENED, false))),
new MeasureUpdateFormula(CoreMetrics.CONFIRMED_ISSUES, false, new AddChildren(),
(context, issues) -> context.setValue(issues.countByStatus(Issue.STATUS_CONFIRMED, false))),
new MeasureUpdateFormula(CoreMetrics.TECHNICAL_DEBT, false, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.CODE_SMELL, false))),
new MeasureUpdateFormula(CoreMetrics.RELIABILITY_REMEDIATION_EFFORT, false, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.BUG, false))),
new MeasureUpdateFormula(CoreMetrics.SECURITY_REMEDIATION_EFFORT, false, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.VULNERABILITY, false))),
new MeasureUpdateFormula(CoreMetrics.SQALE_DEBT_RATIO, false,
(context, formula) -> context.setValue(100.0 * debtDensity(context)),
(context, issues) -> context.setValue(100.0 * debtDensity(context)),
asList(CoreMetrics.TECHNICAL_DEBT, CoreMetrics.DEVELOPMENT_COST)),
new MeasureUpdateFormula(CoreMetrics.SQALE_RATING, false,
(context, issues) -> context.setValue(context.getDebtRatingGrid().getRatingForDensity(debtDensity(context))),
(context, issues) -> context.setValue(context.getDebtRatingGrid().getRatingForDensity(debtDensity(context))),
asList(CoreMetrics.TECHNICAL_DEBT, CoreMetrics.DEVELOPMENT_COST)),
new MeasureUpdateFormula(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, false,
(context, formula) -> context.setValue(effortToReachMaintainabilityRatingA(context)),
(context, issues) -> context.setValue(effortToReachMaintainabilityRatingA(context)), asList(CoreMetrics.TECHNICAL_DEBT, CoreMetrics.DEVELOPMENT_COST)),
new MeasureUpdateFormula(CoreMetrics.RELIABILITY_RATING, false, new MaxRatingChildren(),
(context, issues) -> context.setValue(RATING_BY_SEVERITY.get(issues.getHighestSeverityOfUnresolved(RuleType.BUG, false).orElse(Severity.INFO)))),
new MeasureUpdateFormula(CoreMetrics.SECURITY_RATING, false, new MaxRatingChildren(),
(context, issues) -> context.setValue(RATING_BY_SEVERITY.get(issues.getHighestSeverityOfUnresolved(RuleType.VULNERABILITY, false).orElse(Severity.INFO)))),
new MeasureUpdateFormula(SECURITY_HOTSPOTS_REVIEWED_STATUS, false,
(context, formula) -> context.setValue(context.getValue(SECURITY_HOTSPOTS_REVIEWED_STATUS).orElse(0D) + context.getChildrenHotspotsReviewed()),
(context, issues) -> context.setValue(issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, false))),
new MeasureUpdateFormula(SECURITY_HOTSPOTS_TO_REVIEW_STATUS, false,
(context, formula) -> context.setValue(context.getValue(SECURITY_HOTSPOTS_TO_REVIEW_STATUS).orElse(0D) + context.getChildrenHotspotsToReview()),
(context, issues) -> context.setValue(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, false))),
new MeasureUpdateFormula(CoreMetrics.SECURITY_HOTSPOTS_REVIEWED, false,
(context, formula) -> {
Optional<Double> percent = computePercent(
context.getValue(SECURITY_HOTSPOTS_TO_REVIEW_STATUS).orElse(0D).longValue(),
context.getValue(SECURITY_HOTSPOTS_REVIEWED_STATUS).orElse(0D).longValue());
percent.ifPresent(context::setValue);
},
(context, issues) -> computePercent(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, false), issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, false))
.ifPresent(context::setValue)),
new MeasureUpdateFormula(CoreMetrics.SECURITY_REVIEW_RATING, false,
(context, formula) -> context.setValue(computeRating(context.getValue(SECURITY_HOTSPOTS_REVIEWED).orElse(null))),
(context, issues) -> {
Optional<Double> percent = computePercent(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, false), issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, false));
context.setValue(computeRating(percent.orElse(null)));
}),
new MeasureUpdateFormula(CoreMetrics.NEW_CODE_SMELLS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.CODE_SMELL, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_BUGS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.BUG, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_VULNERABILITIES, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.VULNERABILITY, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_SECURITY_HOTSPOTS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedByType(RuleType.SECURITY_HOTSPOT, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolved(true))),
new MeasureUpdateFormula(CoreMetrics.NEW_BLOCKER_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.BLOCKER, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_CRITICAL_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.CRITICAL, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_MAJOR_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.MAJOR, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_MINOR_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.MINOR, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_INFO_VIOLATIONS, true, new AddChildren(),
(context, issues) -> context.setValue(issues.countUnresolvedBySeverity(Severity.INFO, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_TECHNICAL_DEBT, true, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.CODE_SMELL, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT, true, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.BUG, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT, true, new AddChildren(),
(context, issues) -> context.setValue(issues.sumEffortOfUnresolved(RuleType.VULNERABILITY, true))),
new MeasureUpdateFormula(CoreMetrics.NEW_RELIABILITY_RATING, true, new MaxRatingChildren(),
(context, issues) -> {
String highestSeverity = issues.getHighestSeverityOfUnresolved(RuleType.BUG, true).orElse(Severity.INFO);
context.setValue(RATING_BY_SEVERITY.get(highestSeverity));
}),
new MeasureUpdateFormula(CoreMetrics.NEW_SECURITY_RATING, true, new MaxRatingChildren(),
(context, issues) -> {
String highestSeverity = issues.getHighestSeverityOfUnresolved(RuleType.VULNERABILITY, true).orElse(Severity.INFO);
context.setValue(RATING_BY_SEVERITY.get(highestSeverity));
}),
new MeasureUpdateFormula(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS, true,
(context, formula) -> context.setValue(context.getValue(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS).orElse(0D) + context.getChildrenNewHotspotsReviewed()),
(context, issues) -> context.setValue(issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, true))),
new MeasureUpdateFormula(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS, true,
(context, formula) -> context.setValue(context.getValue(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS).orElse(0D) + context.getChildrenNewHotspotsToReview()),
(context, issues) -> context.setValue(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, true))),
new MeasureUpdateFormula(NEW_SECURITY_HOTSPOTS_REVIEWED, true,
(context, formula) -> {
Optional<Double> percent = computePercent(
context.getValue(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS).orElse(0D).longValue(),
context.getValue(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS).orElse(0D).longValue());
percent.ifPresent(context::setValue);
},
(context, issues) -> computePercent(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, true), issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, true))
.ifPresent(context::setValue)),
new MeasureUpdateFormula(CoreMetrics.NEW_SECURITY_REVIEW_RATING, true,
(context, formula) -> context.setValue(computeRating(context.getValue(NEW_SECURITY_HOTSPOTS_REVIEWED).orElse(null))),
(context, issues) -> {
Optional<Double> percent = computePercent(issues.countHotspotsByStatus(Issue.STATUS_TO_REVIEW, true), issues.countHotspotsByStatus(Issue.STATUS_REVIEWED, true));
context.setValue(computeRating(percent.orElse(null)));
}),
new MeasureUpdateFormula(CoreMetrics.NEW_SQALE_DEBT_RATIO, true,
(context, formula) -> context.setValue(100.0D * newDebtDensity(context)),
(context, issues) -> context.setValue(100.0D * newDebtDensity(context)),
asList(CoreMetrics.NEW_TECHNICAL_DEBT, CoreMetrics.NEW_DEVELOPMENT_COST)),
new MeasureUpdateFormula(CoreMetrics.NEW_MAINTAINABILITY_RATING, true,
(context, formula) -> context.setValue(context.getDebtRatingGrid().getRatingForDensity(newDebtDensity(context))),
(context, issues) -> context.setValue(context.getDebtRatingGrid().getRatingForDensity(newDebtDensity(context))),
asList(CoreMetrics.NEW_TECHNICAL_DEBT, CoreMetrics.NEW_DEVELOPMENT_COST)));
private static final Set<Metric> FORMULA_METRICS = MeasureUpdateFormulaFactory.extractMetrics(FORMULAS);
private static double debtDensity(MeasureUpdateFormula.Context context) {
double debt = Math.max(context.getValue(CoreMetrics.TECHNICAL_DEBT).orElse(0.0D), 0.0D);
Optional<Double> devCost = context.getText(CoreMetrics.DEVELOPMENT_COST).map(Double::parseDouble);
if (devCost.isPresent() && Double.doubleToRawLongBits(devCost.get()) > 0L) {
return debt / devCost.get();
}
return 0.0D;
}
private static double newDebtDensity(MeasureUpdateFormula.Context context) {
double debt = Math.max(context.getValue(CoreMetrics.NEW_TECHNICAL_DEBT).orElse(0.0D), 0.0D);
Optional<Double> devCost = context.getValue(CoreMetrics.NEW_DEVELOPMENT_COST);
if (devCost.isPresent() && Double.doubleToRawLongBits(devCost.get()) > 0L) {
return debt / devCost.get();
}
return 0.0D;
}
private static double effortToReachMaintainabilityRatingA(MeasureUpdateFormula.Context context) {
double developmentCost = context.getText(CoreMetrics.DEVELOPMENT_COST).map(Double::parseDouble).orElse(0.0D);
double effort = context.getValue(CoreMetrics.TECHNICAL_DEBT).orElse(0.0D);
double upperGradeCost = context.getDebtRatingGrid().getGradeLowerBound(Rating.B) * developmentCost;
return upperGradeCost < effort ? (effort - upperGradeCost) : 0.0D;
}
static class AddChildren implements BiConsumer<MeasureUpdateFormula.Context, MeasureUpdateFormula> {
@Override
public void accept(MeasureUpdateFormula.Context context, MeasureUpdateFormula formula) {
double sum = context.getChildrenValues().stream().mapToDouble(x -> x).sum();
context.setValue(context.getValue(formula.getMetric()).orElse(0D) + sum);
}
}
private static class MaxRatingChildren implements BiConsumer<MeasureUpdateFormula.Context, MeasureUpdateFormula> {
@Override
public void accept(MeasureUpdateFormula.Context context, MeasureUpdateFormula formula) {
OptionalInt max = context.getChildrenValues().stream().mapToInt(Double::intValue).max();
if (max.isPresent()) {
int currentRating = context.getValue(formula.getMetric()).map(Double::intValue).orElse(Rating.A.getIndex());
context.setValue(Rating.valueOf(Math.max(currentRating, max.getAsInt())));
}
}
}
@Override
public List<MeasureUpdateFormula> getFormulas() {
return FORMULAS;
}
@Override
public Set<Metric> getFormulaMetrics() {
return FORMULA_METRICS;
}
}
| 16,900 | 57.480969 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.measure.live;
import javax.annotation.ParametersAreNonnullByDefault;
| 969 | 39.416667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.measure.ws;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.metric.MetricDtoFunctions;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Measures;
import org.sonarqube.ws.Measures.ComponentWsResponse;
import static java.lang.String.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.sonar.server.component.ws.MeasuresWsParameters.ACTION_COMPONENT;
import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_METRICS;
import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_PERIOD;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_ADDITIONAL_FIELDS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_COMPONENT;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_KEYS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.measure.ws.ComponentDtoToWsComponent.componentDtoToWsComponent;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createAdditionalFieldsParameter;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createMetricKeysParameter;
import static org.sonar.server.measure.ws.MetricDtoToWsMetric.metricDtoToWsMetric;
import static org.sonar.server.measure.ws.SnapshotDtoToWsPeriod.snapshotToWsPeriods;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ComponentAction implements MeasuresWsAction {
private static final Set<String> QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE = ImmutableSortedSet.of(Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE);
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
public ComponentAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_COMPONENT)
.setDescription("Return component with specified measures.<br>" +
"Requires the following permission: 'Browse' on the project of specified component.")
.setResponseExample(getClass().getResource("component-example.json"))
.setSince("5.4")
.setChangelog(
new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)),
new Change("10.0", format("The use of the following metrics in 'metricKeys' parameter is not deprecated anymore: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("10.0", "the response field periods under measures field is removed."),
new Change("10.0", "the option `periods` of 'additionalFields' request field is removed."),
new Change("9.3", "When the new code period is set to 'reference branch', the response field 'date' under the 'period' field has been removed"),
new Change("9.3", format("The use of the following metrics in 'metricKeys' parameter is deprecated: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("8.8", "deprecated response field 'id' has been removed"),
new Change("8.8", "deprecated response field 'refId' has been removed."),
new Change("8.1", "the response field periods under measures field is deprecated. Use period instead."),
new Change("8.1", "the response field periods is deprecated. Use period instead."),
new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)),
new Change("6.6", "the response field 'id' is deprecated. Use 'key' instead."),
new Change("6.6", "the response field 'refId' is deprecated. Use 'refKey' instead."))
.setHandler(this);
action.createParam(PARAM_COMPONENT)
.setDescription("Component key")
.setRequired(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setDescription("Branch key. Not available in the community edition.")
.setExampleValue(KEY_BRANCH_EXAMPLE_001)
.setSince("6.6");
action.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id. Not available in the community edition.")
.setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001)
.setSince("7.1");
createMetricKeysParameter(action);
createAdditionalFieldsParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
ComponentWsResponse componentWsResponse = doHandle(toComponentWsRequest(request));
writeProtobuf(componentWsResponse, request, response);
}
private ComponentWsResponse doHandle(ComponentRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
String branch = request.getBranch();
String pullRequest = request.getPullRequest();
ComponentDto component = loadComponent(dbSession, request, branch, pullRequest);
checkPermissions(component);
SnapshotDto analysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, component.branchUuid()).orElse(null);
boolean isPR = isPR(pullRequest);
Set<String> metricKeysToRequest = new HashSet<>(request.metricKeys);
if (isPR) {
PrMeasureFix.addReplacementMetricKeys(metricKeysToRequest);
}
List<MetricDto> metrics = searchMetrics(dbSession, metricKeysToRequest);
List<LiveMeasureDto> measures = searchMeasures(dbSession, component, metrics);
Map<MetricDto, LiveMeasureDto> measuresByMetric = getMeasuresByMetric(measures, metrics);
if (isPR) {
Set<String> originalMetricKeys = new HashSet<>(request.metricKeys);
PrMeasureFix.createReplacementMeasures(metrics, measuresByMetric, originalMetricKeys);
PrMeasureFix.removeMetricsNotRequested(metrics, originalMetricKeys);
}
Optional<Measures.Period> period = snapshotToWsPeriods(analysis);
Optional<RefComponent> reference = getReference(dbSession, component);
return buildResponse(dbSession, request, component, reference, measuresByMetric, metrics, period);
}
}
public List<MetricDto> searchMetrics(DbSession dbSession, Collection<String> metricKeys) {
List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, metricKeys);
if (metrics.size() < metricKeys.size()) {
Set<String> foundMetricKeys = metrics.stream().map(MetricDto::getKey).collect(Collectors.toSet());
Set<String> missingMetricKeys = metricKeys.stream().filter(m -> !foundMetricKeys.contains(m)).collect(Collectors.toSet());
throw new NotFoundException(format("The following metric keys are not found: %s", String.join(", ", missingMetricKeys)));
}
return metrics;
}
private List<LiveMeasureDto> searchMeasures(DbSession dbSession, ComponentDto component, Collection<MetricDto> metrics) {
Set<String> metricUuids = metrics.stream().map(MetricDto::getUuid).collect(Collectors.toSet());
List<LiveMeasureDto> measures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, singletonList(component.uuid()), metricUuids);
addBestValuesToMeasures(measures, component, metrics);
return measures;
}
private static Map<MetricDto, LiveMeasureDto> getMeasuresByMetric(List<LiveMeasureDto> measures, Collection<MetricDto> metrics) {
Map<String, MetricDto> metricsByUuid = Maps.uniqueIndex(metrics, MetricDto::getUuid);
Map<MetricDto, LiveMeasureDto> measuresByMetric = new HashMap<>();
for (LiveMeasureDto measure : measures) {
MetricDto metric = metricsByUuid.get(measure.getMetricUuid());
measuresByMetric.put(metric, measure);
}
return measuresByMetric;
}
/**
* Conditions for best value measure:
* <ul>
* <li>component is a production file or test file</li>
* <li>metric is optimized for best value</li>
* </ul>
*/
private static void addBestValuesToMeasures(List<LiveMeasureDto> measures, ComponentDto component, Collection<MetricDto> metrics) {
if (!QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(component.qualifier())) {
return;
}
List<MetricDtoWithBestValue> metricWithBestValueList = metrics.stream()
.filter(MetricDtoFunctions.isOptimizedForBestValue())
.map(MetricDtoWithBestValue::new)
.toList();
Map<String, LiveMeasureDto> measuresByMetricUuid = Maps.uniqueIndex(measures, LiveMeasureDto::getMetricUuid);
for (MetricDtoWithBestValue metricWithBestValue : metricWithBestValueList) {
if (measuresByMetricUuid.get(metricWithBestValue.getMetric().getUuid()) == null) {
measures.add(metricWithBestValue.getBestValue());
}
}
}
private static boolean isPR(@Nullable String pullRequest) {
return pullRequest != null;
}
private ComponentDto loadComponent(DbSession dbSession, ComponentRequest request, @Nullable String branch, @Nullable String pullRequest) {
String componentKey = request.getComponent();
checkRequest(componentKey != null, "The '%s' parameter is missing", PARAM_COMPONENT);
return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
}
private Optional<RefComponent> getReference(DbSession dbSession, ComponentDto component) {
String copyComponentUuid = component.getCopyComponentUuid();
if (copyComponentUuid == null) {
return Optional.empty();
}
Optional<ComponentDto> refComponent = dbClient.componentDao().selectByUuid(dbSession, copyComponentUuid);
if (refComponent.isEmpty()) {
return Optional.empty();
}
Optional<BranchDto> refBranch = dbClient.branchDao().selectByUuid(dbSession, refComponent.get().branchUuid());
return refBranch.map(rb -> new RefComponent(rb, refComponent.get()));
}
private ComponentWsResponse buildResponse(DbSession dbSession, ComponentRequest request, ComponentDto component, Optional<RefComponent> reference,
Map<MetricDto, LiveMeasureDto> measuresByMetric, Collection<MetricDto> metrics, Optional<Measures.Period> period) {
ComponentWsResponse.Builder response = ComponentWsResponse.newBuilder();
if (reference.isPresent()) {
BranchDto refBranch = reference.get().getRefBranch();
ComponentDto refComponent = reference.get().getComponent();
response.setComponent(componentDtoToWsComponent(component, measuresByMetric, singletonMap(refComponent.uuid(), refComponent),
refBranch.isMain() ? null : refBranch.getBranchKey(), null));
} else {
boolean isMainBranch = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid()).map(BranchDto::isMain).orElse(true);
response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap(), isMainBranch ? null : request.getBranch(), request.getPullRequest()));
}
setAdditionalFields(request, metrics, period, response);
return response.build();
}
private static void setAdditionalFields(ComponentRequest request, Collection<MetricDto> metrics, Optional<Measures.Period> period, ComponentWsResponse.Builder response) {
List<String> additionalFields = request.getAdditionalFields();
if (additionalFields != null) {
if (additionalFields.contains(ADDITIONAL_METRICS)) {
for (MetricDto metric : metrics) {
response.getMetricsBuilder().addMetrics(metricDtoToWsMetric(metric));
}
}
if (additionalFields.contains(ADDITIONAL_PERIOD) && period.isPresent()) {
response.setPeriod(period.get());
}
}
}
private static ComponentRequest toComponentWsRequest(Request request) {
ComponentRequest componentRequest = new ComponentRequest()
.setComponent(request.mandatoryParam(PARAM_COMPONENT))
.setBranch(request.param(PARAM_BRANCH))
.setPullRequest(request.param(PARAM_PULL_REQUEST))
.setAdditionalFields(request.paramAsStrings(PARAM_ADDITIONAL_FIELDS))
.setMetricKeys(request.mandatoryParamAsStrings(PARAM_METRIC_KEYS));
checkRequest(!componentRequest.getMetricKeys().isEmpty(), "At least one metric key must be provided");
return componentRequest;
}
private void checkPermissions(ComponentDto baseComponent) {
userSession.checkComponentPermission(UserRole.USER, baseComponent);
}
private static class ComponentRequest {
private String component;
private String branch;
private String pullRequest;
private List<String> metricKeys;
private List<String> additionalFields;
private String getComponent() {
return component;
}
private ComponentRequest setComponent(@Nullable String component) {
this.component = component;
return this;
}
@CheckForNull
private String getBranch() {
return branch;
}
private ComponentRequest setBranch(@Nullable String branch) {
this.branch = branch;
return this;
}
@CheckForNull
public String getPullRequest() {
return pullRequest;
}
public ComponentRequest setPullRequest(@Nullable String pullRequest) {
this.pullRequest = pullRequest;
return this;
}
private List<String> getMetricKeys() {
return metricKeys;
}
private ComponentRequest setMetricKeys(@Nullable List<String> metricKeys) {
this.metricKeys = metricKeys;
return this;
}
@CheckForNull
private List<String> getAdditionalFields() {
return additionalFields;
}
private ComponentRequest setAdditionalFields(@Nullable List<String> additionalFields) {
this.additionalFields = additionalFields;
return this;
}
}
private static class RefComponent {
private final BranchDto refBranch;
private final ComponentDto component;
public RefComponent(BranchDto refBranch, ComponentDto component) {
this.refBranch = refBranch;
this.component = component;
}
public BranchDto getRefBranch() {
return refBranch;
}
public ComponentDto getComponent() {
return component;
}
}
}
| 16,424 | 43.034853 | 172 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.