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/qualityprofile/ws/QProfileWsAction.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.qualityprofile.ws; import org.sonar.server.ws.WsAction; /** * Marker interface for quality profile related web service end points */ public interface QProfileWsAction extends WsAction { // Marker interface }
1,083
33.967742
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/QProfileWsSupport.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.qualityprofile.ws; import java.util.Optional; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkState; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; @ServerSide public class QProfileWsSupport { private final DbClient dbClient; private final UserSession userSession; public QProfileWsSupport(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } public RuleDto getRule(DbSession dbSession, RuleKey ruleKey) { Optional<RuleDto> ruleDefinitionDto = dbClient.ruleDao().selectByKey(dbSession, ruleKey); RuleDto rule = checkFoundWithOptional(ruleDefinitionDto, "Rule with key '%s' not found", ruleKey); checkRequest(!rule.isExternal(), "Operation forbidden for rule '%s' imported from an external rule engine.", ruleKey); return rule; } /** * Get the Quality profile specified by the reference {@code ref}. * * @throws org.sonar.server.exceptions.NotFoundException if the specified profile do not exist */ public QProfileDto getProfile(DbSession dbSession, QProfileReference ref) { QProfileDto profile; if (ref.hasKey()) { profile = dbClient.qualityProfileDao().selectByUuid(dbSession, ref.getKey()); checkFound(profile, "Quality Profile with key '%s' does not exist", ref.getKey()); } else { profile = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, ref.getName(), ref.getLanguage()); checkFound(profile, "Quality Profile for language '%s' and name '%s' does not exist", ref.getLanguage(), ref.getName()); } return profile; } public QProfileDto getProfile(DbSession dbSession, String name, String language) { QProfileDto profile = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, name, language); checkFound(profile, "Quality Profile for language '%s' and name '%s' does not exist", language, name); return profile; } public UserDto getUser(DbSession dbSession, String login) { UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkFound(user, "User with login '%s' is not found'", login); return user; } GroupDto getGroup(DbSession dbSession, String groupName) { Optional<GroupDto> group = dbClient.groupDao().selectByName(dbSession, groupName); checkFoundWithOptional(group, "No group with name '%s'", groupName); return group.get(); } boolean canEdit(DbSession dbSession, QProfileDto profile) { if (canAdministrate(profile)) { return true; } UserDto user = dbClient.userDao().selectByLogin(dbSession, userSession.getLogin()); checkState(user != null, "User from session does not exist"); return dbClient.qProfileEditUsersDao().exists(dbSession, profile, user) || dbClient.qProfileEditGroupsDao().exists(dbSession, profile, userSession.getGroups()); } boolean canAdministrate(QProfileDto profile) { if (profile.isBuiltIn() || !userSession.isLoggedIn()) { return false; } return userSession.hasPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); } public void checkCanEdit(DbSession dbSession, QProfileDto profile) { checkNotBuiltIn(profile); if (!canEdit(dbSession, profile)) { throw insufficientPrivilegesException(); } } public void checkCanAdministrate(QProfileDto profile) { checkNotBuiltIn(profile); if (!canAdministrate(profile)) { throw insufficientPrivilegesException(); } } void checkNotBuiltIn(QProfileDto profile) { checkRequest(!profile.isBuiltIn(), "Operation forbidden for built-in Quality Profile '%s' with language '%s'", profile.getName(), profile.getLanguage()); } }
5,197
39.609375
157
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/QProfilesWs.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.qualityprofile.ws; import org.sonar.api.server.ws.WebService; import static java.util.Arrays.stream; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.CONTROLLER_QUALITY_PROFILES; public class QProfilesWs implements WebService { public static final String API_ENDPOINT = CONTROLLER_QUALITY_PROFILES; private final QProfileWsAction[] actions; public QProfilesWs(QProfileWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(API_ENDPOINT) .setDescription("Manage quality profiles.") .setSince("4.4"); stream(actions) .forEach(action -> action.define(controller)); controller.done(); } }
1,635
32.387755
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/QProfilesWsModule.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.qualityprofile.ws; import org.sonar.core.platform.Module; public class QProfilesWsModule extends Module { @Override protected void configureModule() { add( AddProjectAction.class, AddGroupAction.class, AddUserAction.class, BackupAction.class, ActivateRulesAction.class, DeactivateRulesAction.class, CompareAction.class, CopyAction.class, ChangelogAction.class, ChangeParentAction.class, CreateAction.class, DeleteAction.class, ExportAction.class, ExportersAction.class, ImportersAction.class, InheritanceAction.class, QProfilesWs.class, QProfileWsSupport.class, ProjectsAction.class, RenameAction.class, RemoveProjectAction.class, RemoveGroupAction.class, RemoveUserAction.class, RestoreAction.class, ActivateRuleAction.class, DeactivateRuleAction.class, SearchAction.class, SearchGroupsAction.class, SearchUsersAction.class, SetDefaultAction.class, ShowAction.class ); } }
1,944
30.370968
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/RemoveGroupAction.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.qualityprofile.ws; import java.util.Arrays; import java.util.stream.Collectors; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.user.GroupDto; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_REMOVE_GROUP; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; public class RemoveGroupAction implements QProfileWsAction { private final DbClient dbClient; private final QProfileWsSupport wsSupport; private final Languages languages; public RemoveGroupAction(DbClient dbClient, QProfileWsSupport wsSupport, Languages languages) { this.dbClient = dbClient; this.wsSupport = wsSupport; this.languages = languages; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction(ACTION_REMOVE_GROUP) .setDescription("Remove the ability from a group to edit a Quality Profile.<br>" + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + "</ul>") .setHandler(this) .setPost(true) .setInternal(true) .setSince("6.6"); action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality Profile name") .setRequired(true) .setExampleValue("Recommended quality profile"); action .createParam(PARAM_LANGUAGE) .setDescription("Quality profile language") .setRequired(true) .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet())); action.createParam(PARAM_GROUP) .setDescription("Group name") .setRequired(true) .setExampleValue("sonar-administrators"); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = wsSupport.getProfile(dbSession, request.mandatoryParam(PARAM_QUALITY_PROFILE), request.mandatoryParam(PARAM_LANGUAGE)); wsSupport.checkCanEdit(dbSession, profile); GroupDto group = wsSupport.getGroup(dbSession, request.mandatoryParam(PARAM_GROUP)); removeGroup(dbSession, profile, group); } response.noContent(); } private void removeGroup(DbSession dbSession, QProfileDto profile, GroupDto group) { if (!dbClient.qProfileEditGroupsDao().exists(dbSession, profile, group)) { return; } dbClient.qProfileEditGroupsDao().deleteByQProfileAndGroup(dbSession, profile, group); dbSession.commit(); } }
3,998
38.205882
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/RemoveProjectAction.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.qualityprofile.ws; 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.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.user.UserSession; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_REMOVE_PROJECT; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PROJECT; public class RemoveProjectAction implements QProfileWsAction { private final DbClient dbClient; private final UserSession userSession; private final Languages languages; private final ComponentFinder componentFinder; private final QProfileWsSupport wsSupport; private final QualityProfileChangeEventService qualityProfileChangeEventService; public RemoveProjectAction(DbClient dbClient, UserSession userSession, Languages languages, ComponentFinder componentFinder, QProfileWsSupport wsSupport, QualityProfileChangeEventService qualityProfileChangeEventService) { this.dbClient = dbClient; this.userSession = userSession; this.languages = languages; this.componentFinder = componentFinder; this.wsSupport = wsSupport; this.qualityProfileChangeEventService = qualityProfileChangeEventService; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction(ACTION_REMOVE_PROJECT) .setSince("5.2") .setDescription("Remove a project's association with a quality profile.<br> " + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + " <li>Administer right on the specified project</li>" + "</ul>") .setPost(true) .setHandler(this); QProfileReference.defineParams(action, languages); 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.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = loadProject(dbSession, request); QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromName(request)); checkPermissions(profile, project); dbClient.qualityProfileDao().deleteProjectProfileAssociation(dbSession, project, profile); dbSession.commit(); QProfileDto activatedProfile = null; // publish change for rules in the default quality profile QProfileDto defaultProfile = dbClient.qualityProfileDao().selectDefaultProfile(dbSession, profile.getLanguage()); if (defaultProfile != null) { activatedProfile = defaultProfile; } qualityProfileChangeEventService.publishRuleActivationToSonarLintClients(project, activatedProfile, profile); response.noContent(); } } private ProjectDto loadProject(DbSession dbSession, Request request) { String projectKey = request.mandatoryParam(PARAM_PROJECT); return componentFinder.getProjectByKey(dbSession, projectKey); } private void checkPermissions(QProfileDto profile, ProjectDto project) { if (wsSupport.canAdministrate(profile) || userSession.hasEntityPermission(UserRole.ADMIN, project)) { return; } throw insufficientPrivilegesException(); } }
4,890
39.758333
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/RemoveUserAction.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.qualityprofile.ws; import java.util.Arrays; import java.util.stream.Collectors; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.user.UserDto; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_REMOVE_USER; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; public class RemoveUserAction implements QProfileWsAction { private final DbClient dbClient; private final QProfileWsSupport wsSupport; private final Languages languages; public RemoveUserAction(DbClient dbClient, QProfileWsSupport wsSupport, Languages languages) { this.dbClient = dbClient; this.wsSupport = wsSupport; this.languages = languages; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction(ACTION_REMOVE_USER) .setDescription("Remove the ability from a user to edit a Quality Profile.<br>" + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + "</ul>") .setHandler(this) .setPost(true) .setInternal(true) .setSince("6.6"); action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality Profile name") .setRequired(true) .setExampleValue("Recommended quality profile"); action .createParam(PARAM_LANGUAGE) .setDescription("Quality profile language") .setRequired(true) .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet())); action.createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true) .setExampleValue("john.doe"); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = wsSupport.getProfile(dbSession, request.mandatoryParam(PARAM_QUALITY_PROFILE), request.mandatoryParam(PARAM_LANGUAGE)); wsSupport.checkCanEdit(dbSession, profile); UserDto user = wsSupport.getUser(dbSession, request.mandatoryParam(PARAM_LOGIN)); removeUser(dbSession, profile, user); } response.noContent(); } private void removeUser(DbSession dbSession, QProfileDto profile, UserDto user) { if (!dbClient.qProfileEditUsersDao().exists(dbSession, profile, user)) { return; } dbClient.qProfileEditUsersDao().deleteByQProfileAndUser(dbSession, profile, user); dbSession.commit(); } }
3,967
37.901961
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/RenameAction.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.qualityprofile.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.server.ws.WebService.NewAction; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Optional.ofNullable; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.qualityprofile.ws.CreateAction.NAME_MAXIMUM_LENGTH; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_NAME; public class RenameAction implements QProfileWsAction { private static final int MAXIMUM_NAME_LENGTH = 100; private final DbClient dbClient; private final UserSession userSession; private final QProfileWsSupport wsSupport; public RenameAction(DbClient dbClient, UserSession userSession, QProfileWsSupport wsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.wsSupport = wsSupport; } @Override public void define(WebService.NewController controller) { NewAction setDefault = controller.createAction("rename") .setPost(true) .setDescription("Rename a quality profile.<br> " + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + "</ul>") .setSince("5.2") .setHandler(this); setDefault.createParam(PARAM_KEY) .setRequired(true) .setDescription("Quality profile key") .setExampleValue(UUID_EXAMPLE_01); setDefault.createParam(PARAM_NAME) .setRequired(true) .setMaximumLength(NAME_MAXIMUM_LENGTH) .setDescription("New quality profile name") .setExampleValue("My Sonar way"); } @Override public void handle(Request request, Response response) throws Exception { String newName = request.mandatoryParam(PARAM_NAME); String profileKey = request.mandatoryParam(PARAM_KEY); doHandle(newName, profileKey); response.noContent(); } private void doHandle(String newName, String profileKey) { checkRequest(newName.length() <= MAXIMUM_NAME_LENGTH, "Name is too long (>%d characters)", MAXIMUM_NAME_LENGTH); userSession.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto qualityProfile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(profileKey)); wsSupport.checkCanEdit(dbSession, qualityProfile); if (newName.equals(qualityProfile.getName())) { return; } String language = qualityProfile.getLanguage(); ofNullable(dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, newName, language)) .ifPresent(found -> { throw BadRequestException.create(format("Quality profile already exists: %s", newName)); }); qualityProfile.setName(newName); dbClient.qualityProfileDao().update(dbSession, qualityProfile); dbSession.commit(); } } }
4,247
36.928571
116
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/RestoreAction.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.qualityprofile.ws; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.commons.io.IOUtils; 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.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.qualityprofile.BulkChangeResult; import org.sonar.server.qualityprofile.QProfileBackuper; import org.sonar.server.qualityprofile.QProfileRestoreSummary; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.RestoreActionParameters.PARAM_BACKUP; public class RestoreAction implements QProfileWsAction { private final DbClient dbClient; private final QProfileBackuper backuper; private final Languages languages; private final UserSession userSession; public RestoreAction(DbClient dbClient, QProfileBackuper backuper, Languages languages, UserSession userSession) { this.dbClient = dbClient; this.backuper = backuper; this.languages = languages; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("restore") .setSince("5.2") .setDescription("Restore a quality profile using an XML file. The restored profile name is taken from the backup file, " + "so if a profile with the same name and language already exists, it will be overwritten.<br> " + "Requires to be logged in and the 'Administer Quality Profiles' permission.") .setPost(true) .setHandler(this); action.createParam(PARAM_BACKUP) .setDescription("A profile backup file in XML format, as generated by api/qualityprofiles/backup " + "or the former api/profiles/backup.") .setRequired(true); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); InputStream backup = request.paramAsInputStream(PARAM_BACKUP); checkArgument(backup != null, "A backup file must be provided"); InputStreamReader reader = null; try (DbSession dbSession = dbClient.openSession(false)) { reader = new InputStreamReader(backup, UTF_8); userSession.checkPermission(ADMINISTER_QUALITY_PROFILES); QProfileRestoreSummary summary = backuper.restore(dbSession, reader, (String) null); writeResponse(response.newJsonWriter(), summary); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(backup); } } private void writeResponse(JsonWriter json, QProfileRestoreSummary summary) { QProfileDto profile = summary.profile(); String languageKey = profile.getLanguage(); Language language = languages.get(languageKey); JsonWriter jsonProfile = json.beginObject().name("profile").beginObject(); jsonProfile .prop("key", profile.getKee()) .prop("name", profile.getName()) .prop("language", languageKey) .prop("isDefault", false) .prop("isInherited", false); if (language != null) { jsonProfile.prop("languageName", language.getName()); } jsonProfile.endObject(); BulkChangeResult ruleChanges = summary.ruleChanges(); json.prop("ruleSuccesses", ruleChanges.countSucceeded()); json.prop("ruleFailures", ruleChanges.countFailed()); json.endObject().close(); } }
4,670
38.923077
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/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.qualityprofile.ws; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; 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.project.ProjectDto; import org.sonar.db.qualityprofile.ActiveRuleCountQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.language.LanguageParamUtils; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Qualityprofiles.SearchWsResponse; import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Optional.ofNullable; import static java.util.function.Function.identity; import static org.sonar.api.rule.RuleStatus.DEPRECATED; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_SEARCH; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_DEFAULTS; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PROJECT; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; public class SearchAction implements QProfileWsAction { private static final Comparator<QProfileDto> Q_PROFILE_COMPARATOR = Comparator .comparing(QProfileDto::getLanguage) .thenComparing(QProfileDto::getName); private final UserSession userSession; private final Languages languages; private final DbClient dbClient; private final ComponentFinder componentFinder; public SearchAction(UserSession userSession, Languages languages, DbClient dbClient, ComponentFinder componentFinder) { this.userSession = userSession; this.languages = languages; this.dbClient = dbClient; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction(ACTION_SEARCH) .setSince("5.2") .setDescription("Search quality profiles") .setHandler(this) .setChangelog( new Change("6.5", format("The parameters '%s', '%s' and '%s' can be combined without any constraint", PARAM_DEFAULTS, PARAM_PROJECT, PARAM_LANGUAGE)), new Change("6.6", "Add available actions 'edit', 'copy' and 'setAsDefault' and global action 'create'"), new Change("7.0", "Add available actions 'delete' and 'associateProjects'"), new Change("10.0", "Remove deprecated parameter 'project_key'. Please use 'project' instead.")) .setResponseExample(getClass().getResource("search-example.json")); action .createParam(PARAM_DEFAULTS) .setDescription("If set to true, return only the quality profiles marked as default for each language") .setDefaultValue(false) .setBooleanPossibleValues(); action.createParam(PARAM_PROJECT) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001); action .createParam(PARAM_LANGUAGE) .setDescription("Language key. If provided, only profiles for the given language are returned.") .setPossibleValues(LanguageParamUtils.getOrderedLanguageKeys(languages)); action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality profile name") .setExampleValue("SonarQube Way"); } @Override public void handle(Request request, Response response) throws Exception { SearchWsResponse searchWsResponse = doHandle(toSearchWsRequest(request)); writeProtobuf(searchWsResponse, request, response); } private static SearchRequest toSearchWsRequest(Request request) { return new SearchRequest() .setProjectKey(request.param(PARAM_PROJECT)) .setQualityProfile(request.param(PARAM_QUALITY_PROFILE)) .setDefaults(request.paramAsBoolean(PARAM_DEFAULTS)) .setLanguage(request.param(PARAM_LANGUAGE)); } private SearchWsResponse doHandle(SearchRequest request) { SearchData data = load(request); return buildResponse(data); } private SearchData load(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = findProject(dbSession, request); List<QProfileDto> defaultProfiles = dbClient.qualityProfileDao().selectDefaultProfiles(dbSession, getLanguageKeys()); List<String> editableProfiles = searchEditableProfiles(dbSession); List<QProfileDto> profiles = searchProfiles(dbSession, request, defaultProfiles, project); ActiveRuleCountQuery.Builder builder = ActiveRuleCountQuery.builder(); return new SearchData() .setProfiles(profiles) .setActiveRuleCountByProfileKey( dbClient.activeRuleDao().countActiveRulesByQuery(dbSession, builder.setProfiles(profiles).build())) .setActiveDeprecatedRuleCountByProfileKey( dbClient.activeRuleDao().countActiveRulesByQuery(dbSession, builder.setProfiles(profiles).setRuleStatus(DEPRECATED).build())) .setProjectCountByProfileKey(dbClient.qualityProfileDao().countProjectsByProfiles(dbSession, profiles)) .setDefaultProfileKeys(defaultProfiles) .setEditableProfileKeys(editableProfiles); } } @CheckForNull private ProjectDto findProject(DbSession dbSession, SearchRequest request) { if (request.getProjectKey() == null) { return null; } return componentFinder.getProjectByKey(dbSession, request.getProjectKey()); } private List<String> searchEditableProfiles(DbSession dbSession) { if (!userSession.isLoggedIn()) { return emptyList(); } String login = userSession.getLogin(); UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkState(user != null, "User with login '%s' is not found'", login); return Stream.concat( dbClient.qProfileEditUsersDao().selectQProfileUuidsByUser(dbSession, user).stream(), dbClient.qProfileEditGroupsDao().selectQProfileUuidsByGroups(dbSession, userSession.getGroups()).stream()) .toList(); } private List<QProfileDto> searchProfiles(DbSession dbSession, SearchRequest request, List<QProfileDto> defaultProfiles, @Nullable ProjectDto project) { Collection<QProfileDto> profiles = selectAllProfiles(dbSession); return profiles.stream() .filter(hasLanguagePlugin()) .filter(byLanguage(request)) .filter(byName(request)) .filter(byDefault(request, defaultProfiles)) .filter(byProject(dbSession, project, defaultProfiles)) .sorted(Q_PROFILE_COMPARATOR) .toList(); } private Predicate<QProfileDto> hasLanguagePlugin() { return p -> languages.get(p.getLanguage()) != null; } private static Predicate<QProfileDto> byName(SearchRequest request) { return p -> request.getQualityProfile() == null || Objects.equals(p.getName(), request.getQualityProfile()); } private static Predicate<QProfileDto> byLanguage(SearchRequest request) { return p -> request.getLanguage() == null || Objects.equals(p.getLanguage(), request.getLanguage()); } private static Predicate<QProfileDto> byDefault(SearchRequest request, List<QProfileDto> defaultProfiles) { Set<String> defaultProfileUuids = defaultProfiles.stream().map(QProfileDto::getKee).collect(Collectors.toSet()); return p -> !request.getDefaults() || defaultProfileUuids.contains(p.getKee()); } private Predicate<QProfileDto> byProject(DbSession dbSession, @Nullable ProjectDto project, List<QProfileDto> defaultProfiles) { if (project == null) { return p -> true; } Map<String, QProfileDto> effectiveProfiles = defaultProfiles.stream().collect(Collectors.toMap(QProfileDto::getLanguage, identity())); effectiveProfiles.putAll(dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguages(dbSession, project, getLanguageKeys()).stream() .collect(Collectors.toMap(QProfileDto::getLanguage, identity()))); return p -> Objects.equals(p.getKee(), effectiveProfiles.get(p.getLanguage()).getKee()); } private Collection<QProfileDto> selectAllProfiles(DbSession dbSession) { return dbClient.qualityProfileDao().selectAll(dbSession); } private Set<String> getLanguageKeys() { return Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet()); } private SearchWsResponse buildResponse(SearchData data) { List<QProfileDto> profiles = data.getProfiles(); Map<String, QProfileDto> profilesByKey = profiles.stream().collect(Collectors.toMap(QProfileDto::getKee, identity())); boolean isGlobalQProfileAdmin = userSession.hasPermission(ADMINISTER_QUALITY_PROFILES); SearchWsResponse.Builder response = SearchWsResponse.newBuilder(); response.setActions(SearchWsResponse.Actions.newBuilder().setCreate(isGlobalQProfileAdmin)); for (QProfileDto profile : profiles) { QualityProfile.Builder profileBuilder = response.addProfilesBuilder(); String profileKey = profile.getKee(); profileBuilder.setKey(profileKey); ofNullable(profile.getName()).ifPresent(profileBuilder::setName); ofNullable(profile.getRulesUpdatedAt()).ifPresent(profileBuilder::setRulesUpdatedAt); ofNullable(profile.getLastUsed()).ifPresent(last -> profileBuilder.setLastUsed(formatDateTime(last))); ofNullable(profile.getUserUpdatedAt()).ifPresent(userUpdatedAt -> profileBuilder.setUserUpdatedAt(formatDateTime(userUpdatedAt))); profileBuilder.setActiveRuleCount(data.getActiveRuleCount(profileKey)); profileBuilder.setActiveDeprecatedRuleCount(data.getActiveDeprecatedRuleCount(profileKey)); boolean isDefault = data.isDefault(profile); profileBuilder.setIsDefault(isDefault); if (!isDefault) { profileBuilder.setProjectCount(data.getProjectCount(profileKey)); } writeLanguageFields(profileBuilder, profile); writeParentFields(profileBuilder, profile, profilesByKey); profileBuilder.setIsInherited(profile.getParentKee() != null); profileBuilder.setIsBuiltIn(profile.isBuiltIn()); profileBuilder.setActions(SearchWsResponse.QualityProfile.Actions.newBuilder() .setEdit(!profile.isBuiltIn() && (isGlobalQProfileAdmin || data.isEditable(profile))) .setSetAsDefault(!isDefault && isGlobalQProfileAdmin) .setCopy(isGlobalQProfileAdmin) .setDelete(!isDefault && !profile.isBuiltIn() && isGlobalQProfileAdmin) .setAssociateProjects(!isDefault && isGlobalQProfileAdmin)); } return response.build(); } private void writeLanguageFields(QualityProfile.Builder profileBuilder, QProfileDto profile) { String languageKey = profile.getLanguage(); if (languageKey == null) { return; } profileBuilder.setLanguage(languageKey); String languageName = languages.get(languageKey).getName(); if (languageName != null) { profileBuilder.setLanguageName(languageName); } } private static void writeParentFields(QualityProfile.Builder profileBuilder, QProfileDto profile, Map<String, QProfileDto> profilesByKey) { String parentKey = profile.getParentKee(); if (parentKey == null) { return; } profileBuilder.setParentKey(parentKey); QProfileDto parent = profilesByKey.get(parentKey); if (parent != null && parent.getName() != null) { profileBuilder.setParentName(parent.getName()); } } private static class SearchRequest { private boolean defaults; private String language; private String qualityProfile; private String projectKey; public boolean getDefaults() { return defaults; } public SearchRequest setDefaults(boolean defaults) { this.defaults = defaults; return this; } @CheckForNull public String getLanguage() { return language; } public SearchRequest setLanguage(@Nullable String language) { this.language = language; return this; } @CheckForNull public String getQualityProfile() { return qualityProfile; } public SearchRequest setQualityProfile(@Nullable String qualityProfile) { this.qualityProfile = qualityProfile; return this; } @CheckForNull public String getProjectKey() { return projectKey; } public SearchRequest setProjectKey(@Nullable String projectKey) { this.projectKey = projectKey; return this; } } }
14,307
40.836257
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/SearchData.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.qualityprofile.ws; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.sonar.db.qualityprofile.QProfileDto; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.ImmutableMap.copyOf; class SearchData { private List<QProfileDto> profiles; private Map<String, Long> activeRuleCountByProfileKey; private Map<String, Long> activeDeprecatedRuleCountByProfileKey; private Map<String, Long> projectCountByProfileKey; private Set<String> defaultProfileKeys; private Set<String> editableProfileKeys; List<QProfileDto> getProfiles() { return profiles; } SearchData setProfiles(List<QProfileDto> profiles) { this.profiles = copyOf(profiles); return this; } SearchData setActiveRuleCountByProfileKey(Map<String, Long> activeRuleCountByProfileKey) { this.activeRuleCountByProfileKey = copyOf(activeRuleCountByProfileKey); return this; } SearchData setActiveDeprecatedRuleCountByProfileKey(Map<String, Long> activeDeprecatedRuleCountByProfileKey) { this.activeDeprecatedRuleCountByProfileKey = activeDeprecatedRuleCountByProfileKey; return this; } SearchData setProjectCountByProfileKey(Map<String, Long> projectCountByProfileKey) { this.projectCountByProfileKey = copyOf(projectCountByProfileKey); return this; } long getActiveRuleCount(String profileKey) { return firstNonNull(activeRuleCountByProfileKey.get(profileKey), 0L); } long getProjectCount(String profileKey) { return firstNonNull(projectCountByProfileKey.get(profileKey), 0L); } long getActiveDeprecatedRuleCount(String profileKey) { return firstNonNull(activeDeprecatedRuleCountByProfileKey.get(profileKey), 0L); } boolean isDefault(QProfileDto profile) { return defaultProfileKeys.contains(profile.getKee()); } SearchData setDefaultProfileKeys(List<QProfileDto> s) { this.defaultProfileKeys = s.stream().map(QProfileDto::getKee).collect(Collectors.toSet()); return this; } boolean isEditable(QProfileDto profile) { return editableProfileKeys.contains(profile.getKee()); } SearchData setEditableProfileKeys(List<String> editableProfileKeys) { this.editableProfileKeys = new HashSet<>(editableProfileKeys); return this; } }
3,288
33.260417
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/SearchGroupsAction.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.qualityprofile.ws; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery; import org.sonar.db.user.GroupDto; import org.sonar.db.user.SearchGroupMembershipDto; import org.sonarqube.ws.Common; import org.sonarqube.ws.Qualityprofiles; import static java.util.Optional.ofNullable; 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.server.ws.WebService.Param.SELECTED; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.server.ws.WebService.SelectionMode.ALL; import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED; import static org.sonar.api.server.ws.WebService.SelectionMode.fromParam; import static org.sonar.db.Pagination.forPage; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.ANY; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.IN; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.OUT; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.builder; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_SEARCH_GROUPS; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; public class SearchGroupsAction implements QProfileWsAction { private static final Map<WebService.SelectionMode, String> MEMBERSHIP = Map.of(WebService.SelectionMode.SELECTED, IN, DESELECTED, OUT, ALL, ANY); private final DbClient dbClient; private final QProfileWsSupport wsSupport; private final Languages languages; public SearchGroupsAction(DbClient dbClient, QProfileWsSupport wsSupport, Languages languages) { this.dbClient = dbClient; this.wsSupport = wsSupport; this.languages = languages; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction(ACTION_SEARCH_GROUPS) .setDescription("List the groups that are allowed to edit a Quality Profile.<br>" + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + "</ul>") .setHandler(this) .setInternal(true) .addSelectionModeParam() .addSearchQuery("sonar", "group names") .addPagingParams(25) .setResponseExample(getClass().getResource("search_groups-example.json")) .setSince("6.6"); action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality Profile name") .setRequired(true) .setExampleValue("Recommended quality profile"); action .createParam(PARAM_LANGUAGE) .setDescription("Quality profile language") .setRequired(true) .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet())); } @Override public void handle(Request request, Response response) throws Exception { SearchQualityProfileUsersRequest wsRequest = buildRequest(request); try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = wsSupport.getProfile(dbSession, wsRequest.getQualityProfile(), wsRequest.getLanguage()); wsSupport.checkCanEdit(dbSession, profile); SearchQualityProfilePermissionQuery query = builder() .setProfile(profile) .setQuery(wsRequest.getQuery()) .setMembership(MEMBERSHIP.get(fromParam(wsRequest.getSelected()))) .build(); int total = dbClient.qProfileEditGroupsDao().countByQuery(dbSession, query); List<SearchGroupMembershipDto> groupMemberships = dbClient.qProfileEditGroupsDao().selectByQuery(dbSession, query, forPage(wsRequest.getPage()).andSize(wsRequest.getPageSize())); Map<String, GroupDto> groupsByUuid = dbClient.groupDao().selectByUuids(dbSession, groupMemberships.stream().map(SearchGroupMembershipDto::getGroupUuid).toList()) .stream() .collect(Collectors.toMap(GroupDto::getUuid, Function.identity())); writeProtobuf( Qualityprofiles.SearchGroupsResponse.newBuilder() .addAllGroups(groupMemberships.stream() .map(groupsMembership -> toGroup(groupsByUuid.get(groupsMembership.getGroupUuid()), groupsMembership.isSelected())) .toList()) .setPaging(buildPaging(wsRequest, total)).build(), request, response); } } private static SearchQualityProfileUsersRequest buildRequest(Request request) { return SearchQualityProfileUsersRequest.builder() .setQualityProfile(request.mandatoryParam(PARAM_QUALITY_PROFILE)) .setLanguage(request.mandatoryParam(PARAM_LANGUAGE)) .setQuery(request.param(TEXT_QUERY)) .setSelected(request.mandatoryParam(SELECTED)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(request.mandatoryParamAsInt(PAGE_SIZE)) .build(); } private static Qualityprofiles.SearchGroupsResponse.Group toGroup(GroupDto group, boolean isSelected) { Qualityprofiles.SearchGroupsResponse.Group.Builder builder = Qualityprofiles.SearchGroupsResponse.Group.newBuilder() .setName(group.getName()) .setSelected(isSelected); ofNullable(group.getDescription()).ifPresent(builder::setDescription); return builder.build(); } private static Common.Paging buildPaging(SearchQualityProfileUsersRequest wsRequest, int total) { return Common.Paging.newBuilder() .setPageIndex(wsRequest.getPage()) .setPageSize(wsRequest.getPageSize()) .setTotal(total) .build(); } }
7,183
44.18239
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/SearchQualityProfileUsersRequest.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.qualityprofile.ws; import org.sonar.server.user.ws.SearchUsersRequest; class SearchQualityProfileUsersRequest extends SearchUsersRequest { private String qualityProfile; private String language; private SearchQualityProfileUsersRequest(Builder builder) { this.qualityProfile = builder.qualityProfile; this.language = builder.language; this.selected = builder.getSelected(); this.query = builder.getQuery(); this.page = builder.getPage(); this.pageSize = builder.getPageSize(); } public String getQualityProfile() { return qualityProfile; } public String getLanguage() { return language; } public static Builder builder() { return new Builder(); } public static class Builder extends SearchUsersRequest.Builder<Builder> { private String qualityProfile; private String language; public Builder setQualityProfile(String qualityProfile) { this.qualityProfile = qualityProfile; return this; } public Builder setLanguage(String language) { this.language = language; return this; } public SearchQualityProfileUsersRequest build() { return new SearchQualityProfileUsersRequest(this); } } }
2,082
29.632353
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/SearchUsersAction.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.qualityprofile.ws; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; 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.SelectionMode; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery; import org.sonar.db.user.SearchUserMembershipDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.AvatarResolver; import org.sonarqube.ws.Common; import org.sonarqube.ws.Qualityprofiles.SearchUsersResponse; import static com.google.common.base.Strings.emptyToNull; import static java.util.Optional.ofNullable; 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.server.ws.WebService.Param.SELECTED; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.server.ws.WebService.SelectionMode.ALL; import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED; import static org.sonar.api.server.ws.WebService.SelectionMode.fromParam; import static org.sonar.db.Pagination.forPage; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.ANY; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.IN; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.OUT; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.builder; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_SEARCH_USERS; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; public class SearchUsersAction implements QProfileWsAction { private static final Map<SelectionMode, String> MEMBERSHIP = ImmutableMap.of(SelectionMode.SELECTED, IN, DESELECTED, OUT, ALL, ANY); private final DbClient dbClient; private final QProfileWsSupport wsSupport; private final Languages languages; private final AvatarResolver avatarResolver; public SearchUsersAction(DbClient dbClient, QProfileWsSupport wsSupport, Languages languages, AvatarResolver avatarResolver) { this.dbClient = dbClient; this.wsSupport = wsSupport; this.languages = languages; this.avatarResolver = avatarResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction(ACTION_SEARCH_USERS) .setDescription("List the users that are allowed to edit a Quality Profile.<br>" + "Requires one of the following permissions:" + "<ul>" + " <li>'Administer Quality Profiles'</li>" + " <li>Edit right on the specified quality profile</li>" + "</ul>") .setHandler(this) .setInternal(true) .addSearchQuery("freddy", "names", "logins") .addSelectionModeParam() .addPagingParams(25) .setResponseExample(getClass().getResource("search_users-example.json")) .setSince("6.6"); action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality Profile name") .setRequired(true) .setExampleValue("Recommended quality profile"); action .createParam(PARAM_LANGUAGE) .setDescription("Quality profile language") .setRequired(true) .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet())); } @Override public void handle(Request request, Response response) throws Exception { SearchQualityProfileUsersRequest wsRequest = buildRequest(request); try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = wsSupport.getProfile(dbSession, wsRequest.getQualityProfile(), wsRequest.getLanguage()); wsSupport.checkCanEdit(dbSession, profile); SearchQualityProfilePermissionQuery query = builder() .setProfile(profile) .setQuery(wsRequest.getQuery()) .setMembership(MEMBERSHIP.get(fromParam(wsRequest.getSelected()))) .build(); int total = dbClient.qProfileEditUsersDao().countByQuery(dbSession, query); List<SearchUserMembershipDto> usersMembership = dbClient.qProfileEditUsersDao().selectByQuery(dbSession, query, forPage(wsRequest.getPage()).andSize(wsRequest.getPageSize())); Map<String, UserDto> usersById = dbClient.userDao().selectByUuids(dbSession, usersMembership.stream().map(SearchUserMembershipDto::getUserUuid).toList()) .stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity())); writeProtobuf( SearchUsersResponse.newBuilder() .addAllUsers(usersMembership.stream() .map(userMembershipDto -> toUser(usersById.get(userMembershipDto.getUserUuid()), userMembershipDto.isSelected())) .toList()) .setPaging(buildPaging(wsRequest, total)).build(), request, response); } } private static SearchQualityProfileUsersRequest buildRequest(Request request) { return SearchQualityProfileUsersRequest.builder() .setQualityProfile(request.mandatoryParam(PARAM_QUALITY_PROFILE)) .setLanguage(request.mandatoryParam(PARAM_LANGUAGE)) .setQuery(request.param(TEXT_QUERY)) .setSelected(request.mandatoryParam(SELECTED)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(request.mandatoryParamAsInt(PAGE_SIZE)) .build(); } private SearchUsersResponse.User toUser(UserDto user, boolean isSelected) { SearchUsersResponse.User.Builder builder = SearchUsersResponse.User.newBuilder() .setLogin(user.getLogin()) .setSelected(isSelected); ofNullable(user.getName()).ifPresent(builder::setName); ofNullable(emptyToNull(user.getEmail())).ifPresent(e -> builder.setAvatar(avatarResolver.create(user))); return builder .build(); } private static Common.Paging buildPaging(SearchQualityProfileUsersRequest wsRequest, int total) { return Common.Paging.newBuilder() .setPageIndex(wsRequest.getPage()) .setPageSize(wsRequest.getPageSize()) .setTotal(total) .build(); } }
7,503
44.204819
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/SetDefaultAction.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.qualityprofile.ws; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.DefaultQProfileDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.user.UserSession; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_SET_DEFAULT; public class SetDefaultAction implements QProfileWsAction { private final Languages languages; private final DbClient dbClient; private final UserSession userSession; private final QProfileWsSupport qProfileWsSupport; public SetDefaultAction(Languages languages, DbClient dbClient, UserSession userSession, QProfileWsSupport qProfileWsSupport) { this.languages = languages; this.dbClient = dbClient; this.userSession = userSession; this.qProfileWsSupport = qProfileWsSupport; } @Override public void define(WebService.NewController controller) { NewAction setDefault = controller.createAction(ACTION_SET_DEFAULT) .setSince("5.2") .setDescription("Select the default profile for a given language.<br> " + "Requires to be logged in and the 'Administer Quality Profiles' permission.") .setPost(true) .setHandler(this); QProfileReference.defineParams(setDefault, languages); } @Override public void handle(Request request, Response response) { userSession.checkLoggedIn(); QProfileReference reference = QProfileReference.fromName(request); try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto qualityProfile = qProfileWsSupport.getProfile(dbSession, reference); userSession.checkPermission(ADMINISTER_QUALITY_PROFILES); dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(qualityProfile)); dbSession.commit(); } response.noContent(); } }
3,008
38.592105
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/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.qualityprofile.ws; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import javax.annotation.CheckForNull; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleCountQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.es.SearchOptions; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.rule.index.RuleQuery; import org.sonarqube.ws.Qualityprofiles; import org.sonarqube.ws.Qualityprofiles.ShowResponse; import org.sonarqube.ws.Qualityprofiles.ShowResponse.CompareToSonarWay; import org.sonarqube.ws.Qualityprofiles.ShowResponse.QualityProfile; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.api.rule.RuleStatus.DEPRECATED; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_SHOW; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_COMPARE_TO_SONAR_WAY; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY; public class ShowAction implements QProfileWsAction { private static final String SONAR_WAY = "Sonar way"; private static final String SONARQUBE_WAY = "SonarQube way"; private final DbClient dbClient; private final QProfileWsSupport qProfileWsSupport; private final Languages languages; private final RuleIndex ruleIndex; public ShowAction(DbClient dbClient, QProfileWsSupport qProfileWsSupport, Languages languages, RuleIndex ruleIndex) { this.dbClient = dbClient; this.qProfileWsSupport = qProfileWsSupport; this.languages = languages; this.ruleIndex = ruleIndex; } @Override public void define(WebService.NewController controller) { NewAction show = controller.createAction(ACTION_SHOW) .setDescription("Show a quality profile") .setSince("6.5") .setResponseExample(getClass().getResource("show-example.json")) .setInternal(true) .setHandler(this); show.createParam(PARAM_KEY) .setDescription("Quality profile key") .setExampleValue(UUID_EXAMPLE_01) .setRequired(true); show.createParam(PARAM_COMPARE_TO_SONAR_WAY) .setDescription("Add the number of missing rules from the related Sonar way profile in the response") .setInternal(true) .setDefaultValue("false") .setBooleanPossibleValues(); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = qProfileWsSupport.getProfile(dbSession, QProfileReference.fromKey(request.mandatoryParam(PARAM_KEY))); boolean isDefault = dbClient.defaultQProfileDao().isDefault(dbSession, profile.getKee()); ActiveRuleCountQuery.Builder builder = ActiveRuleCountQuery.builder(); long activeRuleCount = countActiveRulesByQuery(dbSession, profile, builder); long deprecatedActiveRuleCount = countActiveRulesByQuery(dbSession, profile, builder.setRuleStatus(DEPRECATED)); long projectCount = countProjectsByProfiles(dbSession, profile); CompareToSonarWay compareToSonarWay = getSonarWay(request, dbSession, profile); writeProtobuf(buildResponse(profile, isDefault, getLanguage(profile), activeRuleCount, deprecatedActiveRuleCount, projectCount, compareToSonarWay), request, response); } } private long countActiveRulesByQuery(DbSession dbSession, QProfileDto profile, ActiveRuleCountQuery.Builder queryBuilder) { Map<String, Long> result = dbClient.activeRuleDao().countActiveRulesByQuery(dbSession, queryBuilder.setProfiles(singletonList(profile)).build()); return result.getOrDefault(profile.getKee(), 0L); } private long countProjectsByProfiles(DbSession dbSession, QProfileDto profile) { Map<String, Long> projects = dbClient.qualityProfileDao().countProjectsByProfiles(dbSession, singletonList(profile)); return projects.getOrDefault(profile.getKee(), 0L); } public Language getLanguage(QProfileDto profile) { Language language = languages.get(profile.getLanguage()); checkFound(language, "Quality Profile with key '%s' does not exist", profile.getKee()); return language; } @CheckForNull public CompareToSonarWay getSonarWay(Request request, DbSession dbSession, QProfileDto profile) { if (!request.mandatoryParamAsBoolean(PARAM_COMPARE_TO_SONAR_WAY) || profile.isBuiltIn()) { return null; } QProfileDto sonarWay = Stream.of(SONAR_WAY, SONARQUBE_WAY) .map(name -> dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, name, profile.getLanguage())) .filter(Objects::nonNull) .filter(QProfileDto::isBuiltIn) .findFirst() .orElse(null); if (sonarWay == null) { return null; } long missingRuleCount = ruleIndex.search( new RuleQuery().setQProfile(profile).setActivation(false).setCompareToQProfile(sonarWay), new SearchOptions().setLimit(1)) .getTotal(); return CompareToSonarWay.newBuilder() .setProfile(sonarWay.getKee()) .setProfileName(sonarWay.getName()) .setMissingRuleCount(missingRuleCount) .build(); } private static ShowResponse buildResponse(QProfileDto profile, boolean isDefault, Language language, long activeRules, long deprecatedActiveRules, long projects, @Nullable CompareToSonarWay compareToSonarWay) { ShowResponse.Builder showResponseBuilder = Qualityprofiles.ShowResponse.newBuilder(); QualityProfile.Builder profileBuilder = QualityProfile.newBuilder() .setKey(profile.getKee()) .setName(profile.getName()) .setLanguage(profile.getLanguage()) .setLanguageName(language.getName()) .setIsBuiltIn(profile.isBuiltIn()) .setIsDefault(isDefault) .setIsInherited(profile.getParentKee() != null) .setActiveRuleCount(activeRules) .setActiveDeprecatedRuleCount(deprecatedActiveRules) .setProjectCount(projects); ofNullable(profile.getRulesUpdatedAt()).ifPresent(profileBuilder::setRulesUpdatedAt); ofNullable(profile.getLastUsed()).ifPresent(last -> profileBuilder.setLastUsed(formatDateTime(last))); ofNullable(profile.getUserUpdatedAt()).ifPresent(userUpdatedAt -> profileBuilder.setUserUpdatedAt(formatDateTime(userUpdatedAt))); ofNullable(compareToSonarWay).ifPresent(showResponseBuilder::setCompareToSonarWay); return showResponseBuilder.setProfile(profileBuilder).build(); } }
7,972
44.821839
173
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/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.qualityprofile.ws; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/NewCustomRule.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.rule; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; public class NewCustomRule { private String ruleKey; private RuleKey templateKey; private String name; private String markdownDescription; private String severity; private RuleStatus status; private RuleType type; private Map<String, String> parameters = new HashMap<>(); private boolean preventReactivation = false; private NewCustomRule() { // No direct call to constructor } public String ruleKey() { return ruleKey; } public RuleKey templateKey() { return templateKey; } @CheckForNull public String name() { return name; } public NewCustomRule setName(@Nullable String name) { this.name = name; return this; } @CheckForNull public String markdownDescription() { return markdownDescription; } public NewCustomRule setMarkdownDescription(@Nullable String markdownDescription) { this.markdownDescription = markdownDescription; return this; } @CheckForNull public String severity() { return severity; } public NewCustomRule setSeverity(@Nullable String severity) { this.severity = severity; return this; } @CheckForNull public RuleStatus status() { return status; } public NewCustomRule setStatus(@Nullable RuleStatus status) { this.status = status; return this; } @CheckForNull public RuleType type() { return type; } public NewCustomRule setType(@Nullable RuleType type) { this.type = type; return this; } @CheckForNull public String parameter(final String paramKey) { return parameters.get(paramKey); } public NewCustomRule setParameters(Map<String, String> params) { this.parameters = params; return this; } public boolean isPreventReactivation() { return preventReactivation; } /** * When true, if the rule already exists in status REMOVED, an {@link ReactivationException} will be thrown */ public NewCustomRule setPreventReactivation(boolean preventReactivation) { this.preventReactivation = preventReactivation; return this; } public static NewCustomRule createForCustomRule(String customKey, RuleKey templateKey) { Preconditions.checkArgument(!Strings.isNullOrEmpty(customKey), "Custom key should be set"); Preconditions.checkArgument(templateKey != null, "Template key should be set"); NewCustomRule newRule = new NewCustomRule(); newRule.ruleKey = customKey; newRule.templateKey = templateKey; return newRule; } }
3,665
25.565217
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ReactivationException.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.rule; import org.sonar.api.rule.RuleKey; public class ReactivationException extends RuntimeException { private RuleKey ruleKey; public ReactivationException(String s, RuleKey ruleKey) { super(s); this.ruleKey = ruleKey; } public RuleKey ruleKey() { return ruleKey; } }
1,164
30.486486
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/RuleCreator.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.rule; import com.google.common.base.Splitter; import com.google.common.base.Strings; import java.util.ArrayList; 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.Nullable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.server.ServerSide; import org.sonar.api.server.rule.RuleParamType; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Format; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.util.TypeValidations; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.server.exceptions.BadRequestException.checkRequest; @ServerSide public class RuleCreator { private static final String TEMPLATE_KEY_NOT_EXIST_FORMAT = "The template key doesn't exist: %s"; private final System2 system2; private final RuleIndexer ruleIndexer; private final DbClient dbClient; private final TypeValidations typeValidations; private final UuidFactory uuidFactory; public RuleCreator(System2 system2, RuleIndexer ruleIndexer, DbClient dbClient, TypeValidations typeValidations, UuidFactory uuidFactory) { this.system2 = system2; this.ruleIndexer = ruleIndexer; this.dbClient = dbClient; this.typeValidations = typeValidations; this.uuidFactory = uuidFactory; } public RuleKey create(DbSession dbSession, NewCustomRule newRule) { RuleKey templateKey = newRule.templateKey(); RuleDto templateRule = dbClient.ruleDao().selectByKey(dbSession, templateKey) .orElseThrow(() -> new IllegalArgumentException(format(TEMPLATE_KEY_NOT_EXIST_FORMAT, templateKey))); checkArgument(templateRule.isTemplate(), "This rule is not a template rule: %s", templateKey.toString()); checkArgument(templateRule.getStatus() != RuleStatus.REMOVED, TEMPLATE_KEY_NOT_EXIST_FORMAT, templateKey.toString()); validateCustomRule(newRule, dbSession, templateKey); RuleKey customRuleKey = RuleKey.of(templateRule.getRepositoryKey(), newRule.ruleKey()); Optional<RuleDto> definition = loadRule(dbSession, customRuleKey); String customRuleUuid = definition.map(d -> updateExistingRule(d, newRule, dbSession)) .orElseGet(() -> createCustomRule(customRuleKey, newRule, templateRule, dbSession)); ruleIndexer.commitAndIndex(dbSession, customRuleUuid); return customRuleKey; } public List<RuleKey> create(DbSession dbSession, List<NewCustomRule> newRules) { Set<RuleKey> templateKeys = newRules.stream().map(NewCustomRule::templateKey).collect(Collectors.toSet()); Map<RuleKey, RuleDto> templateRules = dbClient.ruleDao().selectByKeys(dbSession, templateKeys) .stream() .collect(Collectors.toMap( RuleDto::getKey, Function.identity())); checkArgument(!templateRules.isEmpty() && templateKeys.size() == templateRules.size(), "Rule template keys should exists for each custom rule!"); templateRules.values().forEach(ruleDto -> { checkArgument(ruleDto.isTemplate(), "This rule is not a template rule: %s", ruleDto.getKey().toString()); checkArgument(ruleDto.getStatus() != RuleStatus.REMOVED, TEMPLATE_KEY_NOT_EXIST_FORMAT, ruleDto.getKey().toString()); }); List<String> customRuleUuids = newRules.stream() .map(newCustomRule -> { RuleDto templateRule = templateRules.get(newCustomRule.templateKey()); validateCustomRule(newCustomRule, dbSession, templateRule.getKey()); RuleKey customRuleKey = RuleKey.of(templateRule.getRepositoryKey(), newCustomRule.ruleKey()); return createCustomRule(customRuleKey, newCustomRule, templateRule, dbSession); }) .toList(); ruleIndexer.commitAndIndex(dbSession, customRuleUuids); return newRules.stream() .map(newCustomRule -> { RuleDto templateRule = templateRules.get(newCustomRule.templateKey()); return RuleKey.of(templateRule.getRepositoryKey(), newCustomRule.ruleKey()); }) .toList(); } private void validateCustomRule(NewCustomRule newRule, DbSession dbSession, RuleKey templateKey) { List<String> errors = new ArrayList<>(); validateRuleKey(errors, newRule.ruleKey()); validateName(errors, newRule); validateDescription(errors, newRule); String severity = newRule.severity(); if (Strings.isNullOrEmpty(severity)) { errors.add("The severity is missing"); } else if (!Severity.ALL.contains(severity)) { errors.add(format("Severity \"%s\" is invalid", severity)); } if (newRule.status() == null) { errors.add("The status is missing"); } for (RuleParamDto ruleParam : dbClient.ruleDao().selectRuleParamsByRuleKey(dbSession, templateKey)) { try { validateParam(ruleParam, newRule.parameter(ruleParam.getName())); } catch (BadRequestException validationError) { errors.addAll(validationError.errors()); } } checkRequest(errors.isEmpty(), errors); } private void validateParam(RuleParamDto ruleParam, @Nullable String value) { if (value != null) { RuleParamType ruleParamType = RuleParamType.parse(ruleParam.getType()); if (ruleParamType.multiple()) { List<String> values = newArrayList(Splitter.on(",").split(value)); typeValidations.validate(values, ruleParamType.type(), ruleParamType.values()); } else { typeValidations.validate(value, ruleParamType.type(), ruleParamType.values()); } } } private static void validateName(List<String> errors, NewCustomRule newRule) { if (Strings.isNullOrEmpty(newRule.name())) { errors.add("The name is missing"); } } private static void validateDescription(List<String> errors, NewCustomRule newRule) { if (Strings.isNullOrEmpty(newRule.markdownDescription())) { errors.add("The description is missing"); } } private static void validateRuleKey(List<String> errors, String ruleKey) { if (!ruleKey.matches("^[\\w]+$")) { errors.add(format("The rule key \"%s\" is invalid, it should only contain: a-z, 0-9, \"_\"", ruleKey)); } } private Optional<RuleDto> loadRule(DbSession dbSession, RuleKey ruleKey) { return dbClient.ruleDao().selectByKey(dbSession, ruleKey); } private String createCustomRule(RuleKey ruleKey, NewCustomRule newRule, RuleDto templateRuleDto, DbSession dbSession) { RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), requireNonNull(newRule.markdownDescription())); RuleDto ruleDto = new RuleDto() .setUuid(uuidFactory.create()) .setRuleKey(ruleKey) .setPluginKey(templateRuleDto.getPluginKey()) .setTemplateUuid(templateRuleDto.getUuid()) .setConfigKey(templateRuleDto.getConfigKey()) .setName(newRule.name()) .setSeverity(newRule.severity()) .setStatus(newRule.status()) .setType(newRule.type() == null ? templateRuleDto.getType() : newRule.type().getDbConstant()) .setLanguage(templateRuleDto.getLanguage()) .setDefRemediationFunction(templateRuleDto.getDefRemediationFunction()) .setDefRemediationGapMultiplier(templateRuleDto.getDefRemediationGapMultiplier()) .setDefRemediationBaseEffort(templateRuleDto.getDefRemediationBaseEffort()) .setGapDescription(templateRuleDto.getGapDescription()) .setScope(templateRuleDto.getScope()) .setSystemTags(templateRuleDto.getSystemTags()) .setSecurityStandards(templateRuleDto.getSecurityStandards()) .setIsExternal(false) .setIsAdHoc(false) .setCreatedAt(system2.now()) .setUpdatedAt(system2.now()) .setDescriptionFormat(Format.MARKDOWN) .addRuleDescriptionSectionDto(ruleDescriptionSectionDto); Set<String> tags = templateRuleDto.getTags(); if (!tags.isEmpty()) { ruleDto.setTags(tags); } dbClient.ruleDao().insert(dbSession, ruleDto); for (RuleParamDto templateRuleParamDto : dbClient.ruleDao().selectRuleParamsByRuleKey(dbSession, templateRuleDto.getKey())) { String customRuleParamValue = Strings.emptyToNull(newRule.parameter(templateRuleParamDto.getName())); createCustomRuleParams(customRuleParamValue, ruleDto, templateRuleParamDto, dbSession); } return ruleDto.getUuid(); } private void createCustomRuleParams(@Nullable String paramValue, RuleDto ruleDto, RuleParamDto templateRuleParam, DbSession dbSession) { RuleParamDto ruleParamDto = RuleParamDto.createFor(ruleDto) .setName(templateRuleParam.getName()) .setType(templateRuleParam.getType()) .setDescription(templateRuleParam.getDescription()) .setDefaultValue(paramValue); dbClient.ruleDao().insertRuleParam(dbSession, ruleDto, ruleParamDto); } private String updateExistingRule(RuleDto ruleDto, NewCustomRule newRule, DbSession dbSession) { if (ruleDto.getStatus().equals(RuleStatus.REMOVED)) { if (newRule.isPreventReactivation()) { throw new ReactivationException(format("A removed rule with the key '%s' already exists", ruleDto.getKey().rule()), ruleDto.getKey()); } else { ruleDto.setStatus(RuleStatus.READY) .setUpdatedAt(system2.now()); dbClient.ruleDao().update(dbSession, ruleDto); } } else { throw new IllegalArgumentException(format("A rule with the key '%s' already exists", ruleDto.getKey().rule())); } return ruleDto.getUuid(); } }
10,962
43.028112
163
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/RuleTagHelper.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.rule; import com.google.common.collect.Sets; import java.util.Set; import org.sonar.api.server.rule.RuleTagFormat; import org.sonar.db.rule.RuleDto; class RuleTagHelper { private RuleTagHelper() { // only static stuff } /** * Validates tags and resolves conflicts between user and system tags. */ static boolean applyTags(RuleDto rule, Set<String> tags) { for (String tag : tags) { RuleTagFormat.validate(tag); } Set<String> initialTags = rule.getTags(); final Set<String> systemTags = rule.getSystemTags(); Set<String> withoutSystemTags = Sets.filter(tags, input -> input != null && !systemTags.contains(input)); rule.setTags(withoutSystemTags); return withoutSystemTags.size() != initialTags.size() || !withoutSystemTags.containsAll(initialTags); } }
1,680
34.020833
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/RuleUpdate.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.rule; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.server.debt.DebtRemediationFunction; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.rule.RuleUpdate.RuleUpdateUseCase.CUSTOM_RULE; import static org.sonar.server.rule.RuleUpdate.RuleUpdateUseCase.PLUGIN_RULE; public class RuleUpdate { private final RuleKey ruleKey; private boolean changeTags = false; private boolean changeMarkdownNote = false; private boolean changeDebtRemediationFunction = false; private boolean changeName = false; private boolean changeDescription = false; private boolean changeSeverity = false; private boolean changeStatus = false; private boolean changeParameters = false; private final RuleUpdateUseCase useCase; private Set<String> tags; private String markdownNote; private DebtRemediationFunction debtRemediationFunction; private String name; private String markdownDescription; private String severity; private RuleStatus status; private final Map<String, String> parameters = new HashMap<>(); private RuleUpdate(RuleKey ruleKey, RuleUpdateUseCase useCase) { this.ruleKey = ruleKey; this.useCase = useCase; } public RuleKey getRuleKey() { return ruleKey; } @CheckForNull public Set<String> getTags() { return tags; } /** * Set to <code>null</code> or empty set to remove existing tags. */ public RuleUpdate setTags(@Nullable Set<String> tags) { this.tags = tags; this.changeTags = true; return this; } @CheckForNull public String getMarkdownNote() { return markdownNote; } /** * Set to <code>null</code> or blank to remove existing note. */ public RuleUpdate setMarkdownNote(@Nullable String s) { this.markdownNote = s == null ? null : StringUtils.defaultIfBlank(s, null); this.changeMarkdownNote = true; return this; } @CheckForNull public DebtRemediationFunction getDebtRemediationFunction() { return debtRemediationFunction; } public RuleUpdate setDebtRemediationFunction(@Nullable DebtRemediationFunction fn) { this.debtRemediationFunction = fn; this.changeDebtRemediationFunction = true; return this; } @CheckForNull public String getName() { return name; } public RuleUpdate setName(@Nullable String name) { checkCustomRule(); this.name = name; this.changeName = true; return this; } @CheckForNull public String getMarkdownDescription() { return markdownDescription; } public RuleUpdate setMarkdownDescription(@Nullable String markdownDescription) { checkCustomRule(); this.markdownDescription = markdownDescription; this.changeDescription = true; return this; } @CheckForNull public String getSeverity() { return severity; } public RuleUpdate setSeverity(@Nullable String severity) { checkCustomRule(); this.severity = severity; this.changeSeverity = true; return this; } @CheckForNull public RuleStatus getStatus() { return status; } public RuleUpdate setStatus(@Nullable RuleStatus status) { checkCustomRule(); this.status = status; this.changeStatus = true; return this; } /** * Parameters to be updated (only for custom rules) */ public RuleUpdate setParameters(Map<String, String> params) { checkCustomRule(); this.parameters.clear(); this.parameters.putAll(params); this.changeParameters = true; return this; } public Map<String, String> getParameters() { return parameters; } @CheckForNull public String parameter(final String paramKey) { return parameters.get(paramKey); } boolean isCustomRule() { return useCase.isCustomRule; } public boolean isChangeTags() { return changeTags; } public boolean isChangeMarkdownNote() { return changeMarkdownNote; } public boolean isChangeDebtRemediationFunction() { return changeDebtRemediationFunction; } public boolean isChangeName() { return changeName; } public boolean isChangeDescription() { return changeDescription; } public boolean isChangeSeverity() { return changeSeverity; } public boolean isChangeStatus() { return changeStatus; } public boolean isChangeParameters() { return changeParameters; } public boolean isEmpty() { return !changeMarkdownNote && !changeTags && !changeDebtRemediationFunction && isCustomRuleFieldsEmpty(); } private boolean isCustomRuleFieldsEmpty() { return !changeName && !changeDescription && !changeSeverity && !changeStatus && !changeParameters; } private void checkCustomRule() { checkArgument(useCase == CUSTOM_RULE, "Not a custom rule"); } /** * Use to update a rule provided by a plugin (name, description, severity, status and parameters cannot by changed) */ public static RuleUpdate createForPluginRule(RuleKey ruleKey) { return new RuleUpdate(ruleKey, PLUGIN_RULE); } /** * Use to update a custom rule */ public static RuleUpdate createForCustomRule(RuleKey ruleKey) { return new RuleUpdate(ruleKey, CUSTOM_RULE); } public enum RuleUpdateUseCase { PLUGIN_RULE(false), CUSTOM_RULE(true); public final boolean isCustomRule; RuleUpdateUseCase(boolean isCustomRule) { this.isCustomRule = isCustomRule; } } }
6,460
25.052419
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/RuleUpdater.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.rule; import com.google.common.base.Function; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import javax.annotation.Nonnull; import org.apache.commons.lang.builder.EqualsBuilder; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.server.ServerSide; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.FluentIterable.from; import static com.google.common.collect.Lists.newArrayList; import static org.apache.commons.lang.StringUtils.isBlank; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; @ServerSide public class RuleUpdater { private final DbClient dbClient; private final RuleIndexer ruleIndexer; private final UuidFactory uuidFactory; private final System2 system; public RuleUpdater(DbClient dbClient, RuleIndexer ruleIndexer, UuidFactory uuidFactory, System2 system) { this.dbClient = dbClient; this.ruleIndexer = ruleIndexer; this.uuidFactory = uuidFactory; this.system = system; } /** * Update manual rules and custom rules (rules instantiated from templates) */ public boolean update(DbSession dbSession, RuleUpdate update, UserSession userSession) { if (update.isEmpty()) { return false; } RuleDto rule = getRuleDto(update); // validate only the changes, not all the rule fields apply(update, rule, userSession); update(dbSession, rule); updateParameters(dbSession, update, rule); ruleIndexer.commitAndIndex(dbSession, rule.getUuid()); return true; } /** * Load all the DTOs required for validating changes and updating rule */ private RuleDto getRuleDto(RuleUpdate change) { try (DbSession dbSession = dbClient.openSession(false)) { RuleDto rule = dbClient.ruleDao().selectOrFailByKey(dbSession, change.getRuleKey()); if (RuleStatus.REMOVED == rule.getStatus()) { throw new IllegalArgumentException("Rule with REMOVED status cannot be updated: " + change.getRuleKey()); } return rule; } } private void apply(RuleUpdate update, RuleDto rule, UserSession userSession) { if (update.isChangeName()) { updateName(update, rule); } if (update.isChangeDescription()) { updateDescription(update, rule); } if (update.isChangeSeverity()) { updateSeverity(update, rule); } if (update.isChangeStatus()) { updateStatus(update, rule); } if (update.isChangeMarkdownNote()) { updateMarkdownNote(update, rule, userSession); } if (update.isChangeTags()) { updateTags(update, rule); } // order is important -> sub-characteristic must be set if (update.isChangeDebtRemediationFunction()) { updateDebtRemediationFunction(update, rule); } } private static void updateName(RuleUpdate update, RuleDto rule) { String name = update.getName(); if (isNullOrEmpty(name)) { throw new IllegalArgumentException("The name is missing"); } rule.setName(name); } private void updateDescription(RuleUpdate update, RuleDto rule) { String description = update.getMarkdownDescription(); if (isNullOrEmpty(description)) { throw new IllegalArgumentException("The description is missing"); } RuleDescriptionSectionDto descriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), description); rule.setDescriptionFormat(RuleDto.Format.MARKDOWN); rule.replaceRuleDescriptionSectionDtos(List.of(descriptionSectionDto)); } private static void updateSeverity(RuleUpdate update, RuleDto rule) { String severity = update.getSeverity(); if (isNullOrEmpty(severity) || !Severity.ALL.contains(severity)) { throw new IllegalArgumentException("The severity is invalid"); } rule.setSeverity(severity); } private static void updateStatus(RuleUpdate update, RuleDto rule) { RuleStatus status = update.getStatus(); if (status == null) { throw new IllegalArgumentException("The status is missing"); } rule.setStatus(status); } private static void updateTags(RuleUpdate update, RuleDto rule) { Set<String> tags = update.getTags(); if (tags == null || tags.isEmpty()) { rule.setTags(Collections.emptySet()); } else { RuleTagHelper.applyTags(rule, tags); } } private static void updateDebtRemediationFunction(RuleUpdate update, RuleDto rule) { DebtRemediationFunction function = update.getDebtRemediationFunction(); if (function == null) { rule.setRemediationFunction(null); rule.setRemediationGapMultiplier(null); rule.setRemediationBaseEffort(null); } else { if (isSameAsDefaultFunction(function, rule)) { // reset to default rule.setRemediationFunction(null); rule.setRemediationGapMultiplier(null); rule.setRemediationBaseEffort(null); } else { rule.setRemediationFunction(function.type().name()); rule.setRemediationGapMultiplier(function.gapMultiplier()); rule.setRemediationBaseEffort(function.baseEffort()); } } } private void updateMarkdownNote(RuleUpdate update, RuleDto rule, UserSession userSession) { if (isBlank(update.getMarkdownNote())) { rule.setNoteData(null); rule.setNoteCreatedAt(null); rule.setNoteUpdatedAt(null); rule.setNoteUserUuid(null); } else { long now = system.now(); rule.setNoteData(update.getMarkdownNote()); rule.setNoteCreatedAt(rule.getNoteCreatedAt() != null ? rule.getNoteCreatedAt() : now); rule.setNoteUpdatedAt(now); rule.setNoteUserUuid(userSession.getUuid()); } } private static boolean isSameAsDefaultFunction(DebtRemediationFunction fn, RuleDto rule) { return new EqualsBuilder() .append(fn.type().name(), rule.getDefRemediationFunction()) .append(fn.gapMultiplier(), rule.getDefRemediationGapMultiplier()) .append(fn.baseEffort(), rule.getDefRemediationBaseEffort()) .isEquals(); } private void updateParameters(DbSession dbSession, RuleUpdate update, RuleDto rule) { if (update.isChangeParameters() && update.isCustomRule()) { RuleDto customRule = rule; String templateUuid = customRule.getTemplateUuid(); checkNotNull(templateUuid, "Rule '%s' has no persisted template!", customRule); Optional<RuleDto> templateRule = dbClient.ruleDao().selectByUuid(templateUuid, dbSession); if (!templateRule.isPresent()) { throw new IllegalStateException(String.format("Template %s of rule %s does not exist", customRule.getTemplateUuid(), customRule.getKey())); } List<String> paramKeys = newArrayList(); // Load active rules and its parameters in cache Multimap<ActiveRuleDto, ActiveRuleParamDto> activeRuleParamsByActiveRule = getActiveRuleParamsByActiveRule(dbSession, customRule); // Browse custom rule parameters to create, update or delete them deleteOrUpdateParameters(dbSession, update, customRule, paramKeys, activeRuleParamsByActiveRule); } } private Multimap<ActiveRuleDto, ActiveRuleParamDto> getActiveRuleParamsByActiveRule(DbSession dbSession, RuleDto customRule) { List<OrgActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByOrgRuleUuid(dbSession, customRule.getUuid()); Map<String, OrgActiveRuleDto> activeRuleByUuid = from(activeRuleDtos).uniqueIndex(ActiveRuleDto::getUuid); List<String> activeRuleUuids = Lists.transform(activeRuleDtos, ActiveRuleDto::getUuid); List<ActiveRuleParamDto> activeRuleParamDtos = dbClient.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, activeRuleUuids); return from(activeRuleParamDtos) .index(new ActiveRuleParamToActiveRule(activeRuleByUuid)); } private void deleteOrUpdateParameters(DbSession dbSession, RuleUpdate update, RuleDto customRule, List<String> paramKeys, Multimap<ActiveRuleDto, ActiveRuleParamDto> activeRuleParamsByActiveRule) { for (RuleParamDto ruleParamDto : dbClient.ruleDao().selectRuleParamsByRuleKey(dbSession, update.getRuleKey())) { String key = ruleParamDto.getName(); String value = Strings.emptyToNull(update.parameter(key)); // Update rule param ruleParamDto.setDefaultValue(value); dbClient.ruleDao().updateRuleParam(dbSession, customRule, ruleParamDto); if (value != null) { // Update linked active rule params or create new one updateOrInsertActiveRuleParams(dbSession, ruleParamDto, activeRuleParamsByActiveRule); } else { // Delete linked active rule params deleteActiveRuleParams(dbSession, key, activeRuleParamsByActiveRule.values()); } paramKeys.add(key); } } private void updateOrInsertActiveRuleParams(DbSession dbSession, RuleParamDto ruleParamDto, Multimap<ActiveRuleDto, ActiveRuleParamDto> activeRuleParamsByActiveRule) { activeRuleParamsByActiveRule .keySet() .forEach(new UpdateOrInsertActiveRuleParams(dbSession, dbClient, ruleParamDto, activeRuleParamsByActiveRule)); } private void deleteActiveRuleParams(DbSession dbSession, String key, Collection<ActiveRuleParamDto> activeRuleParamDtos) { activeRuleParamDtos.forEach(new DeleteActiveRuleParams(dbSession, dbClient, key)); } private static class ActiveRuleParamToActiveRule implements Function<ActiveRuleParamDto, ActiveRuleDto> { private final Map<String, OrgActiveRuleDto> activeRuleByUuid; private ActiveRuleParamToActiveRule(Map<String, OrgActiveRuleDto> activeRuleByUuid) { this.activeRuleByUuid = activeRuleByUuid; } @Override public OrgActiveRuleDto apply(@Nonnull ActiveRuleParamDto input) { return activeRuleByUuid.get(input.getActiveRuleUuid()); } } private static class UpdateOrInsertActiveRuleParams implements Consumer<ActiveRuleDto> { private final DbSession dbSession; private final DbClient dbClient; private final RuleParamDto ruleParamDto; private final Multimap<ActiveRuleDto, ActiveRuleParamDto> activeRuleParams; private UpdateOrInsertActiveRuleParams(DbSession dbSession, DbClient dbClient, RuleParamDto ruleParamDto, Multimap<ActiveRuleDto, ActiveRuleParamDto> activeRuleParams) { this.dbSession = dbSession; this.dbClient = dbClient; this.ruleParamDto = ruleParamDto; this.activeRuleParams = activeRuleParams; } @Override public void accept(@Nonnull ActiveRuleDto activeRuleDto) { Map<String, ActiveRuleParamDto> activeRuleParamByKey = from(activeRuleParams.get(activeRuleDto)) .uniqueIndex(ActiveRuleParamDto::getKey); ActiveRuleParamDto activeRuleParamDto = activeRuleParamByKey.get(ruleParamDto.getName()); if (activeRuleParamDto != null) { dbClient.activeRuleDao().updateParam(dbSession, activeRuleParamDto.setValue(ruleParamDto.getDefaultValue())); } else { dbClient.activeRuleDao().insertParam(dbSession, activeRuleDto, ActiveRuleParamDto.createFor(ruleParamDto).setValue(ruleParamDto.getDefaultValue())); } } } private static class DeleteActiveRuleParams implements Consumer<ActiveRuleParamDto> { private final DbSession dbSession; private final DbClient dbClient; private final String key; public DeleteActiveRuleParams(DbSession dbSession, DbClient dbClient, String key) { this.dbSession = dbSession; this.dbClient = dbClient; this.key = key; } @Override public void accept(@Nonnull ActiveRuleParamDto activeRuleParamDto) { if (activeRuleParamDto.getKey().equals(key)) { dbClient.activeRuleDao().deleteParamByUuid(dbSession, activeRuleParamDto.getUuid()); } } } private void update(DbSession session, RuleDto rule) { rule.setUpdatedAt(system.now()); dbClient.ruleDao().update(session, rule); } }
13,645
39.253687
173
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule; import javax.annotation.ParametersAreNonnullByDefault;
961
40.826087
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/ActiveRuleCompleter.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.rule.ws; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; 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 java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.DateUtils; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleKey; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.qualityprofile.ActiveRuleInheritance; import org.sonar.server.rule.index.RuleQuery; import org.sonarqube.ws.Rules; import org.sonarqube.ws.Rules.SearchResponse; import static com.google.common.base.Strings.nullToEmpty; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; /** * Add details about active rules to api/rules/search and api/rules/show * web services. */ @ServerSide public class ActiveRuleCompleter { private final DbClient dbClient; private final Languages languages; public ActiveRuleCompleter(DbClient dbClient, Languages languages) { this.dbClient = dbClient; this.languages = languages; } void completeSearch(DbSession dbSession, RuleQuery query, List<RuleDto> rules, SearchResponse.Builder searchResponse) { Set<String> profileUuids = writeActiveRules(dbSession, searchResponse, query, rules); searchResponse.setQProfiles(buildQProfiles(dbSession, profileUuids)); } private Set<String> writeActiveRules(DbSession dbSession, SearchResponse.Builder response, RuleQuery query, List<RuleDto> rules) { final Set<String> profileUuids = new HashSet<>(); Rules.Actives.Builder activesBuilder = response.getActivesBuilder(); QProfileDto profile = query.getQProfile(); if (profile != null) { // Load details of active rules on the selected profile List<OrgActiveRuleDto> activeRules = dbClient.activeRuleDao().selectByProfile(dbSession, profile); Map<RuleKey, OrgActiveRuleDto> activeRuleByRuleKey = activeRules.stream() .collect(Collectors.toMap(ActiveRuleDto::getRuleKey, Function.identity())); ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = loadParams(dbSession, activeRules); for (RuleDto rule : rules) { OrgActiveRuleDto activeRule = activeRuleByRuleKey.get(rule.getKey()); if (activeRule != null) { profileUuids.addAll(writeActiveRules(rule.getKey(), singletonList(activeRule), activeRuleParamsByActiveRuleKey, activesBuilder)); } } } else { // Load details of all active rules List<String> ruleUuids = Lists.transform(rules, RuleDto::getUuid); List<OrgActiveRuleDto> activeRules = dbClient.activeRuleDao().selectByRuleUuids(dbSession, ruleUuids); Multimap<RuleKey, OrgActiveRuleDto> activeRulesByRuleKey = activeRules.stream() .collect(MoreCollectors.index(OrgActiveRuleDto::getRuleKey)); ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = loadParams(dbSession, activeRules); rules.forEach(rule -> profileUuids.addAll(writeActiveRules(rule.getKey(), activeRulesByRuleKey.get(rule.getKey()), activeRuleParamsByActiveRuleKey, activesBuilder))); } response.setActives(activesBuilder); return profileUuids; } private static Set<String> writeActiveRules(RuleKey ruleKey, Collection<OrgActiveRuleDto> activeRules, ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey, Rules.Actives.Builder activesBuilder) { final Set<String> profileUuids = new HashSet<>(); Rules.ActiveList.Builder activeRulesListResponse = Rules.ActiveList.newBuilder(); for (OrgActiveRuleDto activeRule : activeRules) { activeRulesListResponse.addActiveList(buildActiveRuleResponse(activeRule, activeRuleParamsByActiveRuleKey.get(activeRule.getKey()))); profileUuids.add(activeRule.getOrgProfileUuid()); } activesBuilder .getMutableActives() .put(ruleKey.toString(), activeRulesListResponse.build()); return profileUuids; } private ListMultimap<ActiveRuleKey, ActiveRuleParamDto> loadParams(DbSession dbSession, List<OrgActiveRuleDto> activeRules) { Map<String, ActiveRuleKey> activeRuleUuidsByKey = new HashMap<>(); for (OrgActiveRuleDto activeRule : activeRules) { activeRuleUuidsByKey.put(activeRule.getUuid(), activeRule.getKey()); } List<ActiveRuleParamDto> activeRuleParams = dbClient.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, Lists.transform(activeRules, ActiveRuleDto::getUuid)); ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = ArrayListMultimap.create(activeRules.size(), 10); for (ActiveRuleParamDto activeRuleParam : activeRuleParams) { ActiveRuleKey activeRuleKey = activeRuleUuidsByKey.get(activeRuleParam.getActiveRuleUuid()); activeRuleParamsByActiveRuleKey.put(activeRuleKey, activeRuleParam); } return activeRuleParamsByActiveRuleKey; } List<Rules.Active> completeShow(DbSession dbSession, RuleDto rule) { List<OrgActiveRuleDto> activeRules = dbClient.activeRuleDao().selectByOrgRuleUuid(dbSession, rule.getUuid()); Map<String, ActiveRuleKey> activeRuleUuidsByKey = new HashMap<>(); for (OrgActiveRuleDto activeRuleDto : activeRules) { activeRuleUuidsByKey.put(activeRuleDto.getUuid(), activeRuleDto.getKey()); } List<String> activeRuleUuids = activeRules.stream().map(ActiveRuleDto::getUuid).toList(); List<ActiveRuleParamDto> activeRuleParams = dbClient.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, activeRuleUuids); ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = ArrayListMultimap.create(activeRules.size(), 10); for (ActiveRuleParamDto activeRuleParamDto : activeRuleParams) { ActiveRuleKey activeRuleKey = activeRuleUuidsByKey.get(activeRuleParamDto.getActiveRuleUuid()); activeRuleParamsByActiveRuleKey.put(activeRuleKey, activeRuleParamDto); } return activeRules.stream() .map(activeRule -> buildActiveRuleResponse(activeRule, activeRuleParamsByActiveRuleKey.get(activeRule.getKey()))) .toList(); } private static Rules.Active buildActiveRuleResponse(OrgActiveRuleDto activeRule, List<ActiveRuleParamDto> parameters) { Rules.Active.Builder builder = Rules.Active.newBuilder(); builder.setQProfile(activeRule.getOrgProfileUuid()); String inheritance = activeRule.getInheritance(); builder.setInherit(inheritance != null ? inheritance : ActiveRuleInheritance.NONE.name()); builder.setSeverity(activeRule.getSeverityString()); builder.setCreatedAt(DateUtils.formatDateTime(activeRule.getCreatedAt())); builder.setUpdatedAt(DateUtils.formatDateTime(activeRule.getUpdatedAt())); Rules.Active.Param.Builder paramBuilder = Rules.Active.Param.newBuilder(); for (ActiveRuleParamDto parameter : parameters) { builder.addParams(paramBuilder.clear() .setKey(parameter.getKey()) .setValue(nullToEmpty(parameter.getValue()))); } return builder.build(); } private Rules.QProfiles.Builder buildQProfiles(DbSession dbSession, Set<String> profileUuids) { Rules.QProfiles.Builder result = Rules.QProfiles.newBuilder(); if (profileUuids.isEmpty()) { return result; } // load profiles Map<String, QProfileDto> profilesByUuid = dbClient.qualityProfileDao().selectByUuids(dbSession, new ArrayList<>(profileUuids)) .stream() .collect(Collectors.toMap(QProfileDto::getKee, Function.identity())); // load associated parents List<String> parentUuids = profilesByUuid.values().stream() .map(QProfileDto::getParentKee) .filter(StringUtils::isNotEmpty) .filter(uuid -> !profilesByUuid.containsKey(uuid)) .toList(); if (!parentUuids.isEmpty()) { dbClient.qualityProfileDao().selectByUuids(dbSession, parentUuids) .forEach(p -> profilesByUuid.put(p.getKee(), p)); } Map<String, Rules.QProfile> qProfilesMapResponse = result.getMutableQProfiles(); profilesByUuid.values().forEach(p -> writeProfile(qProfilesMapResponse, p)); return result; } private void writeProfile(Map<String, Rules.QProfile> profilesResponse, QProfileDto profile) { Rules.QProfile.Builder profileResponse = Rules.QProfile.newBuilder(); ofNullable(profile.getName()).ifPresent(profileResponse::setName); if (profile.getLanguage() != null) { profileResponse.setLang(profile.getLanguage()); Language language = languages.get(profile.getLanguage()); String langName = language == null ? profile.getLanguage() : language.getName(); profileResponse.setLangName(langName); } ofNullable(profile.getParentKee()).ifPresent(profileResponse::setParent); profilesResponse.put(profile.getKee(), profileResponse.build()); } }
10,386
46
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/AppAction.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.rule.ws; 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.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.GlobalPermission; import org.sonar.server.user.UserSession; public class AppAction implements RulesWsAction { private final Languages languages; private final DbClient dbClient; private final UserSession userSession; public AppAction(Languages languages, DbClient dbClient, UserSession userSession) { this.languages = languages; this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { controller.createAction("app") .setDescription("Get data required for rendering the page 'Coding Rules'.") .setResponseExample(getClass().getResource("app-example.json")) .setSince("4.5") .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { JsonWriter json = response.newJsonWriter(); json.beginObject(); addPermissions(json); addLanguages(json); addRuleRepositories(json, dbSession); json.endObject().close(); } } private void addPermissions(JsonWriter json) { boolean canWrite = userSession.hasPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); json.prop("canWrite", canWrite); } private void addLanguages(JsonWriter json) { json.name("languages").beginObject(); for (Language language : languages.all()) { json.prop(language.getKey(), language.getName()); } json.endObject(); } private void addRuleRepositories(JsonWriter json, DbSession dbSession) { json.name("repositories").beginArray(); dbClient.ruleRepositoryDao() .selectAll(dbSession) .forEach(r -> json.beginObject() .prop("key", r.getKey()) .prop("name", r.getName()) .prop("language", r.getLanguage()) .endObject()); json.endArray(); } }
3,133
33.065217
95
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/CreateAction.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.rule.ws; import com.google.common.io.Resources; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; 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.KeyValueFormat; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.rule.NewCustomRule; import org.sonar.server.rule.ReactivationException; import org.sonar.server.rule.RuleCreator; import org.sonarqube.ws.Rules; import static com.google.common.base.Strings.isNullOrEmpty; import static java.net.HttpURLConnection.HTTP_CONFLICT; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class CreateAction implements RulesWsAction { public static final String PARAM_CUSTOM_KEY = "customKey"; public static final String PARAM_NAME = "name"; public static final String PARAM_DESCRIPTION = "markdownDescription"; public static final String PARAM_SEVERITY = "severity"; public static final String PARAM_STATUS = "status"; public static final String PARAM_TEMPLATE_KEY = "templateKey"; public static final String PARAM_TYPE = "type"; public static final String PARAMS = "params"; public static final String PARAM_PREVENT_REACTIVATION = "preventReactivation"; static final int KEY_MAXIMUM_LENGTH = 200; static final int NAME_MAXIMUM_LENGTH = 200; private final DbClient dbClient; private final RuleCreator ruleCreator; private final RuleMapper ruleMapper; private final RuleWsSupport ruleWsSupport; public CreateAction(DbClient dbClient, RuleCreator ruleCreator, RuleMapper ruleMapper, RuleWsSupport ruleWsSupport) { this.dbClient = dbClient; this.ruleCreator = ruleCreator; this.ruleMapper = ruleMapper; this.ruleWsSupport = ruleWsSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("create") .setPost(true) .setDescription("Create a custom rule.<br>" + "Requires the 'Administer Quality Profiles' permission") .setResponseExample(Resources.getResource(getClass(), "create-example.json")) .setSince("4.4") .setChangelog( new Change("10.0","Drop deprecated keys: 'custom_key', 'template_key', 'markdown_description', 'prevent_reactivation'"), new Change("5.5", "Creating manual rule is not more possible")) .setHandler(this); action .createParam(PARAM_CUSTOM_KEY) .setRequired(true) .setMaximumLength(KEY_MAXIMUM_LENGTH) .setDescription("Key of the custom rule") .setExampleValue("Todo_should_not_be_used"); action .createParam(PARAM_TEMPLATE_KEY) .setRequired(true) .setDescription("Key of the template rule in order to create a custom rule (mandatory for custom rule)") .setExampleValue("java:XPath"); action .createParam(PARAM_NAME) .setRequired(true) .setMaximumLength(NAME_MAXIMUM_LENGTH) .setDescription("Rule name") .setExampleValue("My custom rule"); action .createParam(PARAM_DESCRIPTION) .setRequired(true) .setDescription("Rule description in <a href='/formatting/help'>markdown format</a>") .setExampleValue("Description of my custom rule"); action .createParam(PARAM_SEVERITY) .setPossibleValues(Severity.ALL) .setDefaultValue(Severity.MAJOR) .setDescription("Rule severity"); action .createParam(PARAM_STATUS) .setPossibleValues( Arrays.stream(RuleStatus.values()) .filter(status -> !RuleStatus.REMOVED.equals(status)) .toList()) .setDefaultValue(RuleStatus.READY) .setDescription("Rule status"); action.createParam(PARAMS) .setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only for custom rule)"); action .createParam(PARAM_PREVENT_REACTIVATION) .setBooleanPossibleValues() .setDefaultValue(false) .setDescription("If set to true and if the rule has been deactivated (status 'REMOVED'), a status 409 will be returned"); action.createParam(PARAM_TYPE) .setPossibleValues(RuleType.names()) .setDescription("Rule type") .setSince("6.7"); } @Override public void handle(Request request, Response response) throws Exception { ruleWsSupport.checkQProfileAdminPermission(); String customKey = request.mandatoryParam(PARAM_CUSTOM_KEY); try (DbSession dbSession = dbClient.openSession(false)) { try { NewCustomRule newRule = NewCustomRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY))) .setName(request.mandatoryParam(PARAM_NAME)) .setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION)) .setSeverity(request.mandatoryParam(PARAM_SEVERITY)) .setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS))) .setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION)); String params = request.param(PARAMS); if (!isNullOrEmpty(params)) { newRule.setParameters(KeyValueFormat.parse(params)); } ofNullable(request.param(PARAM_TYPE)).ifPresent(t -> newRule.setType(RuleType.valueOf(t))); writeResponse(dbSession, request, response, ruleCreator.create(dbSession, newRule)); } catch (ReactivationException e) { response.stream().setStatus(HTTP_CONFLICT); writeResponse(dbSession, request, response, e.ruleKey()); } } } private void writeResponse(DbSession dbSession, Request request, Response response, RuleKey ruleKey) { writeProtobuf(createResponse(dbSession, ruleKey), request, response); } private Rules.CreateResponse createResponse(DbSession dbSession, RuleKey ruleKey) { RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, ruleKey) .orElseThrow(() -> new IllegalStateException(String.format("Cannot load rule, that has just been created '%s'", ruleKey))); List<RuleDto> templateRules = new ArrayList<>(); if (rule.isCustomRule()) { Optional<RuleDto> templateRule = dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession); templateRule.ifPresent(templateRules::add); } List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid())); SearchAction.SearchResult searchResult = new SearchAction.SearchResult() .setRuleParameters(ruleParameters) .setTemplateRules(templateRules) .setTotal(1L); return Rules.CreateResponse.newBuilder() .setRule(ruleMapper.toWsRule(rule, searchResult, Collections.emptySet())) .build(); } }
8,071
40.183673
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/DeleteAction.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.rule.ws; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; 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.rule.RuleDto; import org.sonar.server.qualityprofile.QProfileRules; import org.sonar.server.rule.index.RuleIndexer; import static com.google.common.base.Preconditions.checkArgument; public class DeleteAction implements RulesWsAction { public static final String PARAM_KEY = "key"; private final System2 system2; private final RuleIndexer ruleIndexer; private final DbClient dbClient; private final QProfileRules qProfileRules; private final RuleWsSupport ruleWsSupport; public DeleteAction(System2 system2, RuleIndexer ruleIndexer, DbClient dbClient, QProfileRules qProfileRules, RuleWsSupport ruleWsSupport) { this.system2 = system2; this.ruleIndexer = ruleIndexer; this.dbClient = dbClient; this.qProfileRules = qProfileRules; this.ruleWsSupport = ruleWsSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("delete") .setDescription("Delete custom rule.<br/>" + "Requires the 'Administer Quality Profiles' permission") .setSince("4.4") .setPost(true) .setHandler(this); action .createParam(PARAM_KEY) .setDescription("Rule key") .setRequired(true) .setExampleValue("java:S1144"); } @Override public void handle(Request request, Response response) { ruleWsSupport.checkQProfileAdminPermission(); RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY)); delete(key); } public void delete(RuleKey ruleKey) { try (DbSession dbSession = dbClient.openSession(false)) { RuleDto rule = dbClient.ruleDao().selectOrFailByKey(dbSession, ruleKey); checkArgument(rule.isCustomRule(), "Rule '%s' cannot be deleted because it is not a custom rule", rule.getKey().toString()); qProfileRules.deleteRule(dbSession, rule); rule.setStatus(RuleStatus.REMOVED); rule.setUpdatedAt(system2.now()); dbClient.ruleDao().update(dbSession, rule); ruleIndexer.commitAndIndex(dbSession, rule.getUuid()); } } }
3,257
34.032258
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/EnumUtils.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.rule.ws; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; public class EnumUtils { private EnumUtils() { // prevent instantiation } public static <E extends Enum<E>> List<E> toEnums(@Nullable Iterable<String> values, Class<E> enumClass) { if (values == null) { return Collections.emptyList(); } List<E> result = new ArrayList<>(); for (String s : values) { result.add(Enum.valueOf(enumClass, s)); } return result; } }
1,404
30.931818
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule.ws; import java.util.Set; 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.rule.RuleDto; import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Rules.ListResponse; import static com.google.common.base.Strings.nullToEmpty; import static java.util.stream.Collectors.toSet; public class ListAction implements RulesWsAction { private final DbClient dbClient; public ListAction(DbClient dbClient) { this.dbClient = dbClient; } @Override public void define(WebService.NewController controller) { controller .createAction("list") .setDescription("List rules, excluding the manual rules and the rules with status REMOVED. JSON format is not supported for response.") .setSince("5.2") .setInternal(true) .setResponseExample(getClass().getResource("list-example.txt")) .setHandler(this); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { final ListResponse.Builder listResponseBuilder = ListResponse.newBuilder(); final ListResponse.Rule.Builder ruleBuilder = ListResponse.Rule.newBuilder(); try (DbSession dbSession = dbClient.openSession(false)) { Set<ListResponse.Rule> rules = dbClient.ruleDao().selectEnabled(dbSession).stream() .map(dto -> toRule(ruleBuilder, dto)) .collect(toSet()); listResponseBuilder.addAllRules(rules); } // JSON response is voluntarily not supported. This WS is for internal use. wsResponse.stream().setMediaType(MediaTypes.PROTOBUF); listResponseBuilder.build().writeTo(wsResponse.stream().output()); } private static ListResponse.Rule toRule(ListResponse.Rule.Builder ruleBuilder, RuleDto dto) { return ruleBuilder .clear() .setRepository(dto.getRepositoryKey()) .setKey(dto.getRuleKey()) .setName(nullToEmpty(dto.getName())) .setInternalKey(nullToEmpty(dto.getConfigKey())) .build(); } }
2,955
35.95
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RepositoriesAction.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.rule.ws; import com.google.common.io.Resources; import java.util.Collection; 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.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleRepositoryDto; /** * @since 5.1 */ public class RepositoriesAction implements RulesWsAction { private static final String LANGUAGE = "language"; private final DbClient dbClient; public RepositoriesAction(DbClient dbClient) { this.dbClient = dbClient; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("repositories") .setDescription("List available rule repositories") .setSince("4.5") .setHandler(this) .setResponseExample(Resources.getResource(getClass(), "repositories-example.json")); action.createParam(Param.TEXT_QUERY) .setDescription("A pattern to match repository keys/names against") .setExampleValue("java"); action.createParam(LANGUAGE) .setDescription("A language key; if provided, only repositories for the given language will be returned") .setExampleValue("java"); } @Override public void handle(Request request, Response response) throws Exception { String query = request.param(Param.TEXT_QUERY); String languageKey = request.param(LANGUAGE); try (JsonWriter json = response.newJsonWriter()) { json.beginObject().name("repositories").beginArray(); for (RuleRepositoryDto repo : listMatchingRepositories(query, languageKey)) { json .beginObject() .prop("key", repo.getKey()) .prop("name", repo.getName()) .prop(LANGUAGE, repo.getLanguage()) .endObject(); } json.endArray().endObject(); } } private Collection<RuleRepositoryDto> listMatchingRepositories(@Nullable String query, @Nullable String languageKey) { return selectFromDb(languageKey, query); } private Collection<RuleRepositoryDto> selectFromDb(@Nullable String language, @Nullable String query) { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.ruleRepositoryDao().selectByQueryAndLanguage(dbSession, query, language); } } }
3,353
34.680851
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RuleMapper.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.rule.ws; import java.util.Collections; import java.util.List; import java.util.Locale; 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 javax.annotation.Nullable; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction; import org.sonar.db.rule.DeprecatedRuleKeyDto; import org.sonar.db.rule.RuleDescriptionSectionContextDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.user.UserDto; import org.sonar.markdown.Markdown; import org.sonar.server.rule.RuleDescriptionFormatter; import org.sonar.server.rule.ws.SearchAction.SearchResult; import org.sonar.server.text.MacroInterpreter; import org.sonarqube.ws.Common; import org.sonarqube.ws.Common.RuleScope; import org.sonarqube.ws.Rules; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.db.rule.RuleDto.Format.MARKDOWN; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_CREATED_AT; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DEBT_REM_FUNCTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DEFAULT_DEBT_REM_FUNCTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DEFAULT_REM_FUNCTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DEPRECATED_KEYS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DESCRIPTION_SECTIONS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_EDUCATION_PRINCIPLES; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_GAP_DESCRIPTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_HTML_DESCRIPTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_INTERNAL_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_IS_EXTERNAL; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_IS_TEMPLATE; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_LANGUAGE; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_LANGUAGE_NAME; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_MARKDOWN_DESCRIPTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_NAME; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_NOTE_LOGIN; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_PARAMS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_REM_FUNCTION; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_REM_FUNCTION_OVERLOADED; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_REPO; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_SCOPE; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_SEVERITY; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_STATUS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_SYSTEM_TAGS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_TAGS; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_TEMPLATE_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_UPDATED_AT; import static org.sonarqube.ws.Rules.Rule.DescriptionSection.Context.newBuilder; /** * Conversion of {@link RuleDto} to {@link Rules.Rule} */ public class RuleMapper { private final Languages languages; private final MacroInterpreter macroInterpreter; private final RuleDescriptionFormatter ruleDescriptionFormatter; public RuleMapper(final Languages languages, final MacroInterpreter macroInterpreter, RuleDescriptionFormatter ruleDescriptionFormatter) { this.languages = languages; this.macroInterpreter = macroInterpreter; this.ruleDescriptionFormatter = ruleDescriptionFormatter; } public Rules.Rule toWsRule(RuleDto ruleDefinitionDto, SearchResult result, Set<String> fieldsToReturn) { Rules.Rule.Builder ruleResponse = Rules.Rule.newBuilder(); applyRuleDefinition(ruleResponse, ruleDefinitionDto, result, fieldsToReturn, Collections.emptyMap()); return ruleResponse.build(); } public Rules.Rule toWsRule(RuleDto ruleDto, SearchResult result, Set<String> fieldsToReturn, Map<String, UserDto> usersByUuid, Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) { Rules.Rule.Builder ruleResponse = Rules.Rule.newBuilder(); applyRuleDefinition(ruleResponse, ruleDto, result, fieldsToReturn, deprecatedRuleKeysByRuleUuid); setDebtRemediationFunctionFields(ruleResponse, ruleDto, fieldsToReturn); setNotesFields(ruleResponse, ruleDto, usersByUuid, fieldsToReturn); return ruleResponse.build(); } private Rules.Rule.Builder applyRuleDefinition(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, SearchResult result, Set<String> fieldsToReturn, Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) { // Mandatory fields ruleResponse.setKey(ruleDto.getKey().toString()); ruleResponse.setType(Common.RuleType.forNumber(ruleDto.getType())); // Optional fields setName(ruleResponse, ruleDto, fieldsToReturn); setRepository(ruleResponse, ruleDto, fieldsToReturn); setStatus(ruleResponse, ruleDto, fieldsToReturn); setSysTags(ruleResponse, ruleDto, fieldsToReturn); setParams(ruleResponse, ruleDto, result, fieldsToReturn); setCreatedAt(ruleResponse, ruleDto, fieldsToReturn); setUpdatedAt(ruleResponse, ruleDto, fieldsToReturn); setDescriptionFields(ruleResponse, ruleDto, fieldsToReturn); setSeverity(ruleResponse, ruleDto, fieldsToReturn); setInternalKey(ruleResponse, ruleDto, fieldsToReturn); setLanguage(ruleResponse, ruleDto, fieldsToReturn); setLanguageName(ruleResponse, ruleDto, fieldsToReturn); setIsTemplate(ruleResponse, ruleDto, fieldsToReturn); setIsExternal(ruleResponse, ruleDto, fieldsToReturn); setTemplateKey(ruleResponse, ruleDto, result, fieldsToReturn); setDefaultDebtRemediationFunctionFields(ruleResponse, ruleDto, fieldsToReturn); setGapDescription(ruleResponse, ruleDto, fieldsToReturn); setScope(ruleResponse, ruleDto, fieldsToReturn); setDeprecatedKeys(ruleResponse, ruleDto, fieldsToReturn, deprecatedRuleKeysByRuleUuid); setTags(ruleResponse, ruleDto, fieldsToReturn); setIsRemediationFunctionOverloaded(ruleResponse, ruleDto, fieldsToReturn); if (ruleDto.isAdHoc()) { setAdHocName(ruleResponse, ruleDto, fieldsToReturn); setAdHocDescription(ruleResponse, ruleDto, fieldsToReturn); setAdHocSeverity(ruleResponse, ruleDto, fieldsToReturn); setAdHocType(ruleResponse, ruleDto); } setEducationPrinciples(ruleResponse, ruleDto, fieldsToReturn); return ruleResponse; } private static void setAdHocName(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String adHocName = ruleDto.getAdHocName(); if (adHocName != null && shouldReturnField(fieldsToReturn, FIELD_NAME)) { ruleResponse.setName(adHocName); } } private void setAdHocDescription(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String adHocDescription = ruleDto.getAdHocDescription(); if (adHocDescription != null && shouldReturnField(fieldsToReturn, FIELD_HTML_DESCRIPTION)) { ruleResponse.setHtmlDesc(macroInterpreter.interpret(adHocDescription)); } if (shouldReturnField(fieldsToReturn, FIELD_DESCRIPTION_SECTIONS) && adHocDescription != null) { ruleResponse.clearDescriptionSections(); ruleResponse.getDescriptionSectionsBuilder().addDescriptionSectionsBuilder() .setKey(RuleDescriptionSectionDto.DEFAULT_KEY) .setContent(macroInterpreter.interpret(adHocDescription)); } } private static void setAdHocSeverity(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String severity = ruleDto.getAdHocSeverity(); if (shouldReturnField(fieldsToReturn, FIELD_SEVERITY) && severity != null) { ruleResponse.setSeverity(severity); } } private static void setAdHocType(Rules.Rule.Builder ruleResponse, RuleDto ruleDto) { Integer ruleType = ruleDto.getAdHocType(); if (ruleType != null) { ruleResponse.setType(Common.RuleType.forNumber(ruleType)); } } private static void setRepository(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_REPO)) { ruleResponse.setRepo(ruleDto.getKey().repository()); } } private static void setScope(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_SCOPE)) { ruleResponse.setScope(toWsRuleScope(ruleDto.getScope())); } } private static void setEducationPrinciples(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_EDUCATION_PRINCIPLES)) { ruleResponse.getEducationPrinciplesBuilder().addAllEducationPrinciples((ruleDto.getEducationPrinciples())); } } private static void setDeprecatedKeys(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn, Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) { if (shouldReturnField(fieldsToReturn, FIELD_DEPRECATED_KEYS)) { List<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = deprecatedRuleKeysByRuleUuid.get(ruleDto.getUuid()); if (deprecatedRuleKeyDtos == null) { return; } List<String> deprecatedKeys = deprecatedRuleKeyDtos.stream() .map(r -> RuleKey.of(r.getOldRepositoryKey(), r.getOldRuleKey()).toString()) .toList(); if (!deprecatedKeys.isEmpty()) { ruleResponse.setDeprecatedKeys(Rules.DeprecatedKeys.newBuilder().addAllDeprecatedKey(deprecatedKeys).build()); } } } private static RuleScope toWsRuleScope(Scope scope) { switch (scope) { case ALL: return RuleScope.ALL; case MAIN: return RuleScope.MAIN; case TEST: return RuleScope.TEST; default: throw new IllegalArgumentException("Unknown rule scope: " + scope); } } private static void setGapDescription(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String gapDescription = ruleDto.getGapDescription(); if (shouldReturnField(fieldsToReturn, FIELD_GAP_DESCRIPTION) && gapDescription != null) { ruleResponse.setGapDescription(gapDescription); } } private static void setIsRemediationFunctionOverloaded(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_REM_FUNCTION_OVERLOADED)) { ruleResponse.setRemFnOverloaded(isRemediationFunctionOverloaded(ruleDto)); } } private static void setDefaultDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_DEFAULT_DEBT_REM_FUNCTION) || shouldReturnField(fieldsToReturn, FIELD_DEFAULT_REM_FUNCTION)) { DebtRemediationFunction defaultDebtRemediationFunction = defaultDebtRemediationFunction(ruleDto); if (defaultDebtRemediationFunction != null) { String gapMultiplier = defaultDebtRemediationFunction.gapMultiplier(); if (gapMultiplier != null) { ruleResponse.setDefaultRemFnGapMultiplier(gapMultiplier); } String baseEffort = defaultDebtRemediationFunction.baseEffort(); if (baseEffort != null) { ruleResponse.setDefaultRemFnBaseEffort(baseEffort); } if (defaultDebtRemediationFunction.type() != null) { ruleResponse.setDefaultRemFnType(defaultDebtRemediationFunction.type().name()); // Set deprecated field ruleResponse.setDefaultDebtRemFnType(defaultDebtRemediationFunction.type().name()); } } } } private static void setDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_DEBT_REM_FUNCTION) || shouldReturnField(fieldsToReturn, FIELD_REM_FUNCTION)) { DebtRemediationFunction debtRemediationFunction = debtRemediationFunction(ruleDto); if (debtRemediationFunction != null) { if (debtRemediationFunction.type() != null) { ruleResponse.setRemFnType(debtRemediationFunction.type().name()); // Set deprecated field ruleResponse.setDebtRemFnType(debtRemediationFunction.type().name()); } String gapMultiplier = debtRemediationFunction.gapMultiplier(); if (gapMultiplier != null) { ruleResponse.setRemFnGapMultiplier(gapMultiplier); } String baseEffort = debtRemediationFunction.baseEffort(); if (baseEffort != null) { ruleResponse.setRemFnBaseEffort(baseEffort); } } } } private static void setName(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_NAME) && ruleDto.getName() != null) { ruleResponse.setName(ruleDto.getName()); } } private static void setStatus(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_STATUS) && ruleDto.getStatus() != null) { ruleResponse.setStatus(Common.RuleStatus.valueOf(ruleDto.getStatus().toString())); } } private static void setTags(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_TAGS)) { ruleResponse.getTagsBuilder().addAllTags(ruleDto.getTags()); } } private static void setSysTags(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_SYSTEM_TAGS)) { ruleResponse.getSysTagsBuilder().addAllSysTags(ruleDto.getSystemTags()); } } private static void setParams(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, SearchResult searchResult, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_PARAMS)) { List<RuleParamDto> ruleParameters = searchResult.getRuleParamsByRuleUuid().get(ruleDto.getUuid()); ruleResponse.getParamsBuilder().addAllParams(ruleParameters.stream().map(RuleParamDtoToWsRuleParam.INSTANCE).toList()); } } private static void setCreatedAt(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_CREATED_AT)) { ruleResponse.setCreatedAt(formatDateTime(ruleDto.getCreatedAt())); } } private static void setUpdatedAt(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_UPDATED_AT)) { ruleResponse.setUpdatedAt(formatDateTime(ruleDto.getUpdatedAt())); } } private void setDescriptionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_HTML_DESCRIPTION)) { String htmlDescription = ruleDescriptionFormatter.getDescriptionAsHtml(ruleDto); if (htmlDescription != null) { ruleResponse.setHtmlDesc(macroInterpreter.interpret(htmlDescription)); } } if (shouldReturnField(fieldsToReturn, FIELD_DESCRIPTION_SECTIONS)) { Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = ruleDto.getRuleDescriptionSectionDtos(); Set<Rules.Rule.DescriptionSection> sections = ruleDescriptionSectionDtos.stream() .filter(sectionDto -> !isDefaultAndMoreThanOneSectionPresent(ruleDescriptionSectionDtos, sectionDto)) .map(sectionDto -> toDescriptionSection(ruleDto, sectionDto)) .collect(Collectors.toSet()); ruleResponse.setDescriptionSections(Rules.Rule.DescriptionSections.newBuilder().addAllDescriptionSections(sections).build()); } if (shouldReturnField(fieldsToReturn, FIELD_MARKDOWN_DESCRIPTION)) { if (MARKDOWN.equals(ruleDto.getDescriptionFormat())) { Optional.ofNullable(ruleDto.getDefaultRuleDescriptionSection()) .map(RuleDescriptionSectionDto::getContent) .ifPresent(ruleResponse::setMdDesc); } else { ruleResponse.setMdDesc(ruleResponse.getHtmlDesc()); } } } /** * This was done to preserve backward compatibility with SonarLint until they stop using htmlDesc field in api/rules/[show|search] endpoints, see SONAR-16635 * @deprecated the method should be removed once SonarLint supports rules.descriptionSections fields, I.E in 10.x and DB is cleaned up of non-necessary default sections. */ @Deprecated(since = "9.6", forRemoval = true) private static boolean isDefaultAndMoreThanOneSectionPresent(Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos, RuleDescriptionSectionDto s) { return ruleDescriptionSectionDtos.size() > 1 && s.isDefault(); } private Rules.Rule.DescriptionSection toDescriptionSection(RuleDto ruleDto, RuleDescriptionSectionDto section) { String htmlContent = ruleDescriptionFormatter.toHtml(ruleDto.getDescriptionFormat(), section); String interpretedHtmlContent = macroInterpreter.interpret(htmlContent); Rules.Rule.DescriptionSection.Builder sectionBuilder = Rules.Rule.DescriptionSection.newBuilder() .setKey(section.getKey()) .setContent(interpretedHtmlContent); toProtobufContext(section.getContext()).ifPresent(sectionBuilder::setContext); return sectionBuilder.build(); } private void setNotesFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Map<String, UserDto> usersByUuid, Set<String> fieldsToReturn) { String noteData = ruleDto.getNoteData(); if (shouldReturnField(fieldsToReturn, "htmlNote") && noteData != null) { ruleResponse.setHtmlNote(macroInterpreter.interpret(Markdown.convertToHtml(noteData))); } if (shouldReturnField(fieldsToReturn, "mdNote") && noteData != null) { ruleResponse.setMdNote(noteData); } String userUuid = ruleDto.getNoteUserUuid(); if (shouldReturnField(fieldsToReturn, FIELD_NOTE_LOGIN) && userUuid != null && usersByUuid.containsKey(userUuid)) { ruleResponse.setNoteLogin(usersByUuid.get(userUuid).getLogin()); } } private static void setSeverity(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String severity = ruleDto.getSeverityString(); if (shouldReturnField(fieldsToReturn, FIELD_SEVERITY) && severity != null) { ruleResponse.setSeverity(severity); } } private static void setInternalKey(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_INTERNAL_KEY) && ruleDto.getConfigKey() != null) { ruleResponse.setInternalKey(ruleDto.getConfigKey()); } } private static void setLanguage(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String language = ruleDto.getLanguage(); if (shouldReturnField(fieldsToReturn, FIELD_LANGUAGE) && language != null) { ruleResponse.setLang(language); } } private void setLanguageName(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { String languageKey = ruleDto.getLanguage(); if (shouldReturnField(fieldsToReturn, FIELD_LANGUAGE_NAME) && languageKey != null) { Language language = languages.get(languageKey); ruleResponse.setLangName(language == null ? languageKey : language.getName()); } } private static void setIsTemplate(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_IS_TEMPLATE)) { ruleResponse.setIsTemplate(ruleDto.isTemplate()); } } private static void setIsExternal(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_IS_EXTERNAL)) { ruleResponse.setIsExternal(ruleDto.isExternal()); } } private static void setTemplateKey(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, SearchResult result, Set<String> fieldsToReturn) { if (shouldReturnField(fieldsToReturn, FIELD_TEMPLATE_KEY) && ruleDto.isCustomRule()) { RuleDto templateRule = result.getTemplateRulesByRuleUuid().get(ruleDto.getTemplateUuid()); if (templateRule != null) { ruleResponse.setTemplateKey(templateRule.getKey().toString()); } } } public static boolean shouldReturnField(Set<String> fieldsToReturn, String fieldName) { return fieldsToReturn.isEmpty() || fieldsToReturn.contains(fieldName); } private static Optional<Rules.Rule.DescriptionSection.Context> toProtobufContext(@Nullable RuleDescriptionSectionContextDto context) { return Optional.ofNullable(context) .map(c -> newBuilder() .setKey(c.getKey()) .setDisplayName(c.getDisplayName()) .build()); } private static boolean isRemediationFunctionOverloaded(RuleDto rule) { return rule.getRemediationFunction() != null; } @CheckForNull private static DebtRemediationFunction defaultDebtRemediationFunction(final RuleDto ruleDto) { final String function = ruleDto.getDefRemediationFunction(); if (function == null || function.isEmpty()) { return null; } else { return new DefaultDebtRemediationFunction( DebtRemediationFunction.Type.valueOf(function.toUpperCase(Locale.ENGLISH)), ruleDto.getDefRemediationGapMultiplier(), ruleDto.getDefRemediationBaseEffort()); } } @CheckForNull private static DebtRemediationFunction debtRemediationFunction(RuleDto ruleDto) { final String function = ruleDto.getRemediationFunction(); if (function == null || function.isEmpty()) { return defaultDebtRemediationFunction(ruleDto); } else { return new DefaultDebtRemediationFunction( DebtRemediationFunction.Type.valueOf(function.toUpperCase(Locale.ENGLISH)), ruleDto.getRemediationGapMultiplier(), ruleDto.getRemediationBaseEffort()); } } private enum RuleParamDtoToWsRuleParam implements Function<RuleParamDto, Rules.Rule.Param> { INSTANCE; @Override public Rules.Rule.Param apply(RuleParamDto param) { Rules.Rule.Param.Builder paramResponse = Rules.Rule.Param.newBuilder(); paramResponse.setKey(param.getName()); if (param.getDescription() != null) { paramResponse.setHtmlDesc(Markdown.convertToHtml(param.getDescription())); } String defaultValue = param.getDefaultValue(); if (defaultValue != null) { paramResponse.setDefaultValue(defaultValue); } if (param.getType() != null) { paramResponse.setType(param.getType()); } return paramResponse.build(); } } }
24,088
45.957115
171
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RuleQueryFactory.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.rule.ws; import java.util.Date; import java.util.List; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.server.rule.index.RuleQuery; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.rule.ws.EnumUtils.toEnums; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVATION; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVE_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_AVAILABLE_SINCE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_COMPARE_TO_PROFILE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_CWE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INCLUDE_EXTERNAL; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INHERITANCE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_IS_TEMPLATE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_LANGUAGES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10_2021; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_QPROFILE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_REPOSITORIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_RULE_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SANS_TOP_25; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SONARSOURCE_SECURITY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_STATUSES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TAGS; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TEMPLATE_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TYPES; @ServerSide public class RuleQueryFactory { private final DbClient dbClient; public RuleQueryFactory(DbClient dbClient) { this.dbClient = dbClient; } /** * Similar to {@link #createRuleQuery(DbSession, Request)} but sets additional fields which are only used * for the rule search WS. */ public RuleQuery createRuleSearchQuery(DbSession dbSession, Request request) { RuleQuery query = createRuleQuery(dbSession, request); query.setIncludeExternal(request.mandatoryParamAsBoolean(PARAM_INCLUDE_EXTERNAL)); return query; } /** * Create a {@link RuleQuery} from a {@link Request}. * When a profile key is set, the language of the profile is automatically set in the query */ public RuleQuery createRuleQuery(DbSession dbSession, Request request) { RuleQuery query = new RuleQuery(); query.setQueryText(request.param(WebService.Param.TEXT_QUERY)); query.setSeverities(request.paramAsStrings(PARAM_SEVERITIES)); query.setRepositories(request.paramAsStrings(PARAM_REPOSITORIES)); Date availableSince = request.paramAsDate(PARAM_AVAILABLE_SINCE); query.setAvailableSince(availableSince != null ? availableSince.getTime() : null); query.setStatuses(toEnums(request.paramAsStrings(PARAM_STATUSES), RuleStatus.class)); // Order is important : 1. Load profile, 2. Load compare to profile setProfile(dbSession, query, request); setCompareToProfile(dbSession, query, request); QProfileDto profile = query.getQProfile(); query.setLanguages(profile == null ? request.paramAsStrings(PARAM_LANGUAGES) : List.of(profile.getLanguage())); query.setActivation(request.paramAsBoolean(PARAM_ACTIVATION)); query.setTags(request.paramAsStrings(PARAM_TAGS)); query.setInheritance(request.paramAsStrings(PARAM_INHERITANCE)); query.setActiveSeverities(request.paramAsStrings(PARAM_ACTIVE_SEVERITIES)); query.setIsTemplate(request.paramAsBoolean(PARAM_IS_TEMPLATE)); query.setTemplateKey(request.param(PARAM_TEMPLATE_KEY)); query.setTypes(toEnums(request.paramAsStrings(PARAM_TYPES), RuleType.class)); query.setKey(request.param(PARAM_RULE_KEY)); query.setCwe(request.paramAsStrings(PARAM_CWE)); query.setOwaspTop10(request.paramAsStrings(PARAM_OWASP_TOP_10)); query.setOwaspTop10For2021(request.paramAsStrings(PARAM_OWASP_TOP_10_2021)); query.setSansTop25(request.paramAsStrings(PARAM_SANS_TOP_25)); query.setSonarsourceSecurity(request.paramAsStrings(PARAM_SONARSOURCE_SECURITY)); String sortParam = request.param(WebService.Param.SORT); if (sortParam != null) { query.setSortField(sortParam); query.setAscendingSort(request.mandatoryParamAsBoolean(WebService.Param.ASCENDING)); } return query; } private void setProfile(DbSession dbSession, RuleQuery query, Request request) { String profileUuid = request.param(PARAM_QPROFILE); if (profileUuid == null) { return; } QProfileDto profileOptional = dbClient.qualityProfileDao().selectByUuid(dbSession, profileUuid); QProfileDto profile = checkFound(profileOptional, "The specified qualityProfile '%s' does not exist", profileUuid); query.setQProfile(profile); } private void setCompareToProfile(DbSession dbSession, RuleQuery query, Request request) { String compareToProfileUuid = request.param(PARAM_COMPARE_TO_PROFILE); if (compareToProfileUuid == null) { return; } QProfileDto profileOptional = dbClient.qualityProfileDao().selectByUuid(dbSession, compareToProfileUuid); QProfileDto profile = checkFound(profileOptional, "The specified qualityProfile '%s' does not exist", compareToProfileUuid); query.setCompareToQProfile(profile); } }
6,730
48.131387
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RuleWsSupport.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.rule.ws; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.qualityprofile.ActiveRuleInheritance; import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.SQCategory; import org.sonar.server.user.UserSession; import static org.sonar.api.server.ws.WebService.Param.ASCENDING; import static org.sonar.api.server.ws.WebService.Param.SORT; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVATION; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVE_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_AVAILABLE_SINCE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_COMPARE_TO_PROFILE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_CWE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INCLUDE_EXTERNAL; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INHERITANCE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_IS_TEMPLATE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_LANGUAGES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10_2021; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_QPROFILE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_REPOSITORIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_RULE_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SANS_TOP_25; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SONARSOURCE_SECURITY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_STATUSES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TAGS; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TEMPLATE_KEY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TYPES; @ServerSide public class RuleWsSupport { private final DbClient dbClient; private final UserSession userSession; public RuleWsSupport(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } public void checkQProfileAdminPermission() { userSession .checkLoggedIn() .checkPermission(ADMINISTER_QUALITY_PROFILES); } Map<String, UserDto> getUsersByUuid(DbSession dbSession, List<RuleDto> rules) { Set<String> userUuids = rules.stream().map(RuleDto::getNoteUserUuid).filter(Objects::nonNull).collect(Collectors.toSet()); return dbClient.userDao().selectByUuids(dbSession, userUuids).stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity())); } public static void defineGenericRuleSearchParameters(WebService.NewAction action) { action .createParam(TEXT_QUERY) .setMinimumLength(2) .setDescription("UTF-8 search query") .setExampleValue("xpath"); action .createParam(PARAM_RULE_KEY) .setDescription("Key of rule to search for") .setExampleValue("java:S1144"); action .createParam(PARAM_REPOSITORIES) .setDescription("Comma-separated list of repositories") .setExampleValue("java,html"); action .createParam(PARAM_SEVERITIES) .setDescription("Comma-separated list of default severities. Not the same than severity of rules in Quality profiles.") .setPossibleValues(Severity.ALL) .setExampleValue("CRITICAL,BLOCKER"); action .createParam(PARAM_CWE) .setDescription("Comma-separated list of CWE identifiers. Use '" + SecurityStandards.UNKNOWN_STANDARD + "' to select rules not associated to any CWE.") .setExampleValue("12,125," + SecurityStandards.UNKNOWN_STANDARD); 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) .setDeprecatedSince("10.0") .setDescription("Comma-separated list of SANS Top 25 categories.") .setSince("7.3") .setPossibleValues(SecurityStandards.CWES_BY_SANS_TOP_25.keySet()); action .createParam(PARAM_SONARSOURCE_SECURITY) .setDescription("Comma-separated list of SonarSource security categories. Use '" + SQCategory.OTHERS.getKey() + "' to select rules not associated" + " with any category") .setSince("7.8") .setPossibleValues(Arrays.stream(SQCategory.values()).map(SQCategory::getKey).toList()) .setExampleValue("sql-injection,command-injection,others"); action .createParam(PARAM_LANGUAGES) .setDescription("Comma-separated list of languages") .setExampleValue("java,js"); action .createParam(PARAM_STATUSES) .setDescription("Comma-separated list of status codes") .setPossibleValues(RuleStatus.values()) .setExampleValue(RuleStatus.READY); action .createParam(PARAM_AVAILABLE_SINCE) .setDescription("Filters rules added since date. Format is yyyy-MM-dd") .setExampleValue("2014-06-22"); action .createParam(PARAM_TAGS) .setDescription("Comma-separated list of tags. Returned rules match any of the tags (OR operator)") .setExampleValue("security,java8"); action .createParam(PARAM_TYPES) .setSince("5.5") .setDescription("Comma-separated list of types. Returned rules match any of the tags (OR operator)") .setPossibleValues(RuleType.values()) .setExampleValue(RuleType.BUG); action .createParam(PARAM_ACTIVATION) .setDescription("Filter rules that are activated or deactivated on the selected Quality profile. Ignored if " + "the parameter '" + PARAM_QPROFILE + "' is not set.") .setBooleanPossibleValues(); action .createParam(PARAM_QPROFILE) .setDescription("Quality profile key to filter on. Used only if the parameter '" + PARAM_ACTIVATION + "' is set.") .setExampleValue(UUID_EXAMPLE_01); action.createParam(PARAM_COMPARE_TO_PROFILE) .setDescription("Quality profile key to filter rules that are activated. Meant to compare easily to profile set in '%s'", PARAM_QPROFILE) .setInternal(true) .setSince("6.5") .setExampleValue(UUID_EXAMPLE_02); action .createParam(PARAM_INHERITANCE) .setDescription("Comma-separated list of values of inheritance for a rule within a quality profile. Used only if the parameter '" + PARAM_ACTIVATION + "' is set.") .setPossibleValues(ActiveRuleInheritance.NONE.name(), ActiveRuleInheritance.INHERITED.name(), ActiveRuleInheritance.OVERRIDES.name()) .setExampleValue(ActiveRuleInheritance.INHERITED.name() + "," + ActiveRuleInheritance.OVERRIDES.name()); action .createParam(PARAM_ACTIVE_SEVERITIES) .setDescription("Comma-separated list of activation severities, i.e the severity of rules in Quality profiles.") .setPossibleValues(Severity.ALL) .setExampleValue("CRITICAL,BLOCKER"); action .createParam(PARAM_IS_TEMPLATE) .setDescription("Filter template rules") .setBooleanPossibleValues(); action .createParam(PARAM_TEMPLATE_KEY) .setDescription("Key of the template rule to filter on. Used to search for the custom rules based on this template.") .setExampleValue("java:S001"); action .createParam(SORT) .setDescription("Sort field") .setPossibleValues(RuleIndexDefinition.SORT_FIELDS) .setExampleValue(RuleIndexDefinition.SORT_FIELDS.iterator().next()); action .createParam(ASCENDING) .setDescription("Ascending sort") .setBooleanPossibleValues() .setDefaultValue(true); } static void defineIsExternalParam(WebService.NewAction action) { action .createParam(PARAM_INCLUDE_EXTERNAL) .setDescription("Include external engine rules in the results") .setDefaultValue(false) .setBooleanPossibleValues() .setSince("7.2"); } }
10,101
40.917012
157
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RulesWs.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.rule.ws; import org.sonar.api.server.ws.WebService; public class RulesWs implements WebService { private final RulesWsAction[] actions; public RulesWs(RulesWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context .createController("api/rules") .setDescription("Get and update some details of automatic rules, and manage custom rules."); for (RulesWsAction action : actions) { action.define(controller); } controller.done(); } }
1,428
30.755556
98
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RulesWsAction.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.rule.ws; import org.sonar.server.ws.WsAction; /** * Marker interface for coding rule related actions * */ interface RulesWsAction extends WsAction { // Marker interface }
1,046
32.774194
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/RulesWsParameters.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.rule.ws; import java.util.Set; public class RulesWsParameters { public static final String PARAM_REPOSITORIES = "repositories"; public static final String PARAM_RULE_KEY = "rule_key"; public static final String PARAM_ACTIVATION = "activation"; public static final String PARAM_QPROFILE = "qprofile"; public static final String PARAM_SEVERITIES = "severities"; public static final String PARAM_AVAILABLE_SINCE = "available_since"; public static final String PARAM_STATUSES = "statuses"; public static final String PARAM_LANGUAGES = "languages"; public static final String PARAM_TAGS = "tags"; public static final String PARAM_TYPES = "types"; public static final String PARAM_CWE = "cwe"; public static final String PARAM_OWASP_TOP_10 = "owaspTop10"; public 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) public static final String PARAM_SANS_TOP_25 = "sansTop25"; public static final String PARAM_SONARSOURCE_SECURITY = "sonarsourceSecurity"; public static final String PARAM_INHERITANCE = "inheritance"; public static final String PARAM_ACTIVE_SEVERITIES = "active_severities"; public static final String PARAM_IS_TEMPLATE = "is_template"; public static final String PARAM_INCLUDE_EXTERNAL = "include_external"; public static final String PARAM_TEMPLATE_KEY = "template_key"; public static final String PARAM_COMPARE_TO_PROFILE = "compareToProfile"; public static final String FIELD_REPO = "repo"; public static final String FIELD_NAME = "name"; public static final String FIELD_CREATED_AT = "createdAt"; public static final String FIELD_UPDATED_AT = "updatedAt"; public static final String FIELD_SEVERITY = "severity"; public static final String FIELD_STATUS = "status"; public static final String FIELD_INTERNAL_KEY = "internalKey"; public static final String FIELD_IS_EXTERNAL = "isExternal"; public static final String FIELD_IS_TEMPLATE = "isTemplate"; public static final String FIELD_TEMPLATE_KEY = "templateKey"; public static final String FIELD_TAGS = "tags"; public static final String FIELD_SYSTEM_TAGS = "sysTags"; public static final String FIELD_LANGUAGE = "lang"; public static final String FIELD_LANGUAGE_NAME = "langName"; public static final String FIELD_HTML_DESCRIPTION = "htmlDesc"; public static final String FIELD_MARKDOWN_DESCRIPTION = "mdDesc"; public static final String FIELD_DESCRIPTION_SECTIONS = "descriptionSections"; public static final String FIELD_EDUCATION_PRINCIPLES = "educationPrinciples"; public static final String FIELD_NOTE_LOGIN = "noteLogin"; public static final String FIELD_MARKDOWN_NOTE = "mdNote"; public static final String FIELD_HTML_NOTE = "htmlNote"; /** * Value for 'f' parameter which is used to return all the "defaultDebtRemFn" fields. * * @deprecated since 10.0, replaced by {@link #FIELD_DEFAULT_REM_FUNCTION} */ @Deprecated(since = "10.0") public static final String FIELD_DEFAULT_DEBT_REM_FUNCTION = "defaultDebtRemFn"; /** * Value for 'f' parameter which is used to return all the "defaultRemFn" fields. */ public static final String FIELD_DEFAULT_REM_FUNCTION = "defaultRemFn"; /** * Value for 'f' parameter which is used to return all the "debtRemFn" fields. * * @deprecated since 10.0, replaced by {@link #FIELD_REM_FUNCTION} */ @Deprecated(since = "10.0") public static final String FIELD_DEBT_REM_FUNCTION = "debtRemFn"; /** * Value for 'f' parameter which is used to return all the "remFn" fields. */ public static final String FIELD_REM_FUNCTION = "remFn"; public static final String FIELD_GAP_DESCRIPTION = "gapDescription"; public static final String FIELD_REM_FUNCTION_OVERLOADED = "remFnOverloaded"; /** * @since 7.1 */ public static final String FIELD_SCOPE = "scope"; public static final String FIELD_PARAMS = "params"; public static final String FIELD_ACTIVES = "actives"; public static final String FIELD_DEPRECATED_KEYS = "deprecatedKeys"; public static final Set<String> OPTIONAL_FIELDS = Set.of(FIELD_REPO, FIELD_NAME, FIELD_CREATED_AT, FIELD_UPDATED_AT, FIELD_SEVERITY, FIELD_STATUS, FIELD_INTERNAL_KEY, FIELD_IS_EXTERNAL, FIELD_IS_TEMPLATE, FIELD_TEMPLATE_KEY, FIELD_TAGS, FIELD_SYSTEM_TAGS, FIELD_LANGUAGE, FIELD_LANGUAGE_NAME, FIELD_HTML_DESCRIPTION, FIELD_MARKDOWN_DESCRIPTION, FIELD_DESCRIPTION_SECTIONS, FIELD_NOTE_LOGIN, FIELD_MARKDOWN_NOTE, FIELD_HTML_NOTE, FIELD_DEFAULT_DEBT_REM_FUNCTION, FIELD_DEBT_REM_FUNCTION, FIELD_DEFAULT_REM_FUNCTION, FIELD_GAP_DESCRIPTION, FIELD_REM_FUNCTION_OVERLOADED, FIELD_REM_FUNCTION, FIELD_PARAMS, FIELD_ACTIVES, FIELD_SCOPE, FIELD_DEPRECATED_KEYS, FIELD_EDUCATION_PRINCIPLES); private RulesWsParameters() { // prevent instantiation } }
5,842
47.289256
168
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule.ws; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.DeprecatedRuleKeyDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.Facets; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.rule.index.RuleQuery; import org.sonarqube.ws.Common; import org.sonarqube.ws.Rules.SearchResponse; import static java.lang.String.format; import static org.sonar.api.server.ws.WebService.Param.ASCENDING; import static org.sonar.api.server.ws.WebService.Param.FACETS; import static org.sonar.api.server.ws.WebService.Param.FIELDS; 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.server.es.SearchOptions.MAX_PAGE_SIZE; import static org.sonar.server.rule.index.RuleIndex.ALL_STATUSES_EXCEPT_REMOVED; import static org.sonar.server.rule.index.RuleIndex.FACET_ACTIVE_SEVERITIES; import static org.sonar.server.rule.index.RuleIndex.FACET_CWE; import static org.sonar.server.rule.index.RuleIndex.FACET_LANGUAGES; import static org.sonar.server.rule.index.RuleIndex.FACET_OLD_DEFAULT; import static org.sonar.server.rule.index.RuleIndex.FACET_OWASP_TOP_10; import static org.sonar.server.rule.index.RuleIndex.FACET_OWASP_TOP_10_2021; import static org.sonar.server.rule.index.RuleIndex.FACET_REPOSITORIES; import static org.sonar.server.rule.index.RuleIndex.FACET_SANS_TOP_25; import static org.sonar.server.rule.index.RuleIndex.FACET_SEVERITIES; import static org.sonar.server.rule.index.RuleIndex.FACET_SONARSOURCE_SECURITY; import static org.sonar.server.rule.index.RuleIndex.FACET_STATUSES; import static org.sonar.server.rule.index.RuleIndex.FACET_TAGS; import static org.sonar.server.rule.index.RuleIndex.FACET_TYPES; import static org.sonar.server.rule.ws.RulesWsParameters.FIELD_DEPRECATED_KEYS; import static org.sonar.server.rule.ws.RulesWsParameters.OPTIONAL_FIELDS; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVE_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_CWE; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_LANGUAGES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_OWASP_TOP_10_2021; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_REPOSITORIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SANS_TOP_25; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SEVERITIES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SONARSOURCE_SECURITY; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_STATUSES; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TAGS; import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TYPES; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchAction implements RulesWsAction { public static final String ACTION = "search"; private static final Collection<String> DEFAULT_FACETS = Set.of(PARAM_LANGUAGES, PARAM_REPOSITORIES, "tags"); private static final String[] POSSIBLE_FACETS = new String[]{ FACET_LANGUAGES, FACET_REPOSITORIES, FACET_TAGS, FACET_SEVERITIES, FACET_ACTIVE_SEVERITIES, FACET_STATUSES, FACET_TYPES, FACET_OLD_DEFAULT, FACET_CWE, FACET_OWASP_TOP_10, FACET_OWASP_TOP_10_2021, FACET_SANS_TOP_25, FACET_SONARSOURCE_SECURITY}; private final RuleQueryFactory ruleQueryFactory; private final DbClient dbClient; private final RuleIndex ruleIndex; private final ActiveRuleCompleter activeRuleCompleter; private final RuleMapper mapper; private final RuleWsSupport ruleWsSupport; public SearchAction(RuleIndex ruleIndex, ActiveRuleCompleter activeRuleCompleter, RuleQueryFactory ruleQueryFactory, DbClient dbClient, RuleMapper mapper, RuleWsSupport ruleWsSupport) { this.ruleIndex = ruleIndex; this.activeRuleCompleter = activeRuleCompleter; this.ruleQueryFactory = ruleQueryFactory; this.dbClient = dbClient; this.mapper = mapper; this.ruleWsSupport = ruleWsSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION) .addPagingParams(100, MAX_PAGE_SIZE) .setHandler(this) .setChangelog( new Change("5.5", "The field 'effortToFixDescription' has been deprecated, use 'gapDescription' instead"), new Change("5.5", "The field 'debtRemFnCoeff' has been deprecated, use 'remFnGapMultiplier' instead"), new Change("5.5", "The field 'defaultDebtRemFnCoeff' has been deprecated, use 'defaultRemFnGapMultiplier' instead"), new Change("5.5", "The field 'debtRemFnOffset' has been deprecated, use 'remFnBaseEffort' instead"), new Change("5.5", "The field 'defaultDebtRemFnOffset' has been deprecated, use 'defaultRemFnBaseEffort' instead"), new Change("5.5", "The field 'debtOverloaded' has been deprecated, use 'remFnOverloaded' instead"), new Change("7.1", "The field 'scope' has been added to the response"), new Change("7.1", "The field 'scope' has been added to the 'f' parameter"), new Change("7.2", "The field 'isExternal' has been added to the response"), new Change("7.2", "The field 'includeExternal' has been added to the 'f' parameter"), new Change("7.5", "The field 'updatedAt' has been added to the 'f' parameter"), new Change("9.5", "The field 'htmlDesc' has been deprecated, use 'descriptionSections' instead"), new Change("9.5", "The field 'descriptionSections' has been added to the payload"), new Change("9.5", "The field 'descriptionSections' has been added to the 'f' parameter"), new Change("9.6", "'descriptionSections' can optionally embed a context field"), new Change("9.6", "The field 'educationPrinciples' has been added to the 'f' parameter"), new Change("9.8", "response fields 'total', 's', 'ps' have been deprecated, please use 'paging' object instead"), new Change("9.8", "The field 'paging' has been added to the response"), new Change("10.0", "The deprecated field 'effortToFixDescription' has been removed, use 'gapDescription' instead."), new Change("10.0", "The deprecated field 'debtRemFnCoeff' has been removed, use 'remFnGapMultiplier' instead."), new Change("10.0", "The deprecated field 'defaultDebtRemFnCoeff' has been removed, use 'defaultRemFnGapMultiplier' instead."), new Change("10.0", "The deprecated field 'debtRemFnOffset' has been removed, use 'remFnBaseEffort' instead."), new Change("10.0", "The deprecated field 'defaultDebtRemFnOffset' has been removed, use 'defaultRemFnBaseEffort' instead."), new Change("10.0", "The deprecated field 'debtOverloaded' has been removed, use 'remFnOverloaded' instead."), new Change("10.0", "The field 'defaultDebtRemFnType' has been deprecated, use 'defaultRemFnType' instead"), new Change("10.0", "The field 'debtRemFnType' has been deprecated, use 'remFnType' instead"), new Change("10.0", "The value 'debtRemFn' for the 'f' parameter has been deprecated, use 'remFn' instead"), new Change("10.0", "The value 'defaultDebtRemFn' for the 'f' parameter has been deprecated, use 'defaultRemFn' instead"), new Change("10.0", "The value 'sansTop25' for the parameter 'facets' has been deprecated"), new Change("10.0", "Parameter 'sansTop25' is deprecated") ); action.createParam(FACETS) .setDescription("Comma-separated list of the facets to be computed. No facet is computed by default.") .setPossibleValues(POSSIBLE_FACETS) .setExampleValue(format("%s,%s", POSSIBLE_FACETS[0], POSSIBLE_FACETS[1])); WebService.NewParam paramFields = action.createParam(FIELDS) .setDescription("Comma-separated list of additional fields to be returned in the response. All the fields are returned by default, except actives.") .setPossibleValues(Ordering.natural().sortedCopy(OPTIONAL_FIELDS)); Iterator<String> it = OPTIONAL_FIELDS.iterator(); paramFields.setExampleValue(format("%s,%s", it.next(), it.next())); action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>") .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); // Rule-specific search parameters RuleWsSupport.defineGenericRuleSearchParameters(action); RuleWsSupport.defineIsExternalParam(action); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { SearchRequest searchWsRequest = toSearchWsRequest(request); SearchOptions context = buildSearchOptions(searchWsRequest); RuleQuery query = ruleQueryFactory.createRuleSearchQuery(dbSession, request); SearchResult searchResult = doSearch(dbSession, query, context); SearchResponse responseBuilder = buildResponse(dbSession, searchWsRequest, context, searchResult, query); writeProtobuf(responseBuilder, request, response); } } private SearchResponse buildResponse(DbSession dbSession, SearchRequest request, SearchOptions context, SearchResult result, RuleQuery query) { SearchResponse.Builder responseBuilder = SearchResponse.newBuilder(); writeStatistics(responseBuilder, result, context); doContextResponse(dbSession, request, result, responseBuilder, query); if (!context.getFacets().isEmpty()) { writeFacets(responseBuilder, request, context, result); } return responseBuilder.build(); } private static void writeStatistics(SearchResponse.Builder response, SearchResult searchResult, SearchOptions context) { response.setTotal(searchResult.total); response.setP(context.getPage()); response.setPs(context.getLimit()); response.setPaging(formatPaging(searchResult.total, context.getPage(), context.getLimit())); } private static Common.Paging.Builder formatPaging(Long total, int pageIndex, int limit) { return Common.Paging.newBuilder() .setPageIndex(pageIndex) .setPageSize(limit) .setTotal(total.intValue()); } private void writeRules(DbSession dbSession, SearchResponse.Builder response, SearchResult result, SearchOptions context) { Map<String, UserDto> usersByUuid = ruleWsSupport.getUsersByUuid(dbSession, result.rules); Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid = getDeprecatedRuleKeysByRuleUuid(dbSession, result.rules, context); result.rules.forEach(rule -> response.addRules(mapper.toWsRule(rule, result, context.getFields(), usersByUuid, deprecatedRuleKeysByRuleUuid))); } private Map<String, List<DeprecatedRuleKeyDto>> getDeprecatedRuleKeysByRuleUuid(DbSession dbSession, List<RuleDto> rules, SearchOptions context) { if (!RuleMapper.shouldReturnField(context.getFields(), FIELD_DEPRECATED_KEYS)) { return Collections.emptyMap(); } Set<String> ruleUuidsSet = rules.stream() .map(RuleDto::getUuid) .collect(Collectors.toSet()); if (ruleUuidsSet.isEmpty()) { return Collections.emptyMap(); } else { return dbClient.ruleDao().selectDeprecatedRuleKeysByRuleUuids(dbSession, ruleUuidsSet).stream() .collect(Collectors.groupingBy(DeprecatedRuleKeyDto::getRuleUuid)); } } private static SearchOptions buildSearchOptions(SearchRequest request) { SearchOptions context = loadCommonContext(request); SearchOptions searchOptions = new SearchOptions() .setLimit(context.getLimit()) .setOffset(context.getOffset()); if (context.getFacets().contains(RuleIndex.FACET_OLD_DEFAULT)) { searchOptions.addFacets(DEFAULT_FACETS); } else { searchOptions.addFacets(context.getFacets()); } return searchOptions; } private static SearchOptions loadCommonContext(SearchRequest request) { int pageSize = Integer.parseInt(request.getPs()); SearchOptions context = new SearchOptions().addFields(request.getF()); if (request.getFacets() != null) { context.addFacets(request.getFacets()); } if (pageSize < 1) { context.setPage(Integer.parseInt(request.getP()), 0).setLimit(MAX_PAGE_SIZE); } else { context.setPage(Integer.parseInt(request.getP()), pageSize); } return context; } private SearchResult doSearch(DbSession dbSession, RuleQuery query, SearchOptions context) { SearchIdResult<String> result = ruleIndex.search(query, context); List<String> ruleUuids = result.getUuids(); // rule order is managed by ES, this order by must be kept when fetching rule details Map<String, RuleDto> rulesByRuleKey = Maps.uniqueIndex(dbClient.ruleDao().selectByUuids(dbSession, ruleUuids), RuleDto::getUuid); List<RuleDto> rules = new ArrayList<>(); for (String ruleUuid : ruleUuids) { RuleDto rule = rulesByRuleKey.get(ruleUuid); if (rule != null) { rules.add(rule); } } List<String> templateRuleUuids = rules.stream() .map(RuleDto::getTemplateUuid) .filter(Objects::nonNull) .toList(); List<RuleDto> templateRules = dbClient.ruleDao().selectByUuids(dbSession, templateRuleUuids); List<RuleParamDto> ruleParamDtos = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, ruleUuids); return new SearchResult() .setRules(rules) .setRuleParameters(ruleParamDtos) .setTemplateRules(templateRules) .setFacets(result.getFacets()) .setTotal(result.getTotal()); } private void doContextResponse(DbSession dbSession, SearchRequest request, SearchResult result, SearchResponse.Builder response, RuleQuery query) { SearchOptions contextForResponse = loadCommonContext(request); writeRules(dbSession, response, result, contextForResponse); if (contextForResponse.getFields().contains("actives")) { activeRuleCompleter.completeSearch(dbSession, query, result.rules, response); } } private static void writeFacets(SearchResponse.Builder response, SearchRequest request, SearchOptions context, SearchResult results) { addMandatoryFacetValues(results, FACET_LANGUAGES, request.getLanguages()); addMandatoryFacetValues(results, FACET_REPOSITORIES, request.getRepositories()); addMandatoryFacetValues(results, FACET_STATUSES, ALL_STATUSES_EXCEPT_REMOVED); addMandatoryFacetValues(results, FACET_SEVERITIES, Severity.ALL); addMandatoryFacetValues(results, FACET_ACTIVE_SEVERITIES, Severity.ALL); addMandatoryFacetValues(results, FACET_TAGS, request.getTags()); addMandatoryFacetValues(results, FACET_TYPES, RuleType.names()); addMandatoryFacetValues(results, FACET_CWE, request.getCwe()); addMandatoryFacetValues(results, FACET_OWASP_TOP_10, request.getOwaspTop10()); addMandatoryFacetValues(results, FACET_OWASP_TOP_10_2021, request.getOwaspTop10For2021()); addMandatoryFacetValues(results, FACET_SANS_TOP_25, request.getSansTop25()); addMandatoryFacetValues(results, FACET_SONARSOURCE_SECURITY, request.getSonarsourceSecurity()); Common.Facet.Builder facet = Common.Facet.newBuilder(); Common.FacetValue.Builder value = Common.FacetValue.newBuilder(); Map<String, List<String>> facetValuesByFacetKey = new HashMap<>(); facetValuesByFacetKey.put(FACET_LANGUAGES, request.getLanguages()); facetValuesByFacetKey.put(FACET_REPOSITORIES, request.getRepositories()); facetValuesByFacetKey.put(FACET_STATUSES, request.getStatuses()); facetValuesByFacetKey.put(FACET_SEVERITIES, request.getSeverities()); facetValuesByFacetKey.put(FACET_ACTIVE_SEVERITIES, request.getActiveSeverities()); facetValuesByFacetKey.put(FACET_TAGS, request.getTags()); facetValuesByFacetKey.put(FACET_TYPES, request.getTypes()); facetValuesByFacetKey.put(FACET_CWE, request.getCwe()); facetValuesByFacetKey.put(FACET_OWASP_TOP_10, request.getOwaspTop10()); facetValuesByFacetKey.put(FACET_OWASP_TOP_10_2021, request.getOwaspTop10For2021()); facetValuesByFacetKey.put(FACET_SANS_TOP_25, request.getSansTop25()); facetValuesByFacetKey.put(FACET_SONARSOURCE_SECURITY, request.getSonarsourceSecurity()); for (String facetName : context.getFacets()) { facet.clear().setProperty(facetName); Map<String, Long> facets = results.facets.get(facetName); if (facets != null) { Set<String> itemsFromFacets = new HashSet<>(); for (Map.Entry<String, Long> facetValue : facets.entrySet()) { itemsFromFacets.add(facetValue.getKey()); facet.addValues(value .clear() .setVal(facetValue.getKey()) .setCount(facetValue.getValue())); } addZeroFacetsForSelectedItems(facet, facetValuesByFacetKey.get(facetName), itemsFromFacets); } response.getFacetsBuilder().addFacets(facet); } } private static void addZeroFacetsForSelectedItems(Common.Facet.Builder facet, @Nullable List<String> requestParams, Set<String> itemsFromFacets) { if (requestParams != null) { Common.FacetValue.Builder value = Common.FacetValue.newBuilder(); for (String param : requestParams) { if (!itemsFromFacets.contains(param)) { facet.addValues(value.clear() .setVal(param) .setCount(0L)); } } } } private static void addMandatoryFacetValues(SearchResult results, String facetName, @Nullable Collection<String> mandatoryValues) { Map<String, Long> facetValues = results.facets.get(facetName); if (facetValues != null) { Collection<String> valuesToAdd = mandatoryValues == null ? Lists.newArrayList() : mandatoryValues; for (String item : valuesToAdd) { if (!facetValues.containsKey(item)) { facetValues.put(item, 0L); } } } } private static SearchRequest toSearchWsRequest(Request request) { request.mandatoryParamAsBoolean(ASCENDING); return new SearchRequest() .setActiveSeverities(request.paramAsStrings(PARAM_ACTIVE_SEVERITIES)) .setF(request.paramAsStrings(FIELDS)) .setFacets(request.paramAsStrings(FACETS)) .setLanguages(request.paramAsStrings(PARAM_LANGUAGES)) .setP("" + request.mandatoryParamAsInt(PAGE)) .setPs("" + request.mandatoryParamAsInt(PAGE_SIZE)) .setRepositories(request.paramAsStrings(PARAM_REPOSITORIES)) .setSeverities(request.paramAsStrings(PARAM_SEVERITIES)) .setStatuses(request.paramAsStrings(PARAM_STATUSES)) .setTags(request.paramAsStrings(PARAM_TAGS)) .setTypes(request.paramAsStrings(PARAM_TYPES)) .setCwe(request.paramAsStrings(PARAM_CWE)) .setOwaspTop10(request.paramAsStrings(PARAM_OWASP_TOP_10)) .setOwaspTop10For2021(request.paramAsStrings(PARAM_OWASP_TOP_10_2021)) .setSansTop25(request.paramAsStrings(PARAM_SANS_TOP_25)) .setSonarsourceSecurity(request.paramAsStrings(PARAM_SONARSOURCE_SECURITY)); } static class SearchResult { private List<RuleDto> rules; private final ListMultimap<String, RuleParamDto> ruleParamsByRuleUuid; private final Map<String, RuleDto> templateRulesByRuleUuid; private Long total; private Facets facets; public SearchResult() { this.rules = new ArrayList<>(); this.ruleParamsByRuleUuid = ArrayListMultimap.create(); this.templateRulesByRuleUuid = new HashMap<>(); } public List<RuleDto> getRules() { return rules; } public SearchResult setRules(List<RuleDto> rules) { this.rules = rules; return this; } public ListMultimap<String, RuleParamDto> getRuleParamsByRuleUuid() { return ruleParamsByRuleUuid; } public SearchResult setRuleParameters(List<RuleParamDto> ruleParams) { ruleParamsByRuleUuid.clear(); for (RuleParamDto ruleParam : ruleParams) { ruleParamsByRuleUuid.put(ruleParam.getRuleUuid(), ruleParam); } return this; } public Map<String, RuleDto> getTemplateRulesByRuleUuid() { return templateRulesByRuleUuid; } public SearchResult setTemplateRules(List<RuleDto> templateRules) { templateRulesByRuleUuid.clear(); for (RuleDto templateRule : templateRules) { templateRulesByRuleUuid.put(templateRule.getUuid(), templateRule); } return this; } @CheckForNull public Long getTotal() { return total; } public SearchResult setTotal(Long total) { this.total = total; return this; } @CheckForNull public Facets getFacets() { return facets; } public SearchResult setFacets(Facets facets) { this.facets = facets; return this; } } private static class SearchRequest { private List<String> activeSeverities; private List<String> f; private List<String> facets; private List<String> languages; private String p; private String ps; private List<String> repositories; private List<String> severities; private List<String> statuses; private List<String> tags; private List<String> types; private List<String> cwe; private List<String> owaspTop10; private List<String> owaspTop10For2021; private List<String> sansTop25; private List<String> sonarsourceSecurity; private SearchRequest setActiveSeverities(List<String> activeSeverities) { this.activeSeverities = activeSeverities; return this; } private List<String> getActiveSeverities() { return activeSeverities; } private SearchRequest setF(List<String> f) { this.f = f; return this; } private List<String> getF() { return f; } private SearchRequest setFacets(List<String> facets) { this.facets = facets; return this; } private List<String> getFacets() { return facets; } private SearchRequest setLanguages(List<String> languages) { this.languages = languages; return this; } private List<String> getLanguages() { return languages; } private SearchRequest setP(String p) { this.p = p; return this; } private String getP() { return p; } private SearchRequest setPs(String ps) { this.ps = ps; return this; } private String getPs() { return ps; } private SearchRequest setRepositories(List<String> repositories) { this.repositories = repositories; return this; } private List<String> getRepositories() { return repositories; } private SearchRequest setSeverities(List<String> severities) { this.severities = severities; return this; } private List<String> getSeverities() { return severities; } private SearchRequest setStatuses(List<String> statuses) { this.statuses = statuses; return this; } private List<String> getStatuses() { return statuses; } private SearchRequest setTags(List<String> tags) { this.tags = tags; return this; } private List<String> getTags() { return tags; } private SearchRequest setTypes(@Nullable List<String> types) { this.types = types; return this; } private List<String> getTypes() { return types; } public List<String> getCwe() { return cwe; } public SearchRequest setCwe(@Nullable List<String> cwe) { this.cwe = cwe; return this; } public List<String> getOwaspTop10() { return owaspTop10; } public SearchRequest setOwaspTop10(@Nullable List<String> owaspTop10) { this.owaspTop10 = owaspTop10; return this; } public List<String> getOwaspTop10For2021() { return owaspTop10For2021; } public SearchRequest setOwaspTop10For2021(@Nullable List<String> owaspTop10For2021) { this.owaspTop10For2021 = owaspTop10For2021; return this; } /** * @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) public List<String> getSansTop25() { return sansTop25; } @Deprecated(since = "10.0", forRemoval = true) public SearchRequest setSansTop25(@Nullable List<String> sansTop25) { this.sansTop25 = sansTop25; return this; } public List<String> getSonarsourceSecurity() { return sonarsourceSecurity; } public SearchRequest setSonarsourceSecurity(@Nullable List<String> sonarsourceSecurity) { this.sonarsourceSecurity = sonarsourceSecurity; return this; } } }
26,669
40.477449
156
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule.ws; import com.google.common.io.Resources; import java.util.Collections; import java.util.List; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.exceptions.NotFoundException; import org.sonarqube.ws.Rules.ShowResponse; import static java.lang.String.format; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.server.ws.WsUtils.writeProtobuf; /** * @since 4.4 */ public class ShowAction implements RulesWsAction { public static final String PARAM_KEY = "key"; public static final String PARAM_ACTIVES = "actives"; private final DbClient dbClient; private final RuleMapper mapper; private final ActiveRuleCompleter activeRuleCompleter; private final RuleWsSupport ruleWsSupport; public ShowAction(DbClient dbClient, RuleMapper mapper, ActiveRuleCompleter activeRuleCompleter, RuleWsSupport ruleWsSupport) { this.dbClient = dbClient; this.activeRuleCompleter = activeRuleCompleter; this.mapper = mapper; this.ruleWsSupport = ruleWsSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("show") .setDescription("Get detailed information about a rule<br>") .setSince("4.2") .setResponseExample(Resources.getResource(getClass(), "show-example.json")) .setHandler(this) .setChangelog( new Change("5.5", "The field 'effortToFixDescription' in the response has been deprecated, it becomes 'gapDescription'."), new Change("5.5", "The field 'debtRemFnCoeff' in the response has been deprecated, it becomes 'remFnGapMultiplier'."), new Change("5.5", "The field 'defaultDebtRemFnCoeff' in the response has been deprecated, it becomes 'defaultRemFnGapMultiplier'."), new Change("5.5", "The field 'debtRemFnOffset' in the response has been deprecated, it becomes 'remFnBaseEffort'."), new Change("5.5", "The field 'defaultDebtRemFnOffset' in the response has been deprecated, it becomes 'defaultRemFnBaseEffort'."), new Change("5.5", "The field 'debtOverloaded' in the response has been deprecated, it becomes 'remFnOverloaded'."), new Change("7.1", "The field 'scope' has been added."), new Change("9.5", "The field 'htmlDesc' in the response has been deprecated, it becomes 'descriptionSections'."), new Change("9.5", "The field 'descriptionSections' has been added to the payload."), new Change("9.6", "'descriptionSections' can optionally embed a context field."), new Change("9.6", "'educationPrinciples' has been added."), new Change("10.0", "The deprecated field 'effortToFixDescription' has been removed, use 'gapDescription' instead."), new Change("10.0", "The deprecated field 'debtRemFnCoeff' has been removed, use 'remFnGapMultiplier' instead."), new Change("10.0", "The deprecated field 'defaultDebtRemFnCoeff' has been removed, use 'defaultRemFnGapMultiplier' instead."), new Change("10.0", "The deprecated field 'debtRemFnOffset' has been removed, use 'remFnBaseEffort' instead."), new Change("10.0", "The deprecated field 'defaultDebtRemFnOffset' has been removed, use 'defaultRemFnBaseEffort' instead."), new Change("10.0", "The deprecated field 'debtOverloaded' has been removed, use 'remFnOverloaded' instead."), new Change("10.0", "The field 'defaultDebtRemFnType' has been deprecated, use 'defaultRemFnType' instead"), new Change("10.0", "The field 'debtRemFnType' has been deprecated, use 'remFnType' instead") ); action .createParam(PARAM_KEY) .setDescription("Rule key") .setRequired(true) .setExampleValue("javascript:EmptyBlock"); action .createParam(PARAM_ACTIVES) .setDescription("Show rule's activations for all profiles (\"active rules\")") .setBooleanPossibleValues() .setDefaultValue(false); } @Override public void handle(Request request, Response response) throws Exception { RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY)); try (DbSession dbSession = dbClient.openSession(false)) { RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key) .orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key))); List<RuleDto> templateRules = ofNullable(rule.getTemplateUuid()) .flatMap(templateUuid -> dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession)) .map(Collections::singletonList).orElseGet(Collections::emptyList); List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid())); ShowResponse showResponse = buildResponse(dbSession, request, new SearchAction.SearchResult() .setRules(singletonList(rule)) .setTemplateRules(templateRules) .setRuleParameters(ruleParameters) .setTotal(1L)); writeProtobuf(showResponse, request, response); } } private ShowResponse buildResponse(DbSession dbSession, Request request, SearchAction.SearchResult searchResult) { ShowResponse.Builder responseBuilder = ShowResponse.newBuilder(); RuleDto rule = searchResult.getRules().get(0); responseBuilder.setRule(mapper.toWsRule(rule, searchResult, Collections.emptySet(), ruleWsSupport.getUsersByUuid(dbSession, searchResult.getRules()), emptyMap())); if (request.mandatoryParamAsBoolean(PARAM_ACTIVES)) { activeRuleCompleter.completeShow(dbSession, rule).forEach(responseBuilder::addActives); } return responseBuilder.build(); } }
6,884
48.178571
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule.ws; import com.google.common.io.Resources; 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.api.server.ws.WebService.Param; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.rule.index.RuleIndex; public class TagsAction implements RulesWsAction { private final RuleIndex ruleIndex; public TagsAction(RuleIndex ruleIndex) { this.ruleIndex = ruleIndex; } @Override public void define(WebService.NewController controller) { NewAction action = controller .createAction("tags") .setDescription("List rule tags") .setSince("4.4") .setHandler(this) .setResponseExample(Resources.getResource(getClass(), "tags-example.json")) .setChangelog(new Change("9.4", "Max page size increased to 500")); action.createSearchQuery("misra", "tags"); action.createPageSize(10, 500); } @Override public void handle(Request request, Response response) { String query = request.param(Param.TEXT_QUERY); int pageSize = request.mandatoryParamAsInt("ps"); List<String> tags = ruleIndex.listTags(query, pageSize == 0 ? Integer.MAX_VALUE : pageSize); writeResponse(response, tags); } private static void writeResponse(Response response, List<String> tags) { try (JsonWriter json = response.newJsonWriter()) { json.beginObject().name("tags").beginArray(); tags.forEach(json::value); json.endArray().endObject(); } } }
2,512
33.902778
96
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/ws/UpdateAction.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.rule.ws; import com.google.common.base.Splitter; import com.google.common.io.Resources; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction; 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.KeyValueFormat; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.rule.RuleUpdate; import org.sonar.server.rule.RuleUpdater; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Rules.UpdateResponse; import static com.google.common.collect.Sets.newHashSet; import static java.lang.String.format; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.server.rule.ws.CreateAction.KEY_MAXIMUM_LENGTH; import static org.sonar.server.rule.ws.CreateAction.NAME_MAXIMUM_LENGTH; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class UpdateAction implements RulesWsAction { public static final String PARAM_KEY = "key"; public static final String PARAM_TAGS = "tags"; public static final String PARAM_MARKDOWN_NOTE = "markdown_note"; public static final String PARAM_REMEDIATION_FN_TYPE = "remediation_fn_type"; public static final String PARAM_REMEDIATION_FN_BASE_EFFORT = "remediation_fn_base_effort"; public static final String PARAM_REMEDIATION_FN_GAP_MULTIPLIER = "remediation_fy_gap_multiplier"; public static final String PARAM_NAME = "name"; public static final String PARAM_DESCRIPTION = "markdown_description"; public static final String PARAM_SEVERITY = "severity"; public static final String PARAM_STATUS = "status"; public static final String PARAMS = "params"; private final DbClient dbClient; private final RuleUpdater ruleUpdater; private final RuleMapper mapper; private final UserSession userSession; private final RuleWsSupport ruleWsSupport; public UpdateAction(DbClient dbClient, RuleUpdater ruleUpdater, RuleMapper mapper, UserSession userSession, RuleWsSupport ruleWsSupport) { this.dbClient = dbClient; this.ruleUpdater = ruleUpdater; this.mapper = mapper; this.userSession = userSession; this.ruleWsSupport = ruleWsSupport; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("update") .setPost(true) .setResponseExample(Resources.getResource(getClass(), "update-example.json")) .setDescription("Update an existing rule.<br>" + "Requires the 'Administer Quality Profiles' permission") .setSince("4.4") .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(KEY_MAXIMUM_LENGTH) .setDescription("Key of the rule to update") .setExampleValue("javascript:NullCheck"); action.createParam(PARAM_TAGS) .setDescription("Optional comma-separated list of tags to set. Use blank value to remove current tags. Tags " + "are not changed if the parameter is not set.") .setExampleValue("java8,security"); action.createParam(PARAM_MARKDOWN_NOTE) .setDescription("Optional note in <a href='/formatting/help'>markdown format</a>. Use empty value to remove current note. Note is not changed " + "if the parameter is not set.") .setExampleValue("my *note*"); action.createParam(PARAM_REMEDIATION_FN_TYPE) .setDescription("Type of the remediation function of the rule") .setPossibleValues(DebtRemediationFunction.Type.values()) .setSince("5.5"); action.createParam(PARAM_REMEDIATION_FN_BASE_EFFORT) .setDescription("Base effort of the remediation function of the rule") .setExampleValue("1d") .setSince("5.5"); action.createParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER) .setDescription("Gap multiplier of the remediation function of the rule") .setExampleValue("3min") .setSince("5.5"); action .createParam(PARAM_NAME) .setMaximumLength(NAME_MAXIMUM_LENGTH) .setDescription("Rule name (mandatory for custom rule)") .setExampleValue("My custom rule"); action .createParam(PARAM_DESCRIPTION) .setDescription("Rule description (mandatory for custom rule and manual rule) in <a href='/formatting/help'>markdown format</a>") .setExampleValue("Description of my custom rule"); action .createParam(PARAM_SEVERITY) .setDescription("Rule severity (Only when updating a custom rule)") .setPossibleValues(Severity.ALL); action .createParam(PARAM_STATUS) .setPossibleValues(RuleStatus.values()) .setDescription("Rule status (Only when updating a custom rule)"); action.createParam(PARAMS) .setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only when updating a custom rule)"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); try (DbSession dbSession = dbClient.openSession(false)) { ruleWsSupport.checkQProfileAdminPermission(); RuleUpdate update = readRequest(dbSession, request); ruleUpdater.update(dbSession, update, userSession); UpdateResponse updateResponse = buildResponse(dbSession, update.getRuleKey()); writeProtobuf(updateResponse, request, response); } } private RuleUpdate readRequest(DbSession dbSession, Request request) { RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY)); RuleUpdate update = createRuleUpdate(dbSession, key); readTags(request, update); readMarkdownNote(request, update); readDebt(request, update); String name = request.param(PARAM_NAME); if (name != null) { update.setName(name); } String description = request.param(PARAM_DESCRIPTION); if (description != null) { update.setMarkdownDescription(description); } String severity = request.param(PARAM_SEVERITY); if (severity != null) { update.setSeverity(severity); } String status = request.param(PARAM_STATUS); if (status != null) { update.setStatus(RuleStatus.valueOf(status)); } String params = request.param(PARAMS); if (params != null) { update.setParameters(KeyValueFormat.parse(params)); } return update; } private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key) { RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key) .orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key))); return ofNullable(rule.getTemplateUuid()) .map(x -> RuleUpdate.createForCustomRule(key)) .orElseGet(() -> RuleUpdate.createForPluginRule(key)); } private static void readTags(Request request, RuleUpdate update) { String value = request.param(PARAM_TAGS); if (value != null) { if (StringUtils.isBlank(value)) { update.setTags(null); } else { update.setTags(newHashSet(Splitter.on(',').omitEmptyStrings().trimResults().split(value))); } } // else do not touch this field } private static void readMarkdownNote(Request request, RuleUpdate update) { String value = request.param(PARAM_MARKDOWN_NOTE); if (value != null) { update.setMarkdownNote(value); } // else do not touch this field } private static void readDebt(Request request, RuleUpdate update) { String value = request.param(PARAM_REMEDIATION_FN_TYPE); if (value != null) { if (StringUtils.isBlank(value)) { update.setDebtRemediationFunction(null); } else { DebtRemediationFunction fn = new DefaultDebtRemediationFunction( DebtRemediationFunction.Type.valueOf(value), request.param(PARAM_REMEDIATION_FN_GAP_MULTIPLIER), request.param(PARAM_REMEDIATION_FN_BASE_EFFORT)); update.setDebtRemediationFunction(fn); } } } private UpdateResponse buildResponse(DbSession dbSession, RuleKey key) { RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key) .orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key))); List<RuleDto> templateRules = new ArrayList<>(1); if (rule.isCustomRule()) { dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession).ifPresent(templateRules::add); } List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid())); UpdateResponse.Builder responseBuilder = UpdateResponse.newBuilder(); SearchAction.SearchResult searchResult = new SearchAction.SearchResult() .setRules(singletonList(rule)) .setTemplateRules(templateRules) .setRuleParameters(ruleParameters) .setTotal(1L); responseBuilder .setRule(mapper.toWsRule(rule, searchResult, Collections.emptySet(), ruleWsSupport.getUsersByUuid(dbSession, singletonList(rule)), emptyMap())); return responseBuilder.build(); } }
10,391
39.27907
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/rule/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.rule.ws; import javax.annotation.ParametersAreNonnullByDefault;
964
40.956522
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/ws/SamlAction.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.saml.ws; import org.sonar.api.server.ws.Definable; import org.sonar.api.server.ws.WebService; public interface SamlAction extends Definable<WebService.NewController> { }
1,040
37.555556
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/ws/SamlValidationModule.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.saml.ws; import org.sonar.core.platform.Module; public class SamlValidationModule extends Module { @Override protected void configureModule() { add( SamlValidationWs.class, ValidationInitAction.class, ValidationAction.class ); } }
1,133
32.352941
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/ws/SamlValidationWs.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.saml.ws; import java.util.List; import org.sonar.api.server.ws.WebService; import org.sonar.server.authentication.SamlValidationRedirectionFilter; public class SamlValidationWs implements WebService { public static final String SAML_VALIDATION_CONTROLLER = SamlValidationRedirectionFilter.SAML_VALIDATION_CONTROLLER_CONTEXT; private final List<SamlAction> actions; public SamlValidationWs(List<SamlAction> actions) { this.actions = actions; } @Override public void define(WebService.Context context) { WebService.NewController controller = context.createController(SAML_VALIDATION_CONTROLLER); controller.setDescription("Handle SAML validation."); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,632
36.976744
125
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/ws/ValidationAction.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.saml.ws; import java.io.IOException; import java.util.Arrays; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.auth.saml.SamlAuthenticator; import org.sonar.auth.saml.SamlIdentityProvider; import org.sonar.server.authentication.AuthenticationError; import org.sonar.server.authentication.OAuth2ContextFactory; import org.sonar.server.authentication.OAuthCsrfVerifier; import org.sonar.server.authentication.SamlValidationCspHeaders; import org.sonar.server.authentication.SamlValidationRedirectionFilter; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.ws.ServletFilterHandler; import static org.sonar.server.saml.ws.SamlValidationWs.SAML_VALIDATION_CONTROLLER; public class ValidationAction extends HttpFilter implements SamlAction { static final String VALIDATION_CALLBACK_KEY = SamlValidationRedirectionFilter.SAML_VALIDATION_KEY; private static final String URL_DELIMITER = "/"; private final ThreadLocalUserSession userSession; private final SamlAuthenticator samlAuthenticator; private final OAuth2ContextFactory oAuth2ContextFactory; private final SamlIdentityProvider samlIdentityProvider; private final OAuthCsrfVerifier oAuthCsrfVerifier; public ValidationAction(ThreadLocalUserSession userSession, SamlAuthenticator samlAuthenticator, OAuth2ContextFactory oAuth2ContextFactory, SamlIdentityProvider samlIdentityProvider, OAuthCsrfVerifier oAuthCsrfVerifier) { this.samlAuthenticator = samlAuthenticator; this.userSession = userSession; this.oAuth2ContextFactory = oAuth2ContextFactory; this.samlIdentityProvider = samlIdentityProvider; this.oAuthCsrfVerifier = oAuthCsrfVerifier; } @Override public UrlPattern doGetPattern() { return UrlPattern.create(composeUrlPattern(SAML_VALIDATION_CONTROLLER, VALIDATION_CALLBACK_KEY)); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) throws IOException { try { oAuthCsrfVerifier.verifyState(request, response, samlIdentityProvider, "CSRFToken"); } catch (AuthenticationException exception) { AuthenticationError.handleError(request, response, exception.getMessage()); return; } if (!userSession.hasSession() || !userSession.isSystemAdministrator()) { AuthenticationError.handleError(request, response, "User needs to be logged in as system administrator to access this page."); return; } HttpServletRequest httpRequest = new HttpServletRequestWrapper(((JavaxHttpRequest) request).getDelegate()) { @Override public StringBuffer getRequestURL() { return new StringBuffer(oAuth2ContextFactory.generateCallbackUrl(SamlIdentityProvider.KEY)); } }; response.setContentType("text/html"); String htmlResponse = samlAuthenticator.getAuthenticationStatusPage(new JavaxHttpRequest(httpRequest), response); String nonce = SamlValidationCspHeaders.addCspHeadersWithNonceToResponse(response); htmlResponse = htmlResponse.replace("%NONCE%", nonce); response.getWriter().print(htmlResponse); } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction(VALIDATION_CALLBACK_KEY) .setInternal(true) .setPost(true) .setHandler(ServletFilterHandler.INSTANCE) .setDescription("Handle the callback of a SAML assertion from the identity Provider and produces " + "a HTML page with all information available in the assertion.") .setSince("9.7"); action.createParam("SAMLResponse") .setDescription("SAML assertion value") .setRequired(true); } private static String composeUrlPattern(String... parameters) { return Arrays .stream(parameters) .map(URL_DELIMITER::concat) .collect(Collectors.joining()); } }
5,185
41.508197
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/ws/ValidationInitAction.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.saml.ws; import java.io.IOException; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.auth.saml.SamlAuthenticator; import org.sonar.auth.saml.SamlIdentityProvider; import org.sonar.server.authentication.AuthenticationError; import org.sonar.server.authentication.OAuth2ContextFactory; import org.sonar.server.authentication.OAuthCsrfVerifier; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.user.UserSession; import org.sonar.server.ws.ServletFilterHandler; import static org.sonar.server.authentication.SamlValidationRedirectionFilter.SAML_VALIDATION_CONTROLLER_CONTEXT; import static org.sonar.server.authentication.SamlValidationRedirectionFilter.SAML_VALIDATION_KEY; public class ValidationInitAction extends HttpFilter implements SamlAction { public static final String VALIDATION_RELAY_STATE = "validation-query"; public static final String VALIDATION_INIT_KEY = "validation_init"; private final SamlAuthenticator samlAuthenticator; private final OAuthCsrfVerifier oAuthCsrfVerifier; private final OAuth2ContextFactory oAuth2ContextFactory; private final UserSession userSession; public ValidationInitAction(SamlAuthenticator samlAuthenticator, OAuthCsrfVerifier oAuthCsrfVerifier, OAuth2ContextFactory oAuth2ContextFactory, UserSession userSession) { this.samlAuthenticator = samlAuthenticator; this.oAuthCsrfVerifier = oAuthCsrfVerifier; this.oAuth2ContextFactory = oAuth2ContextFactory; this.userSession = userSession; } @Override public UrlPattern doGetPattern() { return UrlPattern.create("/" + SamlValidationWs.SAML_VALIDATION_CONTROLLER + "/" + VALIDATION_INIT_KEY); } @Override public void define(WebService.NewController controller) { controller .createAction(VALIDATION_INIT_KEY) .setInternal(true) .setPost(false) .setHandler(ServletFilterHandler.INSTANCE) .setDescription("Initiate a SAML request to the identity Provider for configuration validation purpose.") .setSince("9.7"); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { try { userSession.checkIsSystemAdministrator(); } catch (ForbiddenException e) { AuthenticationError.handleError(request, response, "User needs to be logged in as system administrator to access this page."); return; } String csrfState = oAuthCsrfVerifier.generateState(request, response); try { samlAuthenticator.initLogin(oAuth2ContextFactory.generateCallbackUrl(SamlIdentityProvider.KEY), VALIDATION_RELAY_STATE + "/" + csrfState, request, response); } catch (IllegalStateException e) { response.sendRedirect("/" + SAML_VALIDATION_CONTROLLER_CONTEXT + "/" + SAML_VALIDATION_KEY); } } }
3,888
41.271739
173
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/saml/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.saml.ws; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ScannerCache.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.scannercache; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbInputStream; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDao; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDao; import org.sonar.db.project.ProjectDto; import org.sonar.db.scannercache.ScannerAnalysisCacheDao; @ServerSide public class ScannerCache { private final DbClient dbClient; private final ScannerAnalysisCacheDao dao; private final ProjectDao projectDao; private final BranchDao branchDao; public ScannerCache(DbClient dbClient, ScannerAnalysisCacheDao dao, ProjectDao projectDao, BranchDao branchDao) { this.dbClient = dbClient; this.dao = dao; this.projectDao = projectDao; this.branchDao = branchDao; } @CheckForNull public DbInputStream get(String branchUuid) { try (DbSession session = dbClient.openSession(false)) { return dao.selectData(session, branchUuid); } } /** * clear all the cache. */ public void clear() { doClear(null, null); } /** * clear the project cache, that is the cache of all the branches of the project. * * @param projectKey the key of the project. */ public void clearProject(String projectKey) { doClear(projectKey, null); } /** * clear the branch cache, that is the cache of this branch only. * * @param projectKey the key of the project. * @param branchKey the key of the specific branch. */ public void clearBranch(String projectKey, String branchKey) { doClear(projectKey, branchKey); } private void doClear(@Nullable final String projectKey, @Nullable final String branchKey) { try (final DbSession session = dbClient.openSession(true)) { if (projectKey == null) { dao.removeAll(session); } else { Optional<ProjectDto> projectDto = projectDao.selectProjectByKey(session, projectKey); projectDto.stream().flatMap(pDto -> { if (branchKey == null) { return branchDao.selectByProject(session, pDto).stream(); } else { return branchDao.selectByKeys(session, pDto.getUuid(), Set.of(branchKey)).stream(); } }) .map(BranchDto::getUuid) .forEach(bUuid -> dao.remove(session, bUuid)); } session.commit(); } } }
3,366
31.68932
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/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.scannercache; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ws/AnalysisCacheWs.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.scannercache.ws; import org.sonar.api.server.ws.WebService; public class AnalysisCacheWs implements WebService { private final AnalysisCacheWsAction[] actions; public AnalysisCacheWs(AnalysisCacheWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context .createController("api/analysis_cache") .setSince("9.4") .setDescription("Access the analysis cache"); for (AnalysisCacheWsAction action : actions) { action.define(controller); } controller.done(); } }
1,461
30.782609
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ws/AnalysisCacheWsAction.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.scannercache.ws; import org.sonar.server.ws.WsAction; /** * Marker interface for coding rule related actions * */ interface AnalysisCacheWsAction extends WsAction { // Marker interface }
1,062
33.290323
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ws/AnalysisCacheWsModule.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.scannercache.ws; import org.sonar.core.platform.Module; public class AnalysisCacheWsModule extends Module { @Override protected void configureModule() { add( AnalysisCacheWs.class, GetAction.class, ClearAction.class ); } }
1,125
32.117647
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ws/ClearAction.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.scannercache.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.permission.GlobalPermission; import org.sonar.server.scannercache.ScannerCache; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; public class ClearAction implements AnalysisCacheWsAction { public static final String PARAM_PROJECT_KEY = "project"; public static final String PARAM_BRANCH_KEY = "branch"; private final UserSession userSession; private final ScannerCache cache; public ClearAction(UserSession userSession, ScannerCache cache) { this.userSession = userSession; this.cache = cache; } @Override public void define(WebService.NewController context) { WebService.NewAction clearDefinition = context.createAction("clear") .setInternal(true) .setPost(true) .setDescription("Clear all or part of the scanner's cached data. Requires global administration permission.") .setSince("9.4") .setHandler(this); clearDefinition.createParam(PARAM_PROJECT_KEY) .setRequired(false) .setSince("9.7") .setDescription("Filter which project's cached data will be cleared with the provided key.") .setExampleValue("org.sonarsource.sonarqube:sonarqube-private"); clearDefinition.createParam(PARAM_BRANCH_KEY) .setRequired(false) .setSince("9.7") .setDescription("Filter which project's branch's cached data will be cleared with the provided key. '" + PARAM_PROJECT_KEY + "' parameter must be set.") .setExampleValue("6468"); } private static class ClearRequestDto { private final String projectKey; private final String branchKey; private ClearRequestDto(Request request) { this.projectKey = request.param(PARAM_PROJECT_KEY); this.branchKey = request.param(PARAM_BRANCH_KEY); } } @Override public void handle(Request request, Response response) throws Exception { checkPermission(); ClearRequestDto params = new ClearRequestDto(request); validateParams(params); if (params.projectKey != null) { if (params.branchKey != null) { cache.clearBranch(params.projectKey, params.branchKey); } else { cache.clearProject(params.projectKey); } } else { cache.clear(); } response.noContent(); } private static void validateParams(ClearRequestDto params) { if (params.branchKey != null) { checkArgument( params.projectKey != null, "{} needs to be specified when {} is present", PARAM_PROJECT_KEY, PARAM_BRANCH_KEY); } } private void checkPermission() { if (!userSession.hasPermission(GlobalPermission.ADMINISTER)) { throw insufficientPrivilegesException(); } } }
3,808
35.27619
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/ws/GetAction.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.scannercache.ws; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.zip.GZIPInputStream; import org.apache.commons.io.IOUtils; 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.DbInputStream; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.scannercache.ScannerCache; import org.sonar.server.user.UserSession; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class GetAction implements AnalysisCacheWsAction { private static final String PROJECT = "project"; private static final String BRANCH = "branch"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; private final ScannerCache cache; public GetAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, ScannerCache cache) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; this.cache = cache; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("get") .setDescription("Get the scanner's cached data for a branch. Requires scan permission on the project. " + "Data is returned gzipped if the corresponding 'Accept-Encoding' header is set in the request.") .setChangelog(new Change("9.9", "The web service is no longer internal")) .setSince("9.4") .setHandler(this); action.createParam(PROJECT) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001) .setRequired(true); action.createParam(BRANCH) .setDescription("Branch key. If not provided, main branch will be used.") .setExampleValue(KEY_BRANCH_EXAMPLE_001) .setRequired(false); } @Override public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PROJECT); String branchKey = request.param(BRANCH); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); checkPermission(project); BranchDto branchDto = componentFinder.getBranchOrPullRequest(dbSession, project, branchKey, null); try (DbInputStream dbInputStream = cache.get(branchDto.getUuid())) { if (dbInputStream == null) { throw new NotFoundException("No cache for given branch or pull request"); } boolean compressed = requestedCompressedData(request); try (OutputStream output = response.stream().output()) { if (compressed) { response.setHeader("Content-Encoding", "gzip"); // data is stored compressed IOUtils.copy(dbInputStream, output); } else { try (InputStream uncompressedInput = new GZIPInputStream(dbInputStream)) { IOUtils.copy(uncompressedInput, output); } } } } } } private static boolean requestedCompressedData(Request request) { return request.header("Accept-Encoding") .map(encoding -> Arrays.stream(encoding.split(",")) .map(String::trim) .anyMatch("gzip"::equals)) .orElse(false); } private void checkPermission(ProjectDto project) { if (userSession.hasEntityPermission(UserRole.SCAN, project) || userSession.hasEntityPermission(UserRole.ADMIN, project) || userSession.hasPermission(SCAN)) { return; } throw insufficientPrivilegesException(); } }
5,061
37.641221
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/scannercache/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.scannercache.ws; import javax.annotation.ParametersAreNonnullByDefault;
972
39.541667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/CheckSecretKeyAction.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.setting.ws; import org.sonar.api.config.internal.Settings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings.CheckSecretKeyWsResponse; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class CheckSecretKeyAction implements SettingsWsAction { private final Settings settings; private final UserSession userSession; public CheckSecretKeyAction(Settings settings, UserSession userSession) { this.settings = settings; this.userSession = userSession; } @Override public void define(WebService.NewController context) { context.createAction("check_secret_key") .setDescription("Check if a secret key is available.<br>" + "Requires the 'Administer System' permission.") .setSince("6.1") .setInternal(true) .setResponseExample(getClass().getResource("check_secret_key-example.json")) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); writeProtobuf(CheckSecretKeyWsResponse.newBuilder().setSecretKeyAvailable(settings.getEncryption().hasSecretKey()).build(), request, response); } }
2,186
36.706897
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/EncryptAction.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.setting.ws; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.Settings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings.EncryptWsResponse; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUE; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class EncryptAction implements SettingsWsAction { private final UserSession userSession; private final Settings settings; public EncryptAction(UserSession userSession, Settings settings) { this.userSession = userSession; this.settings = settings; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("encrypt") .setDescription("Encrypt a setting value.<br>" + "Requires 'Administer System' permission.") .setSince("6.1") .setHandler(this) .setInternal(true) .setResponseExample(getClass().getResource("encrypt-example.json")); action.createParam(PARAM_VALUE) .setRequired(true) .setDescription("Setting value to encrypt") .setExampleValue("my value"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); String value = request.mandatoryParam(PARAM_VALUE); Encryption encryption = settings.getEncryption(); checkRequest(encryption.hasSecretKey(), "No secret key available"); String encryptedValue = encryption.encrypt(value); writeProtobuf(toEncryptWsResponse(encryptedValue), request, response); } private static EncryptWsResponse toEncryptWsResponse(String encryptedValue) { return EncryptWsResponse.newBuilder().setEncryptedValue(encryptedValue).build(); } }
2,848
36
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/GenerateSecretKeyAction.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.setting.ws; import org.sonar.api.config.internal.Settings; 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.audit.AuditPersister; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings.GenerateSecretKeyWsResponse; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class GenerateSecretKeyAction implements SettingsWsAction { private final DbClient dbClient; private final Settings settings; private final UserSession userSession; private final AuditPersister auditPersister; public GenerateSecretKeyAction(DbClient dbClient, Settings settings, UserSession userSession, AuditPersister auditPersister) { this.dbClient = dbClient; this.settings = settings; this.userSession = userSession; this.auditPersister = auditPersister; } @Override public void define(WebService.NewController context) { context.createAction("generate_secret_key") .setDescription("Generate a secret key.<br>" + "Requires the 'Administer System' permission") .setSince("6.1") .setInternal(true) .setResponseExample(getClass().getResource("generate_secret_key-example.json")) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); writeProtobuf(GenerateSecretKeyWsResponse.newBuilder().setSecretKey(settings.getEncryption().generateRandomSecretKey()).build(), request, response); try (DbSession dbSession = dbClient.openSession(false)) { auditPersister.generateSecretKey(dbSession); dbSession.commit(); } } }
2,645
36.8
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ListDefinitionsAction.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.setting.ws; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.PropertyFieldDefinition; 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.entity.EntityDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings; import org.sonarqube.ws.Settings.ListDefinitionsWsResponse; import static com.google.common.base.Strings.emptyToNull; import static java.lang.String.format; import static java.util.Comparator.comparing; import static java.util.Optional.ofNullable; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_COMPONENT; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListDefinitionsAction implements SettingsWsAction { private final DbClient dbClient; private final UserSession userSession; private final PropertyDefinitions propertyDefinitions; private final SettingsWsSupport settingsWsSupport; public ListDefinitionsAction(DbClient dbClient, UserSession userSession, PropertyDefinitions propertyDefinitions, SettingsWsSupport settingsWsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.propertyDefinitions = propertyDefinitions; this.settingsWsSupport = settingsWsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list_definitions") .setDescription("List settings definitions.<br>" + "Requires 'Browse' permission when a component is specified<br/>" + "To access licensed settings, authentication is required<br/>" + "To access secured settings, one of the following permissions is required: " + "<ul>" + "<li>'Execute Analysis'</li>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the specified component</li>" + "</ul>") .setResponseExample(getClass().getResource("list_definitions-example.json")) .setSince("6.3") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Component key") .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { writeProtobuf(doHandle(request), request, response); } private ListDefinitionsWsResponse doHandle(Request request) { ListDefinitionsRequest wsRequest = toWsRequest(request); Optional<EntityDto> component = loadComponent(wsRequest); Optional<String> qualifier = component.map(EntityDto::getQualifier); ListDefinitionsWsResponse.Builder wsResponse = ListDefinitionsWsResponse.newBuilder(); propertyDefinitions.getAll().stream() .filter(definition -> qualifier.map(s -> definition.qualifiers().contains(s)).orElseGet(definition::global)) .filter(definition -> settingsWsSupport.isVisible(definition.key(), component)) .sorted(comparing(PropertyDefinition::category, String::compareToIgnoreCase) .thenComparingInt(PropertyDefinition::index) .thenComparing(PropertyDefinition::name, String::compareToIgnoreCase)) .forEach(definition -> addDefinition(definition, wsResponse)); return wsResponse.build(); } private static ListDefinitionsRequest toWsRequest(Request request) { return new ListDefinitionsRequest() .setComponent(request.param(PARAM_COMPONENT)); } private Optional<EntityDto> loadComponent(ListDefinitionsRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { String entityKey = request.getComponent(); if (entityKey == null) { return Optional.empty(); } EntityDto entity = dbClient.entityDao().selectByKey(dbSession, entityKey) .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", entityKey))); userSession.checkEntityPermission(USER, entity); return Optional.of(entity); } } private void addDefinition(PropertyDefinition definition, ListDefinitionsWsResponse.Builder wsResponse) { String key = definition.key(); Settings.Definition.Builder builder = wsResponse.addDefinitionsBuilder() .setKey(key) .setType(Settings.Type.valueOf(definition.type().name())) .setMultiValues(definition.multiValues()); ofNullable(emptyToNull(definition.deprecatedKey())).ifPresent(builder::setDeprecatedKey); ofNullable(emptyToNull(definition.name())).ifPresent(builder::setName); ofNullable(emptyToNull(definition.description())).ifPresent(builder::setDescription); String category = propertyDefinitions.getCategory(key); ofNullable(emptyToNull(category)).ifPresent(builder::setCategory); String subCategory = propertyDefinitions.getSubCategory(key); ofNullable(emptyToNull(subCategory)).ifPresent(builder::setSubCategory); ofNullable(emptyToNull(definition.defaultValue())).ifPresent(builder::setDefaultValue); List<String> options = definition.options(); if (!options.isEmpty()) { builder.addAllOptions(options); } List<PropertyFieldDefinition> fields = definition.fields(); if (!fields.isEmpty()) { fields.forEach(fieldDefinition -> addField(fieldDefinition, builder)); } } private static void addField(PropertyFieldDefinition fieldDefinition, Settings.Definition.Builder builder) { builder.addFieldsBuilder() .setKey(fieldDefinition.key()) .setName(fieldDefinition.name()) .setDescription(fieldDefinition.description()) .setType(Settings.Type.valueOf(fieldDefinition.type().name())) .addAllOptions(fieldDefinition.options()) .build(); } private static class ListDefinitionsRequest { private String component; public ListDefinitionsRequest setComponent(@Nullable String component) { this.component = component; return this; } @CheckForNull public String getComponent() { return component; } } }
7,539
42.333333
154
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/LoginMessageAction.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.setting.ws; import com.google.common.io.Resources; 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.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.property.PropertyDto; import org.sonar.markdown.Markdown; import org.sonar.server.loginmessage.LoginMessageFeature; import static org.sonar.core.config.WebConstants.SONAR_LOGIN_DISPLAY_MESSAGE; import static org.sonar.core.config.WebConstants.SONAR_LOGIN_MESSAGE; public class LoginMessageAction implements SettingsWsAction { private final DbClient dbClient; private final LoginMessageFeature loginMessageFeature; public LoginMessageAction(DbClient dbClient, LoginMessageFeature loginMessageFeature) { this.dbClient = dbClient; this.loginMessageFeature = loginMessageFeature; } @Override public void define(WebService.NewController controller) { controller.createAction("login_message") .setDescription("Returns the formatted login message, set to the '" + SONAR_LOGIN_MESSAGE + "' property.") .setSince("9.8") .setInternal(true) .setResponseExample(Resources.getResource(getClass(), "example-login-message.json")) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { try (JsonWriter writer = response.newJsonWriter()) { writer.beginObject() .prop("message", isMessageDisplayEnabled() && loginMessageFeature.isAvailable() ? Markdown.convertToHtml(getLoginMessage()) : "") .endObject() .close(); } } /** * Gets the boolean value of the property "sonar.login.displayMessage". * @return True if the property is enabled, false if it's disabled or not set. */ private boolean isMessageDisplayEnabled() { PropertyDto displayMessageProperty = dbClient.propertiesDao().selectGlobalProperty(SONAR_LOGIN_DISPLAY_MESSAGE); return displayMessageProperty != null && Boolean.TRUE.toString().equals(displayMessageProperty.getValue()); } /** * Retrieves the String value of the property "sonar.login.message". * @return The saved String value, or empty String if it's not set. */ private String getLoginMessage() { PropertyDto loginMessageProperty = dbClient.propertiesDao().selectGlobalProperty(SONAR_LOGIN_MESSAGE); return loginMessageProperty != null && loginMessageProperty.getValue() != null ? loginMessageProperty.getValue() : ""; } }
3,368
40.085366
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/PropertySetExtractor.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.setting.ws; import com.google.common.base.Splitter; import java.util.HashSet; import java.util.Set; import org.sonar.api.config.PropertyDefinition; import org.sonar.db.property.PropertyDto; public class PropertySetExtractor { private static final Splitter COMMA_SPLITTER = Splitter.on(","); private PropertySetExtractor() { // Only static stuff } public static Set<String> extractPropertySetKeys(PropertyDto propertyDto, PropertyDefinition definition) { Set<String> propertySetKeys = new HashSet<>(); definition.fields() .forEach(field -> COMMA_SPLITTER.splitToList(propertyDto.getValue()) .forEach(setId -> propertySetKeys.add(generatePropertySetKey(propertyDto.getKey(), setId, field.key())))); return propertySetKeys; } private static String generatePropertySetKey(String propertyBaseKey, String id, String fieldKey) { return propertyBaseKey + "." + id + "." + fieldKey; } }
1,800
36.520833
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ResetAction.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.setting.ws; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; 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.entity.EntityDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.setting.ws.SettingValidations.SettingData; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Collections.emptyList; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_BRANCH; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_COMPONENT; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_KEYS; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_PULL_REQUEST; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class ResetAction implements SettingsWsAction { private final DbClient dbClient; private final SettingsUpdater settingsUpdater; private final UserSession userSession; private final PropertyDefinitions definitions; private final SettingValidations validations; public ResetAction(DbClient dbClient, SettingsUpdater settingsUpdater, UserSession userSession, PropertyDefinitions definitions, SettingValidations validations) { this.dbClient = dbClient; this.settingsUpdater = settingsUpdater; this.userSession = userSession; this.definitions = definitions; this.validations = validations; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("reset") .setDescription("Remove a setting value.<br>" + "The settings defined in conf/sonar.properties are read-only and can't be changed.<br/>" + "Requires one of the following permissions: " + "<ul>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the specified component</li>" + "</ul>") .setSince("6.1") .setChangelog( new Change("10.1", "Param 'component' now only accept keys for projects, applications, portfolios or subportfolios"), new Change("10.1", format("Internal parameters '%s' and '%s' were removed", PARAM_BRANCH, PARAM_PULL_REQUEST)), new Change("8.8", "Deprecated parameter 'componentKey' has been removed"), new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)), new Change("7.1", "The settings defined in conf/sonar.properties are read-only and can't be changed")) .setPost(true) .setHandler(this); action.createParam(PARAM_KEYS) .setDescription("Comma-separated list of keys") .setExampleValue("sonar.links.scm,sonar.debt.hoursInDay") .setRequired(true); action.createParam(PARAM_COMPONENT) .setDescription("Component key. Only keys for projects, applications, portfolios or subportfolios are accepted.") .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { ResetRequest resetRequest = toWsRequest(request); Optional<EntityDto> entity = getEntity(dbSession, resetRequest); checkPermissions(entity); resetRequest.getKeys().forEach(key -> { SettingsWsSupport.validateKey(key); SettingData data = new SettingData(key, emptyList(), entity.orElse(null)); List.of(validations.scope(), validations.qualifier()).forEach(validation -> validation.accept(data)); }); List<String> keys = getKeys(resetRequest); if (entity.isPresent()) { settingsUpdater.deleteComponentSettings(dbSession, entity.get(), keys); } else { settingsUpdater.deleteGlobalSettings(dbSession, keys); } dbSession.commit(); response.noContent(); } } private List<String> getKeys(ResetRequest request) { return new ArrayList<>(request.getKeys().stream() .map(key -> { PropertyDefinition definition = definitions.get(key); return definition != null ? definition.key() : key; }) .collect(Collectors.toSet())); } private static ResetRequest toWsRequest(Request request) { return new ResetRequest() .setKeys(request.mandatoryParamAsStrings(PARAM_KEYS)) .setEntity(request.param(PARAM_COMPONENT)); } private Optional<EntityDto> getEntity(DbSession dbSession, ResetRequest request) { String componentKey = request.getEntity(); if (componentKey == null) { return Optional.empty(); } return Optional.of(dbClient.entityDao().selectByKey(dbSession, componentKey) .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", componentKey)))); } private void checkPermissions(Optional<EntityDto> component) { if (component.isPresent()) { userSession.checkEntityPermission(UserRole.ADMIN, component.get()); } else { userSession.checkIsSystemAdministrator(); } } private static class ResetRequest { private String entity = null; private List<String> keys = null; public ResetRequest setEntity(@Nullable String entity) { this.entity = entity; return this; } @CheckForNull public String getEntity() { return entity; } public ResetRequest setKeys(List<String> keys) { this.keys = keys; return this; } public List<String> getKeys() { return keys; } } }
6,780
37.971264
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SetAction.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.setting.ws; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.PropertyFieldDefinition; 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.entity.EntityDto; import org.sonar.db.property.PropertyDto; import org.sonar.scanner.protocol.GsonHelper; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.setting.SettingsChangeNotifier; import org.sonar.server.setting.ws.SettingValidations.SettingData; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_COMPONENT; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_FIELD_VALUES; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_KEY; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUE; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUES; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class SetAction implements SettingsWsAction { private static final Collector<CharSequence, ?, String> COMMA_JOINER = Collectors.joining(","); private static final String MSG_NO_EMPTY_VALUE = "A non empty value must be provided"; private static final int VALUE_MAXIMUM_LENGTH = 4000; private final PropertyDefinitions propertyDefinitions; private final DbClient dbClient; private final UserSession userSession; private final SettingsUpdater settingsUpdater; private final SettingsChangeNotifier settingsChangeNotifier; private final SettingValidations validations; public SetAction(PropertyDefinitions propertyDefinitions, DbClient dbClient, UserSession userSession, SettingsUpdater settingsUpdater, SettingsChangeNotifier settingsChangeNotifier, SettingValidations validations) { this.propertyDefinitions = propertyDefinitions; this.dbClient = dbClient; this.userSession = userSession; this.settingsUpdater = settingsUpdater; this.settingsChangeNotifier = settingsChangeNotifier; this.validations = validations; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("set") .setDescription("Update a setting value.<br>" + "Either '%s' or '%s' must be provided.<br> " + "The settings defined in conf/sonar.properties are read-only and can't be changed.<br/>" + "Requires one of the following permissions: " + "<ul>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the specified component</li>" + "</ul>", PARAM_VALUE, PARAM_VALUES) .setSince("6.1") .setChangelog( new Change("10.1", "Param 'component' now only accept keys for projects, applications, portfolios or subportfolios"), new Change("10.1", format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("8.8", "Deprecated parameter 'componentKey' has been removed"), new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)), new Change("7.1", "The settings defined in conf/sonar.properties are read-only and can't be changed")) .setPost(true) .setHandler(this); action.createParam(PARAM_KEY) .setDescription("Setting key") .setExampleValue("sonar.core.serverBaseURL") .setRequired(true); action.createParam(PARAM_VALUE) .setMaximumLength(VALUE_MAXIMUM_LENGTH) .setDescription("Setting value. To reset a value, please use the reset web service.") .setExampleValue("http://my-sonarqube-instance.com"); action.createParam(PARAM_VALUES) .setDescription("Setting multi value. To set several values, the parameter must be called once for each value.") .setExampleValue("values=firstValue&values=secondValue&values=thirdValue"); action.createParam(PARAM_FIELD_VALUES) .setDescription("Setting field values. To set several values, the parameter must be called once for each value.") .setExampleValue(PARAM_FIELD_VALUES + "={\"firstField\":\"first value\", \"secondField\":\"second value\", \"thirdField\":\"third value\"}"); action.createParam(PARAM_COMPONENT) .setDescription("Component key. Only keys for projects, applications, portfolios or subportfolios are accepted.") .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { SetRequest wsRequest = toWsRequest(request); SettingsWsSupport.validateKey(wsRequest.getKey()); doHandle(dbSession, wsRequest); } response.noContent(); } private void doHandle(DbSession dbSession, SetRequest request) { Optional<EntityDto> component = searchEntity(dbSession, request); String projectKey = component.map(EntityDto::getKey).orElse(null); String projectName = component.map(EntityDto::getName).orElse(null); String qualifier = component.map(EntityDto::getQualifier).orElse(null); checkPermissions(component); PropertyDefinition definition = propertyDefinitions.get(request.getKey()); String value; commonChecks(request, component); if (!request.getFieldValues().isEmpty()) { value = doHandlePropertySet(dbSession, request, definition, component); } else { validate(request); PropertyDto property = toProperty(request, component); value = property.getValue(); dbClient.propertiesDao().saveProperty(dbSession, property, null, projectKey, projectName, qualifier); } dbSession.commit(); if (!component.isPresent()) { settingsChangeNotifier.onGlobalPropertyChange(persistedKey(request), value); } } private String doHandlePropertySet(DbSession dbSession, SetRequest request, @Nullable PropertyDefinition definition, Optional<EntityDto> component) { validatePropertySet(request, definition); int[] fieldIds = IntStream.rangeClosed(1, request.getFieldValues().size()).toArray(); String inlinedFieldKeys = IntStream.of(fieldIds).mapToObj(String::valueOf).collect(COMMA_JOINER); String key = persistedKey(request); String componentUuid = component.isPresent() ? component.get().getUuid() : null; String componentKey = component.isPresent() ? component.get().getKey() : null; String componentName = component.isPresent() ? component.get().getName() : null; String qualifier = component.isPresent() ? component.get().getQualifier() : null; deleteSettings(dbSession, component, key); dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(key).setValue(inlinedFieldKeys) .setEntityUuid(componentUuid), null, componentKey, componentName, qualifier); List<String> fieldValues = request.getFieldValues(); IntStream.of(fieldIds).boxed() .flatMap(i -> readOneFieldValues(fieldValues.get(i - 1), request.getKey()).entrySet().stream() .map(entry -> new KeyValue(key + "." + i + "." + entry.getKey(), entry.getValue()))) .forEach(keyValue -> dbClient.propertiesDao().saveProperty(dbSession, toFieldProperty(keyValue, componentUuid), null, componentKey, componentName, qualifier)); return inlinedFieldKeys; } private void deleteSettings(DbSession dbSession, Optional<EntityDto> component, String key) { if (component.isPresent()) { settingsUpdater.deleteComponentSettings(dbSession, component.get(), key); } else { settingsUpdater.deleteGlobalSettings(dbSession, key); } } private void commonChecks(SetRequest request, Optional<EntityDto> entity) { checkValueIsSet(request); String settingKey = request.getKey(); SettingData settingData = new SettingData(settingKey, valuesFromRequest(request), entity.orElse(null)); List.of(validations.scope(), validations.qualifier(), validations.valueType()) .forEach(validation -> validation.accept(settingData)); } private static void validatePropertySet(SetRequest request, @Nullable PropertyDefinition definition) { checkRequest(definition != null, "Setting '%s' is undefined", request.getKey()); checkRequest(PropertyType.PROPERTY_SET.equals(definition.type()), "Parameter '%s' is used for setting of property set type only", PARAM_FIELD_VALUES); Set<String> fieldKeys = definition.fields().stream().map(PropertyFieldDefinition::key).collect(Collectors.toSet()); ListMultimap<String, String> valuesByFieldKeys = ArrayListMultimap.create(fieldKeys.size(), request.getFieldValues().size() * fieldKeys.size()); List<Map<String, String>> maps = request.getFieldValues().stream() .map(oneFieldValues -> readOneFieldValues(oneFieldValues, request.getKey())) .toList(); for (Map<String, String> map : maps) { checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE); } List<Map.Entry<String, String>> entries = maps.stream().flatMap(map -> map.entrySet().stream()).toList(); entries.forEach(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue())); entries.forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey())); checkFieldType(request, definition, valuesByFieldKeys); } private void validate(SetRequest request) { PropertyDefinition definition = propertyDefinitions.get(request.getKey()); if (definition == null) { return; } checkSingleOrMultiValue(request, definition); } private static void checkFieldType(SetRequest request, PropertyDefinition definition, ListMultimap<String, String> valuesByFieldKeys) { for (PropertyFieldDefinition fieldDefinition : definition.fields()) { for (String value : valuesByFieldKeys.get(fieldDefinition.key())) { PropertyDefinition.Result result = fieldDefinition.validate(value); checkRequest(result.isValid(), "Error when validating setting with key '%s'. Field '%s' has incorrect value '%s'.", request.getKey(), fieldDefinition.key(), value); } } } private static void checkSingleOrMultiValue(SetRequest request, PropertyDefinition definition) { checkRequest(definition.multiValues() ^ request.getValue() != null, "Parameter '%s' must be used for single value setting. Parameter '%s' must be used for multi value setting.", PARAM_VALUE, PARAM_VALUES); } private static void checkValueIsSet(SetRequest request) { checkRequest( request.getValue() != null ^ !request.getValues().isEmpty() ^ !request.getFieldValues().isEmpty(), "Either '%s', '%s' or '%s' must be provided", PARAM_VALUE, PARAM_VALUES, PARAM_FIELD_VALUES); checkRequest(request.getValues().stream().allMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE); checkRequest(request.getValue() == null || StringUtils.isNotBlank(request.getValue()), MSG_NO_EMPTY_VALUE); } private static List<String> valuesFromRequest(SetRequest request) { return request.getValue() == null ? request.getValues() : Collections.singletonList(request.getValue()); } private String persistedKey(SetRequest request) { PropertyDefinition definition = propertyDefinitions.get(request.getKey()); // handles deprecated key but persist the new key return definition == null ? request.getKey() : definition.key(); } private static String persistedValue(SetRequest request) { return request.getValue() == null ? request.getValues().stream().map(value -> value.replace(",", "%2C")).collect(COMMA_JOINER) : request.getValue(); } private void checkPermissions(Optional<EntityDto> entity) { if (entity.isPresent()) { userSession.checkEntityPermission(UserRole.ADMIN, entity.get()); } else { userSession.checkIsSystemAdministrator(); } } private static SetRequest toWsRequest(Request request) { SetRequest set = new SetRequest() .setKey(request.mandatoryParam(PARAM_KEY)) .setValue(request.param(PARAM_VALUE)) .setValues(request.multiParam(PARAM_VALUES)) .setFieldValues(request.multiParam(PARAM_FIELD_VALUES)) .setEntity(request.param(PARAM_COMPONENT)); checkArgument(set.getValues() != null, "Setting values must not be null"); checkArgument(set.getFieldValues() != null, "Setting fields values must not be null"); return set; } private static Map<String, String> readOneFieldValues(String json, String key) { Type type = new TypeToken<Map<String, String>>() { }.getType(); Gson gson = GsonHelper.create(); try { return gson.fromJson(json, type); } catch (JsonSyntaxException e) { throw BadRequestException.create(format("JSON '%s' does not respect expected format for setting '%s'. Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}", json, key)); } } private Optional<EntityDto> searchEntity(DbSession dbSession, SetRequest request) { String entityKey = request.getEntity(); if (entityKey == null) { return Optional.empty(); } return Optional.of(dbClient.entityDao().selectByKey(dbSession, entityKey) .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", entityKey)))); } private PropertyDto toProperty(SetRequest request, Optional<EntityDto> entity) { String key = persistedKey(request); String value = persistedValue(request); PropertyDto property = new PropertyDto() .setKey(key) .setValue(value); if (entity.isPresent()) { property.setEntityUuid(entity.get().getUuid()); } return property; } private static PropertyDto toFieldProperty(KeyValue keyValue, @Nullable String componentUuid) { return new PropertyDto().setKey(keyValue.key).setValue(keyValue.value).setEntityUuid(componentUuid); } private static class KeyValue { private final String key; private final String value; private KeyValue(String key, String value) { this.key = key; this.value = value; } } private static class SetRequest { private String entity; private List<String> fieldValues; private String key; private String value; private List<String> values; public SetRequest setEntity(@Nullable String entity) { this.entity = entity; return this; } @CheckForNull public String getEntity() { return entity; } public SetRequest setFieldValues(List<String> fieldValues) { this.fieldValues = fieldValues; return this; } public List<String> getFieldValues() { return fieldValues; } public SetRequest setKey(String key) { this.key = key; return this; } public String getKey() { return key; } public SetRequest setValue(@Nullable String value) { this.value = value; return this; } @CheckForNull public String getValue() { return value; } public SetRequest setValues(@Nullable List<String> values) { this.values = values; return this; } public List<String> getValues() { return values; } } }
17,181
40.703883
173
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/Setting.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.setting.ws; import com.google.common.base.Splitter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.PropertyDefinition; import org.sonar.db.property.PropertyDto; public class Setting { private static final Splitter DOT_SPLITTER = Splitter.on(".").omitEmptyStrings(); private final String key; private final String componentUuid; private final String value; private final PropertyDefinition definition; private final List<Map<String, String>> propertySets; private final boolean isDefault; private Setting(PropertyDto propertyDto, List<PropertyDto> propertyDtoSetValues, @Nullable PropertyDefinition definition) { this.key = propertyDto.getKey(); this.value = propertyDto.getValue(); this.componentUuid = propertyDto.getEntityUuid(); this.definition = definition; this.propertySets = buildPropertySetValuesAsMap(key, propertyDtoSetValues); this.isDefault = false; } private Setting(PropertyDefinition definition) { this.key = definition.key(); this.value = definition.defaultValue(); this.componentUuid = null; this.definition = definition; this.propertySets = Collections.emptyList(); this.isDefault = true; } public static Setting createFromDto(PropertyDto propertyDto, List<PropertyDto> propertyDtoSetValues, @Nullable PropertyDefinition definition){ return new Setting(propertyDto, propertyDtoSetValues, definition); } public static Setting createFromDefinition(PropertyDefinition definition){ return new Setting(definition); } public String getKey() { return key; } @CheckForNull public String getComponentUuid() { return componentUuid; } @CheckForNull public PropertyDefinition getDefinition() { return definition; } public String getValue() { return value; } public boolean isDefault() { return isDefault; } public List<Map<String, String>> getPropertySets() { return propertySets; } private static List<Map<String, String>> buildPropertySetValuesAsMap(String propertyKey, List<PropertyDto> propertySets) { if (propertySets.isEmpty()) { return Collections.emptyList(); } Map<String, Map<String, String>> table = new HashMap<>(); propertySets.forEach(property -> { String keyWithoutSettingKey = property.getKey().replace(propertyKey + ".", ""); List<String> setIdWithFieldKey = DOT_SPLITTER.splitToList(keyWithoutSettingKey); String setId = setIdWithFieldKey.get(0); String fieldKey = keyWithoutSettingKey.replaceFirst(setId + ".", ""); table.computeIfAbsent(setId, k -> new HashMap<>()).put(fieldKey, property.getValue()); }); return table.keySet().stream() .map(table::get) .toList(); } }
3,747
32.168142
144
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.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.setting.ws; import com.google.gson.Gson; import com.google.gson.JsonElement; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.resources.Qualifiers; import org.sonar.core.i18n.I18n; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.sonar.server.exceptions.BadRequestException.checkRequest; public class SettingValidations { private static final Set<String> SECURITY_JSON_PROPERTIES = Set.of( "sonar.security.config.javasecurity", "sonar.security.config.phpsecurity", "sonar.security.config.pythonsecurity", "sonar.security.config.roslyn.sonaranalyzer.security.cs" ); private static final Set<String> SUPPORTED_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP, Qualifiers.SUBVIEW); private final PropertyDefinitions definitions; private final DbClient dbClient; private final I18n i18n; public SettingValidations(PropertyDefinitions definitions, DbClient dbClient, I18n i18n) { this.definitions = definitions; this.dbClient = dbClient; this.i18n = i18n; } public Consumer<SettingData> scope() { return data -> { PropertyDefinition definition = definitions.get(data.key); checkRequest(data.entity != null || definition == null || definition.global() || isGlobal(definition), "Setting '%s' cannot be global", data.key); }; } public Consumer<SettingData> qualifier() { return data -> { String qualifier = data.entity == null ? "" : data.entity.getQualifier(); PropertyDefinition definition = definitions.get(data.key); checkRequest(checkComponentQualifier(data, definition), "Setting '%s' cannot be set on a %s", data.key, i18n.message(Locale.ENGLISH, "qualifier." + qualifier, null)); }; } private static boolean checkComponentQualifier(SettingData data, @Nullable PropertyDefinition definition) { EntityDto entity = data.entity; if (entity == null) { return true; } if (definition == null) { return SUPPORTED_QUALIFIERS.contains(entity.getQualifier()); } return definition.qualifiers().contains(entity.getQualifier()); } public Consumer<SettingData> valueType() { return new ValueTypeValidation(); } private static boolean isGlobal(PropertyDefinition definition) { return !definition.global() && definition.qualifiers().isEmpty(); } static class SettingData { private final String key; private final List<String> values; @CheckForNull private final EntityDto entity; SettingData(String key, List<String> values, @Nullable EntityDto entity) { this.key = requireNonNull(key); this.values = requireNonNull(values); this.entity = entity; } } private class ValueTypeValidation implements Consumer<SettingData> { @Override public void accept(SettingData data) { PropertyDefinition definition = definitions.get(data.key); if (definition == null) { return; } if (definition.type() == PropertyType.METRIC) { validateMetric(data); } else if (definition.type() == PropertyType.USER_LOGIN) { validateLogin(data); } else if (definition.type() == PropertyType.JSON) { validateJson(data, definition); } else { validateOtherTypes(data, definition); } } private void validateOtherTypes(SettingData data, PropertyDefinition definition) { data.values.stream() .map(definition::validate) .filter(result -> !result.isValid()) .findAny() .ifPresent(result -> { throw BadRequestException.create(i18n.message(Locale.ENGLISH, "property.error." + result.getErrorKey(), format("Error when validating setting with key '%s' and value [%s]", data.key, data.values.stream().collect(Collectors.joining(", "))))); }); } private void validateMetric(SettingData data) { try (DbSession dbSession = dbClient.openSession(false)) { List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, data.values).stream().filter(MetricDto::isEnabled).toList(); checkRequest(data.values.size() == metrics.size(), "Error when validating metric setting with key '%s' and values [%s]. A value is not a valid metric key.", data.key, data.values.stream().collect(Collectors.joining(", "))); } } private void validateLogin(SettingData data) { try (DbSession dbSession = dbClient.openSession(false)) { List<UserDto> users = dbClient.userDao().selectByLogins(dbSession, data.values).stream().filter(UserDto::isActive).toList(); checkRequest(data.values.size() == users.size(), "Error when validating login setting with key '%s' and values [%s]. A value is not a valid login.", data.key, data.values.stream().collect(Collectors.joining(", "))); } } private void validateJson(SettingData data, PropertyDefinition definition) { Optional<String> jsonContent = data.values.stream().findFirst(); if (jsonContent.isPresent()) { try { new Gson().getAdapter(JsonElement.class).fromJson(jsonContent.get()); validateJsonSchema(jsonContent.get(), definition); } catch (ValidationException e) { throw new IllegalArgumentException(String.format("Provided JSON is invalid [%s]", e.getMessage())); } catch (IOException e) { throw new IllegalArgumentException("Provided JSON is invalid"); } } } private void validateJsonSchema(String json, PropertyDefinition definition) { if (SECURITY_JSON_PROPERTIES.contains(definition.key())) { InputStream jsonSchemaInputStream = this.getClass().getClassLoader().getResourceAsStream("json-schemas/security.json"); if (jsonSchemaInputStream != null) { JSONObject jsonSchema = new JSONObject(new JSONTokener(jsonSchemaInputStream)); JSONObject jsonSubject = new JSONObject(new JSONTokener(json)); SchemaLoader.load(jsonSchema).validate(jsonSubject); } } } } }
7,744
38.717949
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsUpdater.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.setting.ws; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.db.property.PropertyDto; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Arrays.asList; import static org.sonar.server.setting.ws.PropertySetExtractor.extractPropertySetKeys; public class SettingsUpdater { private final DbClient dbClient; private final PropertyDefinitions definitions; public SettingsUpdater(DbClient dbClient, PropertyDefinitions definitions) { this.dbClient = dbClient; this.definitions = definitions; } public void deleteGlobalSettings(DbSession dbSession, String... settingKeys) { deleteGlobalSettings(dbSession, asList(settingKeys)); } public void deleteGlobalSettings(DbSession dbSession, List<String> settingKeys) { checkArgument(!settingKeys.isEmpty(), "At least one setting key is required"); settingKeys.forEach(key -> delete(dbSession, key, null)); } public void deleteComponentSettings(DbSession dbSession, EntityDto entity, String... settingKeys) { deleteComponentSettings(dbSession, entity, asList(settingKeys)); } public void deleteComponentSettings(DbSession dbSession, EntityDto entity, List<String> settingKeys) { checkArgument(!settingKeys.isEmpty(), "At least one setting key is required"); for (String propertyKey : settingKeys) { delete(dbSession, propertyKey, entity); } } private void delete(DbSession dbSession, String settingKey, @Nullable EntityDto entity) { PropertyDefinition definition = definitions.get(settingKey); if (definition == null || !definition.type().equals(PropertyType.PROPERTY_SET)) { deleteSetting(dbSession, settingKey, entity); } else { deletePropertySet(dbSession, settingKey, definition, entity); } } private void deleteSetting(DbSession dbSession, String settingKey, @Nullable EntityDto entity) { if (entity != null) { dbClient.propertiesDao().deleteProjectProperty(dbSession, settingKey, entity.getUuid(), entity.getKey(), entity.getName(), entity.getQualifier()); } else { dbClient.propertiesDao().deleteGlobalProperty(settingKey, dbSession); } } private void deletePropertySet(DbSession dbSession, String settingKey, PropertyDefinition definition, @Nullable EntityDto entity) { Optional<PropertyDto> propertyDto = selectPropertyDto(dbSession, settingKey, entity); if (!propertyDto.isPresent()) { // Setting doesn't exist, nothing to do return; } Set<String> settingSetKeys = extractPropertySetKeys(propertyDto.get(), definition); for (String key : settingSetKeys) { deleteSetting(dbSession, key, entity); } deleteSetting(dbSession, settingKey, entity); } private Optional<PropertyDto> selectPropertyDto(DbSession dbSession, String settingKey, @Nullable EntityDto entity) { if (entity != null) { return Optional.ofNullable(dbClient.propertiesDao().selectProjectProperty(dbSession, entity.getUuid(), settingKey)); } else { return Optional.ofNullable(dbClient.propertiesDao().selectGlobalProperty(dbSession, settingKey)); } } }
4,297
38.796296
133
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWs.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.setting.ws; import org.sonar.api.server.ws.WebService; public class SettingsWs implements WebService { private final SettingsWsAction[] actions; public SettingsWs(SettingsWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/settings") .setDescription("Manage settings.") .setSince("6.1"); for (SettingsWsAction action : actions) { action.define(controller); } controller.done(); } }
1,407
31.744186
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWsAction.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.setting.ws; import org.sonar.server.ws.WsAction; public interface SettingsWsAction extends WsAction { // marker interface }
996
35.925926
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWsModule.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.setting.ws; import org.sonar.core.platform.Module; public class SettingsWsModule extends Module { @Override protected void configureModule() { add( SettingsWs.class, org.sonar.server.setting.ws.SetAction.class, SettingsWsSupport.class, ListDefinitionsAction.class, LoginMessageAction.class, ValuesAction.class, ResetAction.class, EncryptAction.class, GenerateSecretKeyAction.class, CheckSecretKeyAction.class, SettingsUpdater.class, SettingValidations.class); } }
1,416
32.738095
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWsParameters.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.setting.ws; public class SettingsWsParameters { public static final String PARAM_COMPONENT = "component"; public static final String PARAM_BRANCH = "branch"; public static final String PARAM_PULL_REQUEST = "pullRequest"; public static final String PARAM_KEYS = "keys"; public static final String PARAM_KEY = "key"; public static final String PARAM_VALUE = "value"; public static final String PARAM_VALUES = "values"; public static final String PARAM_FIELD_VALUES = "fieldValues"; private SettingsWsParameters() { // Only static stuff } }
1,434
36.763158
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingsWsSupport.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.setting.ws; import com.google.common.annotations.VisibleForTesting; import java.util.Optional; import java.util.Set; import org.sonar.api.server.ServerSide; import org.sonar.api.web.UserRole; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.process.ProcessProperties; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Arrays.stream; import static org.sonar.api.web.UserRole.ADMIN; @ServerSide public class SettingsWsSupport { public static final String DOT_SECURED = ".secured"; @VisibleForTesting static final Set<String> ADMIN_ONLY_SETTINGS = Set.of("sonar.auth.bitbucket.workspaces", "sonar.auth.github.organizations"); private final UserSession userSession; public SettingsWsSupport(UserSession userSession) { this.userSession = userSession; } static void validateKey(String key) { stream(ProcessProperties.Property.values()) .filter(property -> property.getKey().equalsIgnoreCase(key)) .findFirst() .ifPresent(property -> { throw new IllegalArgumentException(format("Setting '%s' can only be used in sonar.properties", key)); }); } boolean isVisible(String key, Optional<EntityDto> component) { if (isAdmin(component)) { return true; } return hasPermission(GlobalPermission.SCAN, UserRole.SCAN, component) || !isProtected(key); } private boolean isAdmin(Optional<EntityDto> component) { return userSession.isSystemAdministrator() || hasPermission(GlobalPermission.ADMINISTER, ADMIN, component); } private static boolean isProtected(String key) { return isSecured(key) || isAdminOnly(key); } static boolean isSecured(String key) { return key.endsWith(DOT_SECURED); } private static boolean isAdminOnly(String key) { return ADMIN_ONLY_SETTINGS.contains(key); } private boolean hasPermission(GlobalPermission orgPermission, String projectPermission, Optional<EntityDto> component) { if (userSession.hasPermission(orgPermission)) { return true; } return component .map(c -> userSession.hasEntityPermission(projectPermission, c)) .orElse(false); } }
3,085
33.288889
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/ValuesAction.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.setting.ws; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; 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.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; 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.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.property.PropertyDto; import org.sonar.markdown.Markdown; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Settings; import org.sonarqube.ws.Settings.ValuesWsResponse; import static java.lang.String.format; import static java.util.stream.Stream.concat; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.sonar.api.CoreProperties.SERVER_ID; import static org.sonar.api.CoreProperties.SERVER_STARTTIME; import static org.sonar.api.PropertyType.FORMATTED_TEXT; import static org.sonar.api.PropertyType.PROPERTY_SET; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.setting.ws.PropertySetExtractor.extractPropertySetKeys; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_COMPONENT; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_KEYS; import static org.sonar.server.setting.ws.SettingsWsSupport.isSecured; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ValuesAction implements SettingsWsAction { private static final Splitter COMMA_SPLITTER = Splitter.on(","); private static final String COMMA_ENCODED_VALUE = "%2C"; private static final Set<String> SERVER_SETTING_KEYS = Set.of(SERVER_STARTTIME, SERVER_ID); private final DbClient dbClient; private final UserSession userSession; private final PropertyDefinitions propertyDefinitions; private final SettingsWsSupport settingsWsSupport; public ValuesAction(DbClient dbClient, UserSession userSession, PropertyDefinitions propertyDefinitions, SettingsWsSupport settingsWsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.propertyDefinitions = propertyDefinitions; this.settingsWsSupport = settingsWsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("values") .setDescription("List settings values.<br>" + "If no value has been set for a setting, then the default value is returned.<br>" + "The settings from conf/sonar.properties are excluded from results.<br>" + "Requires 'Browse' or 'Execute Analysis' permission when a component is specified.<br/>" + "Secured settings values are not returned by the endpoint.<br/>") .setResponseExample(getClass().getResource("values-example.json")) .setSince("6.3") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("9.1", "The secured settings values are no longer returned. Secured settings keys that have a value " + "are now returned in setSecuredSettings array."), new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)), new Change("7.1", "The settings from conf/sonar.properties are excluded from results.")) .setHandler(this); action.createParam(PARAM_KEYS) .setDescription("List of setting keys") .setExampleValue("sonar.test.inclusions,sonar.exclusions"); action.createParam(PARAM_COMPONENT) .setDescription("Component key") .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { writeProtobuf(doHandle(request), request, response); } private ValuesWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(true)) { ValuesRequest valuesRequest = ValuesRequest.from(request); Optional<EntityDto> component = loadComponent(dbSession, valuesRequest); Set<String> keys = loadKeys(valuesRequest); Map<String, String> keysToDisplayMap = getKeysToDisplayMap(keys); List<Setting> settings = loadSettings(dbSession, component, keysToDisplayMap.keySet()); return new ValuesResponseBuilder(settings, component, keysToDisplayMap).build(); } } private Set<String> loadKeys(ValuesRequest valuesRequest) { List<String> keys = valuesRequest.getKeys(); Set<String> result; if (keys == null || keys.isEmpty()) { result = concat(propertyDefinitions.getAll().stream().map(PropertyDefinition::key), SERVER_SETTING_KEYS.stream()).collect(Collectors.toSet()); } else { result = ImmutableSet.copyOf(keys); } result.forEach(SettingsWsSupport::validateKey); return result; } private Optional<EntityDto> loadComponent(DbSession dbSession, ValuesRequest valuesRequest) { String componentKey = valuesRequest.getComponent(); if (componentKey == null) { return Optional.empty(); } EntityDto entity = dbClient.entityDao().selectByKey(dbSession, componentKey) .orElseThrow(() -> new NotFoundException(format("Component key '%s' not found", componentKey))); if (!userSession.hasEntityPermission(USER, entity) && !userSession.hasEntityPermission(UserRole.SCAN, entity) && !userSession.hasPermission(GlobalPermission.SCAN)) { throw insufficientPrivilegesException(); } return Optional.of(entity); } private List<Setting> loadSettings(DbSession dbSession, Optional<EntityDto> component, Set<String> keys) { // List of settings must be kept in the following orders : default -> global -> component List<Setting> settings = new ArrayList<>(); settings.addAll(loadDefaultValues(keys)); settings.addAll(loadGlobalSettings(dbSession, keys)); component.ifPresent(c -> settings.addAll(loadComponentSettings(dbSession, c, keys))); return settings.stream() .filter(s -> settingsWsSupport.isVisible(s.getKey(), component)) .toList(); } private Collection<Setting> loadComponentSettings(DbSession dbSession, EntityDto entity, Set<String> keys) { return loadComponentSettings(dbSession, keys, entity.getUuid()); } private List<Setting> loadDefaultValues(Set<String> keys) { return propertyDefinitions.getAll().stream() .filter(definition -> keys.contains(definition.key())) .filter(defaultProperty -> !isEmpty(defaultProperty.defaultValue())) .map(Setting::createFromDefinition) .toList(); } private Map<String, String> getKeysToDisplayMap(Set<String> keys) { return keys.stream() .collect(Collectors.toMap(propertyDefinitions::validKey, Function.identity(), (u, v) -> { throw new IllegalArgumentException(format("'%s' and '%s' cannot be used at the same time as they refer to the same setting", u, v)); })); } private List<Setting> loadGlobalSettings(DbSession dbSession, Set<String> keys) { List<PropertyDto> properties = dbClient.propertiesDao().selectGlobalPropertiesByKeys(dbSession, keys); List<PropertyDto> propertySets = dbClient.propertiesDao().selectGlobalPropertiesByKeys(dbSession, getPropertySetKeys(properties)); return properties.stream() .map(property -> Setting.createFromDto(property, filterPropertySets(property.getKey(), propertySets, null), propertyDefinitions.get(property.getKey()))) .toList(); } /** * Return list of settings by component uuids */ private Collection<Setting> loadComponentSettings(DbSession dbSession, Set<String> keys, String entityUuid) { List<PropertyDto> properties = dbClient.propertiesDao().selectPropertiesByKeysAndEntityUuids(dbSession, keys, Set.of(entityUuid)); List<PropertyDto> propertySets = dbClient.propertiesDao().selectPropertiesByKeysAndEntityUuids(dbSession, getPropertySetKeys(properties), Set.of(entityUuid)); List<Setting> settings = new LinkedList<>(); for (PropertyDto propertyDto : properties) { String componentUuid = propertyDto.getEntityUuid(); String propertyKey = propertyDto.getKey(); settings.add(Setting.createFromDto(propertyDto, filterPropertySets(propertyKey, propertySets, componentUuid), propertyDefinitions.get(propertyKey))); } return settings; } private Set<String> getPropertySetKeys(List<PropertyDto> properties) { return properties.stream() .filter(propertyDto -> propertyDefinitions.get(propertyDto.getKey()) != null) .filter(propertyDto -> propertyDefinitions.get(propertyDto.getKey()).type().equals(PROPERTY_SET)) .flatMap(propertyDto -> extractPropertySetKeys(propertyDto, propertyDefinitions.get(propertyDto.getKey())).stream()) .collect(Collectors.toSet()); } private static List<PropertyDto> filterPropertySets(String propertyKey, List<PropertyDto> propertySets, @Nullable String componentUuid) { return propertySets.stream() .filter(propertyDto -> Objects.equals(propertyDto.getEntityUuid(), componentUuid)) .filter(propertyDto -> propertyDto.getKey().startsWith(propertyKey + ".")) .toList(); } private class ValuesResponseBuilder { private final List<Setting> settings; private final Optional<EntityDto> requestedComponent; private final ValuesWsResponse.Builder valuesWsBuilder = ValuesWsResponse.newBuilder(); private final Map<String, Settings.Setting.Builder> settingsBuilderByKey = new HashMap<>(); private final Map<String, Setting> settingsByParentKey = new HashMap<>(); private final Map<String, String> keysToDisplayMap; ValuesResponseBuilder(List<Setting> settings, Optional<EntityDto> requestedComponent, Map<String, String> keysToDisplayMap) { this.settings = settings; this.requestedComponent = requestedComponent; this.keysToDisplayMap = keysToDisplayMap; } ValuesWsResponse build() { processSettings(); settingsBuilderByKey.values().forEach(Settings.Setting.Builder::build); return valuesWsBuilder.build(); } private void processSettings() { settings.forEach(setting -> { if (isSecured(setting.getKey())) { if (!setting.isDefault()) { valuesWsBuilder.addSetSecuredSettings(setting.getKey()); } return; } Settings.Setting.Builder valueBuilder = getOrCreateValueBuilder(keysToDisplayMap.get(setting.getKey())); setInherited(setting, valueBuilder); setValue(setting, valueBuilder); setParent(setting, valueBuilder); }); } private Settings.Setting.Builder getOrCreateValueBuilder(String key) { return settingsBuilderByKey.computeIfAbsent(key, k -> valuesWsBuilder.addSettingsBuilder().setKey(key)); } private void setInherited(Setting setting, Settings.Setting.Builder valueBuilder) { boolean isDefault = setting.isDefault(); boolean isGlobal = !requestedComponent.isPresent(); boolean isOnComponent = requestedComponent.isPresent() && Objects.equals(setting.getComponentUuid(), requestedComponent.get().getUuid()); boolean isSet = isGlobal || isOnComponent; valueBuilder.setInherited(isDefault || !isSet); } private void setValue(Setting setting, Settings.Setting.Builder valueBuilder) { PropertyDefinition definition = setting.getDefinition(); String value = setting.getValue(); if (definition == null) { valueBuilder.setValue(value); return; } if (definition.type().equals(PROPERTY_SET)) { valueBuilder.setFieldValues(createFieldValuesBuilder(filterVisiblePropertySets(setting.getPropertySets()))); } else if (definition.type().equals(FORMATTED_TEXT)) { valueBuilder.setValues(createFormattedTextValuesBuilder(value)); } else if (definition.multiValues()) { valueBuilder.setValues(createValuesBuilder(value)); } else { valueBuilder.setValue(value); } } private void setParent(Setting setting, Settings.Setting.Builder valueBuilder) { Setting parent = settingsByParentKey.get(setting.getKey()); if (parent != null) { String value = valueBuilder.getInherited() ? setting.getValue() : parent.getValue(); PropertyDefinition definition = setting.getDefinition(); if (definition == null) { valueBuilder.setParentValue(value); return; } if (definition.type().equals(PROPERTY_SET)) { valueBuilder.setParentFieldValues( createFieldValuesBuilder(valueBuilder.getInherited() ? filterVisiblePropertySets(setting.getPropertySets()) : filterVisiblePropertySets(parent.getPropertySets()))); } else if (definition.multiValues()) { valueBuilder.setParentValues(createValuesBuilder(value)); } else { valueBuilder.setParentValue(value); } } settingsByParentKey.put(setting.getKey(), setting); } private Settings.Values.Builder createValuesBuilder(String value) { List<String> values = COMMA_SPLITTER.splitToList(value).stream().map(v -> v.replace(COMMA_ENCODED_VALUE, ",")).toList(); return Settings.Values.newBuilder().addAllValues(values); } private Settings.Values.Builder createFormattedTextValuesBuilder(String value) { List<String> values = List.of(value, Markdown.convertToHtml(value)); return Settings.Values.newBuilder().addAllValues(values); } private Settings.FieldValues.Builder createFieldValuesBuilder(List<Map<String, String>> fieldValues) { Settings.FieldValues.Builder builder = Settings.FieldValues.newBuilder(); for (Map<String, String> propertySetMap : fieldValues) { builder.addFieldValuesBuilder().putAllValue(propertySetMap); } return builder; } private List<Map<String, String>> filterVisiblePropertySets(List<Map<String, String>> propertySets) { List<Map<String, String>> filteredPropertySets = new ArrayList<>(); propertySets.forEach(map -> { Map<String, String> set = new HashMap<>(); map.entrySet().stream() .filter(entry -> settingsWsSupport.isVisible(entry.getKey(), requestedComponent)) .forEach(entry -> set.put(entry.getKey(), entry.getValue())); filteredPropertySets.add(set); }); return filteredPropertySets; } } private static class ValuesRequest { private String component; private List<String> keys; public ValuesRequest setComponent(@Nullable String component) { this.component = component; return this; } @CheckForNull public String getComponent() { return component; } public ValuesRequest setKeys(@Nullable List<String> keys) { this.keys = keys; return this; } @CheckForNull public List<String> getKeys() { return keys; } private static ValuesRequest from(Request request) { ValuesRequest result = new ValuesRequest() .setComponent(request.param(PARAM_COMPONENT)); if (request.hasParam(PARAM_KEYS)) { result.setKeys(request.paramAsStrings(PARAM_KEYS)); } return result; } } }
16,798
42.97644
176
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/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.setting.ws; import javax.annotation.ParametersAreNonnullByDefault;
967
39.333333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/CharactersReader.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.source; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; class CharactersReader { static final int END_OF_STREAM = -1; private final BufferedReader stringBuffer; private final Deque<String> openTags; private int currentValue; private int previousValue; private int currentIndex = -1; public CharactersReader(BufferedReader stringBuffer) { this.stringBuffer = stringBuffer; this.openTags = new ArrayDeque<>(); } boolean readNextChar() throws IOException { previousValue = currentValue; currentValue = stringBuffer.read(); currentIndex++; return currentValue != END_OF_STREAM; } int getCurrentValue() { return currentValue; } int getPreviousValue() { return previousValue; } int getCurrentIndex() { return currentIndex; } void registerOpenTag(String textType) { openTags.push(textType); } void removeLastOpenTag() { openTags.remove(); } Deque<String> getOpenTags() { return openTags; } }
1,922
24.986486
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/DecorationDataHolder.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.source; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.Iterator; import java.util.List; class DecorationDataHolder { private static final String ENTITY_SEPARATOR = ";"; private static final String FIELD_SEPARATOR = ","; private static final String SYMBOL_PREFIX = "sym-"; private static final String HIGHLIGHTABLE = "sym"; private List<OpeningHtmlTag> openingTagsEntries; private int openingTagsIndex; private List<Integer> closingTagsOffsets; private int closingTagsIndex; DecorationDataHolder() { openingTagsEntries = Lists.newArrayList(); closingTagsOffsets = Lists.newArrayList(); } void loadSymbolReferences(String symbolsReferences) { String[] symbols = symbolsReferences.split(ENTITY_SEPARATOR); for (String symbol : symbols) { String[] symbolFields = symbol.split(FIELD_SEPARATOR); int declarationStartOffset = Integer.parseInt(symbolFields[0]); int declarationEndOffset = Integer.parseInt(symbolFields[1]); int symbolLength = declarationEndOffset - declarationStartOffset; String[] symbolOccurrences = Arrays.copyOfRange(symbolFields, 2, symbolFields.length); loadSymbolOccurrences(declarationStartOffset, symbolLength, symbolOccurrences); } } void loadLineSymbolReferences(String symbolsReferences) { String[] symbols = symbolsReferences.split(ENTITY_SEPARATOR); for (String symbol : symbols) { String[] symbolFields = symbol.split(FIELD_SEPARATOR); int startOffset = Integer.parseInt(symbolFields[0]); int endOffset = Integer.parseInt(symbolFields[1]); int symbolLength = endOffset - startOffset; int symbolId = Integer.parseInt(symbolFields[2]); loadSymbolOccurrences(symbolId, symbolLength, new String[] { Integer.toString(startOffset) }); } } void loadSyntaxHighlightingData(String syntaxHighlightingRules) { String[] rules = syntaxHighlightingRules.split(ENTITY_SEPARATOR); for (String rule : rules) { String[] ruleFields = rule.split(FIELD_SEPARATOR); int startOffset = Integer.parseInt(ruleFields[0]); int endOffset = Integer.parseInt(ruleFields[1]); if (startOffset < endOffset) { insertAndPreserveOrder(new OpeningHtmlTag(startOffset, ruleFields[2]), openingTagsEntries); insertAndPreserveOrder(endOffset, closingTagsOffsets); } } } List<OpeningHtmlTag> getOpeningTagsEntries() { return openingTagsEntries; } OpeningHtmlTag getCurrentOpeningTagEntry() { return openingTagsIndex < openingTagsEntries.size() ? openingTagsEntries.get(openingTagsIndex) : null; } void nextOpeningTagEntry() { openingTagsIndex++; } List<Integer> getClosingTagsOffsets() { return closingTagsOffsets; } int getCurrentClosingTagOffset() { return closingTagsIndex < closingTagsOffsets.size() ? closingTagsOffsets.get(closingTagsIndex) : -1; } void nextClosingTagOffset() { closingTagsIndex++; } private void loadSymbolOccurrences(int declarationStartOffset, int symbolLength, String[] symbolOccurrences) { for (String symbolOccurrence : symbolOccurrences) { int occurrenceStartOffset = Integer.parseInt(symbolOccurrence); int occurrenceEndOffset = occurrenceStartOffset + symbolLength; insertAndPreserveOrder(new OpeningHtmlTag(occurrenceStartOffset, SYMBOL_PREFIX + declarationStartOffset + " " + HIGHLIGHTABLE), openingTagsEntries); insertAndPreserveOrder(occurrenceEndOffset, closingTagsOffsets); } } private static void insertAndPreserveOrder(OpeningHtmlTag newEntry, List<OpeningHtmlTag> openingHtmlTags) { int insertionIndex = 0; Iterator<OpeningHtmlTag> tagIterator = openingHtmlTags.iterator(); while (tagIterator.hasNext() && tagIterator.next().getStartOffset() <= newEntry.getStartOffset()) { insertionIndex++; } openingHtmlTags.add(insertionIndex, newEntry); } private static void insertAndPreserveOrder(int newOffset, List<Integer> orderedOffsets) { int insertionIndex = 0; Iterator<Integer> entriesIterator = orderedOffsets.iterator(); while (entriesIterator.hasNext() && entriesIterator.next() <= newOffset) { insertionIndex++; } orderedOffsets.add(insertionIndex, newOffset); } }
5,147
37.706767
154
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/HtmlSourceDecorator.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.source; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; public class HtmlSourceDecorator { @CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) { decorationDataHolder.loadSyntaxHighlightingData(highlighting); } if (StringUtils.isNotBlank(symbols)) { decorationDataHolder.loadLineSymbolReferences(symbols); } HtmlTextDecorator textDecorator = new HtmlTextDecorator(); List<String> decoratedSource = textDecorator.decorateTextWithHtml(sourceLine, decorationDataHolder, 1, 1); if (decoratedSource == null) { return null; } else { if (decoratedSource.isEmpty()) { return ""; } else { return decoratedSource.get(0); } } } }
1,937
34.236364
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/HtmlTextDecorator.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.source; import com.google.common.io.Closeables; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.slf4j.LoggerFactory; import static com.google.common.collect.Lists.newArrayList; class HtmlTextDecorator { static final char CR_END_OF_LINE = '\r'; static final char LF_END_OF_LINE = '\n'; static final char HTML_OPENING = '<'; static final char HTML_CLOSING = '>'; static final char AMPERSAND = '&'; static final String ENCODED_HTML_OPENING = "&lt;"; static final String ENCODED_HTML_CLOSING = "&gt;"; static final String ENCODED_AMPERSAND = "&amp;"; List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) { return decorateTextWithHtml(text, decorationDataHolder, null, null); } List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder, @Nullable Integer from, @Nullable Integer to) { StringBuilder currentHtmlLine = new StringBuilder(); List<String> decoratedHtmlLines = newArrayList(); int currentLine = 1; BufferedReader stringBuffer = null; try { stringBuffer = new BufferedReader(new StringReader(text)); CharactersReader charsReader = new CharactersReader(stringBuffer); while (charsReader.readNextChar()) { if (shouldStop(currentLine, to)) { break; } if (shouldStartNewLine(charsReader)) { if (canAddLine(currentLine, from)) { decoratedHtmlLines.add(currentHtmlLine.toString()); } currentLine++; currentHtmlLine = new StringBuilder(); } addCharToCurrentLine(charsReader, currentHtmlLine, decorationDataHolder); } closeCurrentSyntaxTags(charsReader, currentHtmlLine); if (shouldStartNewLine(charsReader)) { addLine(decoratedHtmlLines, currentHtmlLine.toString(), currentLine, from, to); currentLine++; addLine(decoratedHtmlLines, "", currentLine, from, to); } else if (currentHtmlLine.length() > 0) { addLine(decoratedHtmlLines, currentHtmlLine.toString(), currentLine, from, to); } } catch (IOException exception) { String errorMsg = "An exception occurred while highlighting the syntax of one of the project's files"; LoggerFactory.getLogger(HtmlTextDecorator.class).error(errorMsg); throw new IllegalStateException(errorMsg, exception); } finally { Closeables.closeQuietly(stringBuffer); } return decoratedHtmlLines; } private static void addCharToCurrentLine(CharactersReader charsReader, StringBuilder currentHtmlLine, DecorationDataHolder decorationDataHolder) { if (shouldStartNewLine(charsReader)) { if (shouldReopenPendingTags(charsReader)) { reopenCurrentSyntaxTags(charsReader, currentHtmlLine); } } int numberOfTagsToClose = getNumberOfTagsToClose(charsReader.getCurrentIndex(), decorationDataHolder); closeCompletedTags(charsReader, numberOfTagsToClose, currentHtmlLine); if (shouldClosePendingTags(charsReader)) { closeCurrentSyntaxTags(charsReader, currentHtmlLine); } Collection<String> tagsToOpen = getTagsToOpen(charsReader.getCurrentIndex(), decorationDataHolder); openNewTags(charsReader, tagsToOpen, currentHtmlLine); if (shouldAppendCharToHtmlOutput(charsReader)) { char currentChar = (char) charsReader.getCurrentValue(); currentHtmlLine.append(normalize(currentChar)); } } private static void addLine(List<String> decoratedHtmlLines, String line, int currentLine, @Nullable Integer from, @Nullable Integer to) { if (canAddLine(currentLine, from) && !shouldStop(currentLine, to)) { decoratedHtmlLines.add(line); } } private static boolean canAddLine(int currentLine, @Nullable Integer from) { return from == null || currentLine >= from; } private static boolean shouldStop(int currentLine, @Nullable Integer to) { return to != null && to < currentLine; } private static char[] normalize(char currentChar) { char[] normalizedChars; if (currentChar == HTML_OPENING) { normalizedChars = ENCODED_HTML_OPENING.toCharArray(); } else if (currentChar == HTML_CLOSING) { normalizedChars = ENCODED_HTML_CLOSING.toCharArray(); } else if (currentChar == AMPERSAND) { normalizedChars = ENCODED_AMPERSAND.toCharArray(); } else { normalizedChars = new char[] {currentChar}; } return normalizedChars; } private static boolean shouldAppendCharToHtmlOutput(CharactersReader charsReader) { return charsReader.getCurrentValue() != CR_END_OF_LINE && charsReader.getCurrentValue() != LF_END_OF_LINE; } private static int getNumberOfTagsToClose(int currentIndex, DecorationDataHolder dataHolder) { int numberOfTagsToClose = 0; while (currentIndex == dataHolder.getCurrentClosingTagOffset()) { numberOfTagsToClose++; dataHolder.nextClosingTagOffset(); } return numberOfTagsToClose; } private static Collection<String> getTagsToOpen(int currentIndex, DecorationDataHolder dataHolder) { Collection<String> tagsToOpen = newArrayList(); while (dataHolder.getCurrentOpeningTagEntry() != null && currentIndex == dataHolder.getCurrentOpeningTagEntry().getStartOffset()) { tagsToOpen.add(dataHolder.getCurrentOpeningTagEntry().getCssClass()); dataHolder.nextOpeningTagEntry(); } return tagsToOpen; } private static boolean shouldClosePendingTags(CharactersReader charactersReader) { return charactersReader.getCurrentValue() == CR_END_OF_LINE || (charactersReader.getCurrentValue() == LF_END_OF_LINE && charactersReader.getPreviousValue() != CR_END_OF_LINE) || (charactersReader.getCurrentValue() == CharactersReader.END_OF_STREAM && charactersReader.getPreviousValue() != LF_END_OF_LINE); } private static boolean shouldReopenPendingTags(CharactersReader charactersReader) { return (charactersReader.getPreviousValue() == LF_END_OF_LINE && charactersReader.getCurrentValue() != LF_END_OF_LINE) || (charactersReader.getPreviousValue() == CR_END_OF_LINE && charactersReader.getCurrentValue() != CR_END_OF_LINE && charactersReader.getCurrentValue() != LF_END_OF_LINE); } private static boolean shouldStartNewLine(CharactersReader charactersReader) { return charactersReader.getPreviousValue() == LF_END_OF_LINE || (charactersReader.getPreviousValue() == CR_END_OF_LINE && charactersReader.getCurrentValue() != LF_END_OF_LINE); } private static void closeCompletedTags(CharactersReader charactersReader, int numberOfTagsToClose, StringBuilder decoratedText) { for (int i = 0; i < numberOfTagsToClose; i++) { injectClosingHtml(decoratedText); charactersReader.removeLastOpenTag(); } } private static void openNewTags(CharactersReader charactersReader, Collection<String> tagsToOpen, StringBuilder decoratedText) { for (String tagToOpen : tagsToOpen) { injectOpeningHtmlForRule(tagToOpen, decoratedText); charactersReader.registerOpenTag(tagToOpen); } } private static void closeCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) { for (int i = 0; i < charactersReader.getOpenTags().size(); i++) { injectClosingHtml(decoratedText); } } private static void reopenCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) { for (String tags : charactersReader.getOpenTags()) { injectOpeningHtmlForRule(tags, decoratedText); } } private static void injectOpeningHtmlForRule(String textType, StringBuilder decoratedText) { decoratedText.append("<span class=\"").append(textType).append("\">"); } private static void injectClosingHtml(StringBuilder decoratedText) { decoratedText.append("</span>"); } }
8,827
38.765766
148
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/OpeningHtmlTag.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.source; class OpeningHtmlTag { private final int startOffset; private final String cssClass; OpeningHtmlTag(int startOffset, String cssClass) { this.startOffset = startOffset; this.cssClass = cssClass; } int getStartOffset() { return startOffset; } String getCssClass() { return cssClass; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return compareTo((OpeningHtmlTag) o); } @Override public int hashCode() { int result = startOffset; result = 31 * result + (cssClass != null ? cssClass.hashCode() : 0); return result; } private boolean compareTo(OpeningHtmlTag otherTag) { if (startOffset != otherTag.startOffset) { return false; } return (cssClass != null) ? cssClass.equals(otherTag.cssClass) : (otherTag.cssClass == null); } }
1,812
26.892308
97
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/SourceService.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.source; import java.util.Optional; import java.util.Set; import java.util.function.Function; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.protobuf.DbFileSources; import org.sonar.db.source.FileSourceDto; import static com.google.common.base.Preconditions.checkArgument; public class SourceService { private final DbClient dbClient; private final HtmlSourceDecorator htmlDecorator; private final Function<DbFileSources.Line, String> lineToHtml; public SourceService(DbClient dbClient, HtmlSourceDecorator htmlDecorator) { this.dbClient = dbClient; this.htmlDecorator = htmlDecorator; this.lineToHtml = lineToHtml(); } /** * Returns a range of lines as raw db data. User permission is not verified. * * @param from starts from 1 * @param toInclusive starts from 1, must be greater than or equal param {@code from} */ public Optional<Iterable<DbFileSources.Line>> getLines(DbSession dbSession, String fileUuid, int from, int toInclusive) { return getLines(dbSession, fileUuid, from, toInclusive, Function.identity()); } public Optional<Iterable<DbFileSources.Line>> getLines(DbSession dbSession, String fileUuid, Set<Integer> lines) { return getLines(dbSession, fileUuid, lines, Function.identity()); } /** * Returns a range of lines as raw text. * * @see #getLines(DbSession, String, int, int) */ public Optional<Iterable<String>> getLinesAsRawText(DbSession dbSession, String fileUuid, int from, int toInclusive) { return getLines(dbSession, fileUuid, from, toInclusive, DbFileSources.Line::getSource); } public Optional<Iterable<String>> getLinesAsHtml(DbSession dbSession, String fileUuid, int from, int toInclusive) { return getLines(dbSession, fileUuid, from, toInclusive, lineToHtml); } private <E> Optional<Iterable<E>> getLines(DbSession dbSession, String fileUuid, int from, int toInclusive, Function<DbFileSources.Line, E> function) { verifyLine(from); checkArgument(toInclusive >= from, String.format("Line number must greater than or equal to %d, got %d", from, toInclusive)); FileSourceDto dto = dbClient.fileSourceDao().selectByFileUuid(dbSession, fileUuid); if (dto == null) { return Optional.empty(); } return Optional.of(dto.getSourceData().getLinesList().stream() .filter(line -> line.hasLine() && line.getLine() >= from) .limit((toInclusive - from) + 1L) .map(function) .toList()); } private <E> Optional<Iterable<E>> getLines(DbSession dbSession, String fileUuid, Set<Integer> lines, Function<DbFileSources.Line, E> function) { FileSourceDto dto = dbClient.fileSourceDao().selectByFileUuid(dbSession, fileUuid); if (dto == null) { return Optional.empty(); } return Optional.of(dto.getSourceData().getLinesList().stream() .filter(line -> line.hasLine() && lines.contains(line.getLine())) .map(function) .toList()); } private static void verifyLine(int line) { checkArgument(line >= 1, String.format("Line number must start at 1, got %d", line)); } private Function<DbFileSources.Line, String> lineToHtml() { return line -> htmlDecorator.getDecoratedSourceAsHtml(line.getSource(), line.getHighlighting(), line.getSymbols()); } }
4,173
38.752381
153
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/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.source; import javax.annotation.ParametersAreNonnullByDefault;
963
39.166667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/IndexAction.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.source.ws; import com.google.common.io.Resources; 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.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; public class IndexAction implements SourcesWsAction { private final DbClient dbClient; private final SourceService sourceService; private final UserSession userSession; private final ComponentFinder componentFinder; public IndexAction(DbClient dbClient, SourceService sourceService, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.sourceService = sourceService; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("index") .setDescription("Get source code as line number / text pairs. Require See Source Code permission on file") .setSince("5.0") .setResponseExample(Resources.getResource(getClass(), "example-index.json")) .setInternal(true) .setHandler(this); action .createParam("resource") .setRequired(true) .setDescription("File key") .setExampleValue("my_project:/src/foo/Bar.php"); action .createParam("from") .setDefaultValue(1) .setDescription("First line"); action .createParam("to") .setDescription("Last line (excluded). If not specified, all lines are returned until end of file"); } @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("resource"); int from = request.mandatoryParamAsInt("from"); Integer to = request.paramAsInt("to"); try (DbSession session = dbClient.openSession(false)) { ComponentDto component = componentFinder.getByKey(session, fileKey); userSession.checkComponentPermission(UserRole.CODEVIEWER, component); Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(session, component.uuid(), from, to == null ? Integer.MAX_VALUE : (to - 1)); try (JsonWriter json = response.newJsonWriter()) { json.beginArray().beginObject(); if (lines.isPresent()) { int lineCounter = from; for (String line : lines.get()) { json.prop(String.valueOf(lineCounter), line); lineCounter++; } } json.endObject().endArray(); } } } }
3,677
36.530612
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/IssueSnippetsAction.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.source.ws; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; 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.text.JsonWriter; 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.issue.IssueDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbFileSources; import org.sonar.db.protobuf.DbIssues; import org.sonar.server.component.ws.ComponentViewerJsonWriter; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; import static com.google.common.io.Resources.getResource; import static java.lang.String.format; public class IssueSnippetsAction implements SourcesWsAction { private final DbClient dbClient; private final UserSession userSession; private final SourceService sourceService; private final ComponentViewerJsonWriter componentViewerJsonWriter; private final LinesJsonWriter linesJsonWriter; public IssueSnippetsAction(DbClient dbClient, UserSession userSession, SourceService sourceService, LinesJsonWriter linesJsonWriter, ComponentViewerJsonWriter componentViewerJsonWriter) { this.sourceService = sourceService; this.dbClient = dbClient; this.userSession = userSession; this.linesJsonWriter = linesJsonWriter; this.componentViewerJsonWriter = componentViewerJsonWriter; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("issue_snippets") .setDescription("Get code snippets involved in an issue or hotspot. Requires 'See Source Code permission' permission on the project<br/>") .setSince("7.8") .setInternal(true) .setResponseExample(getResource(getClass(), "example-show.json")) .setHandler(this); action .createParam("issueKey") .setRequired(true) .setDescription("Issue or hotspot key") .setExampleValue("AU-Tpxb--iU5OvuD2FLy"); } @Override public void handle(Request request, Response response) throws Exception { String issueKey = request.mandatoryParam("issueKey"); try (DbSession dbSession = dbClient.openSession(false)) { IssueDto issueDto = dbClient.issueDao().selectByKey(dbSession, issueKey) .orElseThrow(() -> new NotFoundException(format("Issue with key '%s' does not exist", issueKey))); ProjectDto projectDto = dbClient.projectDao().selectByBranchUuid(dbSession, issueDto.getProjectUuid()) .orElseThrow(() -> new NotFoundException(format("Project with uuid '%s' does not exist", issueDto.getProjectUuid()))); userSession.checkEntityPermission(UserRole.CODEVIEWER, projectDto); DbIssues.Locations locations = issueDto.parseLocations(); String componentUuid = issueDto.getComponentUuid(); if (locations == null || componentUuid == null) { response.noContent(); } else { Map<String, TreeSet<Integer>> linesPerComponent = getLinesPerComponent(componentUuid, locations); Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids(dbSession, linesPerComponent.keySet()) .stream().collect(Collectors.toMap(ComponentDto::uuid, c -> c)); Set<String> branchUuids = componentsByUuid.values().stream() .map(ComponentDto::branchUuid) .collect(Collectors.toSet()); Map<String, BranchDto> branches = dbClient.branchDao() .selectByUuids(dbSession, branchUuids) .stream() .collect(Collectors.toMap(BranchDto::getUuid, b -> b)); try (JsonWriter jsonWriter = response.newJsonWriter()) { jsonWriter.beginObject(); for (Map.Entry<String, TreeSet<Integer>> e : linesPerComponent.entrySet()) { ComponentDto componentDto = componentsByUuid.get(e.getKey()); if (componentDto != null) { writeSnippet(dbSession, jsonWriter, projectDto, componentDto, e.getValue(), branches.get(componentDto.branchUuid())); } } jsonWriter.endObject(); } } } } private void writeSnippet(DbSession dbSession, JsonWriter writer, ProjectDto projectDto, ComponentDto fileDto, Set<Integer> lines, BranchDto branchDto) { Optional<Iterable<DbFileSources.Line>> lineSourcesOpt = sourceService.getLines(dbSession, fileDto.uuid(), lines); if (lineSourcesOpt.isEmpty()) { return; } Supplier<Optional<Long>> periodDateSupplier = () -> dbClient.snapshotDao() .selectLastAnalysisByComponentUuid(dbSession, fileDto.branchUuid()) .map(SnapshotDto::getPeriodDate); Iterable<DbFileSources.Line> lineSources = lineSourcesOpt.get(); writer.name(fileDto.getKey()).beginObject(); writer.name("component").beginObject(); String branch = branchDto.isMain() ? null : branchDto.getBranchKey(); String pullRequest = branchDto.getPullRequestKey(); componentViewerJsonWriter.writeComponentWithoutFav(writer, projectDto, fileDto, branch, pullRequest); componentViewerJsonWriter.writeMeasures(writer, fileDto, dbSession); writer.endObject(); linesJsonWriter.writeSource(lineSources, writer, periodDateSupplier); writer.endObject(); } private static Map<String, TreeSet<Integer>> getLinesPerComponent(String componentUuid, DbIssues.Locations locations) { Map<String, TreeSet<Integer>> linesPerComponent = new HashMap<>(); if (locations.hasTextRange()) { // extra lines for the main location addTextRange(linesPerComponent, componentUuid, locations.getTextRange(), 9); } for (DbIssues.Flow flow : locations.getFlowList()) { for (DbIssues.Location l : flow.getLocationList()) { if (l.hasComponentId()) { addTextRange(linesPerComponent, l.getComponentId(), l.getTextRange(), 5); } else { addTextRange(linesPerComponent, componentUuid, l.getTextRange(), 5); } } } return linesPerComponent; } private static void addTextRange(Map<String, TreeSet<Integer>> linesPerComponent, String componentUuid, DbCommons.TextRange textRange, int numLinesAfterIssue) { int start = textRange.getStartLine() - 5; int end = textRange.getEndLine() + numLinesAfterIssue; TreeSet<Integer> lines = linesPerComponent.computeIfAbsent(componentUuid, c -> new TreeSet<>()); IntStream.rangeClosed(start, end).forEach(lines::add); // If two snippets in the same component are 10 lines apart from each other, include those 10 lines. Integer closestToStart = lines.lower(start); if (closestToStart != null && closestToStart >= start - 11) { IntStream.range(closestToStart + 1, start).forEach(lines::add); } Integer closestToEnd = lines.higher(end); if (closestToEnd != null && closestToEnd <= end + 11) { IntStream.range(end + 1, closestToEnd).forEach(lines::add); } } }
8,236
41.02551
155
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesAction.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.source.ws; import com.google.common.base.MoreObjects; import com.google.common.io.Resources; import java.util.Optional; import java.util.function.Supplier; 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.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.protobuf.DbFileSources; import org.sonar.server.component.ComponentFinder; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.component.ComponentFinder.ParamNames.UUID_AND_KEY; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_FILE_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; public class LinesAction implements SourcesWsAction { private static final String PARAM_UUID = "uuid"; private static final String PARAM_KEY = "key"; private static final String PARAM_FROM = "from"; private static final String PARAM_TO = "to"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_PULL_REQUEST = "pullRequest"; private final ComponentFinder componentFinder; private final SourceService sourceService; private final LinesJsonWriter linesJsonWriter; private final DbClient dbClient; private final UserSession userSession; public LinesAction(ComponentFinder componentFinder, DbClient dbClient, SourceService sourceService, LinesJsonWriter linesJsonWriter, UserSession userSession) { this.componentFinder = componentFinder; this.sourceService = sourceService; this.linesJsonWriter = linesJsonWriter; this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("lines") .setDescription("Show source code with line oriented info. Requires See Source Code permission on file's project<br/>" + "Each element of the result array is an object which contains:" + "<ol>" + "<li>Line number</li>" + "<li>Content of the line</li>" + "<li>Author of the line (from SCM information)</li>" + "<li>Revision of the line (from SCM information)</li>" + "<li>Last commit date of the line (from SCM information)</li>" + "<li>Line hits from coverage</li>" + "<li>Number of conditions to cover in tests</li>" + "<li>Number of conditions covered by tests</li>" + "<li>Whether the line is new</li>" + "</ol>") .setSince("5.0") .setInternal(true) .setResponseExample(Resources.getResource(getClass(), "lines-example.json")) .setChangelog( new Change("6.2", "fields \"utLineHits\", \"utConditions\" and \"utCoveredConditions\" " + "has been renamed \"lineHits\", \"conditions\" and \"coveredConditions\""), new Change("6.2", "fields \"itLineHits\", \"itConditions\" and \"itCoveredConditions\" " + "are no more returned"), new Change("6.6", "field \"branch\" added"), new Change("7.4", "field \"isNew\" added")) .setHandler(this); action .createParam(PARAM_UUID) .setDescription("File uuid. Mandatory if param 'key' is not set") .setExampleValue("f333aab4-7e3a-4d70-87e1-f4c491f05e5c"); action .createParam(PARAM_KEY) .setDescription("File key. Mandatory if param 'uuid' is not set. Available since 5.2") .setExampleValue(KEY_FILE_EXAMPLE_001); action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setInternal(true) .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id") .setInternal(true) .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); action .createParam(PARAM_FROM) .setDescription("First line to return. Starts from 1") .setExampleValue("10") .setDefaultValue("1"); action .createParam(PARAM_TO) .setDescription("Optional last line to return (inclusive). It must be greater than " + "or equal to parameter 'from'. If unset, then all the lines greater than or equal to 'from' " + "are returned.") .setExampleValue("20"); } @Override public void handle(Request request, Response response) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = loadComponent(dbSession, request); Supplier<Optional<Long>> periodDateSupplier = () -> dbClient.snapshotDao() .selectLastAnalysisByComponentUuid(dbSession, file.branchUuid()) .map(SnapshotDto::getPeriodDate); userSession.checkComponentPermission(UserRole.CODEVIEWER, file); int from = request.mandatoryParamAsInt(PARAM_FROM); int to = MoreObjects.firstNonNull(request.paramAsInt(PARAM_TO), Integer.MAX_VALUE); Iterable<DbFileSources.Line> lines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "No source found for file '%s' (uuid: %s)", file.getKey(), file.uuid()); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); linesJsonWriter.writeSource(lines, json, periodDateSupplier); json.endObject(); } } } private ComponentDto loadComponent(DbSession dbSession, Request wsRequest) { String componentKey = wsRequest.param(PARAM_KEY); String componentUuid = wsRequest.param(PARAM_UUID); String branch = wsRequest.param(PARAM_BRANCH); String pullRequest = wsRequest.param(PARAM_PULL_REQUEST); checkArgument(componentUuid == null || (branch == null && pullRequest == null), "Parameter '%s' cannot be used at the same time as '%s' or '%s'", PARAM_UUID, PARAM_BRANCH, PARAM_PULL_REQUEST); if (branch == null && pullRequest == null) { return componentFinder.getByUuidOrKey(dbSession, componentUuid, componentKey, UUID_AND_KEY); } checkRequest(componentKey != null, "The '%s' parameter is missing", PARAM_KEY); return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest); } }
7,565
42.482759
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/LinesJsonWriter.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.source.ws; import java.util.Date; import java.util.Optional; import java.util.function.Supplier; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.protobuf.DbFileSources; import org.sonar.server.source.HtmlSourceDecorator; public class LinesJsonWriter { private final HtmlSourceDecorator htmlSourceDecorator; public LinesJsonWriter(HtmlSourceDecorator htmlSourceDecorator) { this.htmlSourceDecorator = htmlSourceDecorator; } public void writeSource(Iterable<DbFileSources.Line> lines, JsonWriter json, Supplier<Optional<Long>> periodDateSupplier) { Long periodDate = null; json.name("sources").beginArray(); for (DbFileSources.Line line : lines) { json.beginObject() .prop("line", line.getLine()) .prop("code", htmlSourceDecorator.getDecoratedSourceAsHtml(line.getSource(), line.getHighlighting(), line.getSymbols())) .prop("scmRevision", line.getScmRevision()); json.prop("scmAuthor", line.getScmAuthor()); if (line.hasScmDate()) { json.prop("scmDate", DateUtils.formatDateTime(new Date(line.getScmDate()))); } getLineHits(line).ifPresent(lh -> { json.prop("utLineHits", lh); json.prop("lineHits", lh); }); getConditions(line).ifPresent(conditions -> { json.prop("utConditions", conditions); json.prop("conditions", conditions); }); getCoveredConditions(line).ifPresent(coveredConditions -> { json.prop("utCoveredConditions", coveredConditions); json.prop("coveredConditions", coveredConditions); }); json.prop("duplicated", line.getDuplicationCount() > 0); if (line.hasIsNewLine()) { json.prop("isNew", line.getIsNewLine()); } else { if (periodDate == null) { periodDate = periodDateSupplier.get().orElse(Long.MAX_VALUE); } json.prop("isNew", line.getScmDate() > periodDate); } json.endObject(); } json.endArray(); } private static Optional<Integer> getLineHits(DbFileSources.Line line) { if (line.hasLineHits()) { return Optional.of(line.getLineHits()); } else if (line.hasDeprecatedOverallLineHits()) { return Optional.of(line.getDeprecatedOverallLineHits()); } else if (line.hasDeprecatedUtLineHits()) { return Optional.of(line.getDeprecatedUtLineHits()); } else if (line.hasDeprecatedItLineHits()) { return Optional.of(line.getDeprecatedItLineHits()); } return Optional.empty(); } private static Optional<Integer> getConditions(DbFileSources.Line line) { if (line.hasConditions()) { return Optional.of(line.getConditions()); } else if (line.hasDeprecatedOverallConditions()) { return Optional.of(line.getDeprecatedOverallConditions()); } else if (line.hasDeprecatedUtConditions()) { return Optional.of(line.getDeprecatedUtConditions()); } else if (line.hasDeprecatedItConditions()) { return Optional.of(line.getDeprecatedItConditions()); } return Optional.empty(); } private static Optional<Integer> getCoveredConditions(DbFileSources.Line line) { if (line.hasCoveredConditions()) { return Optional.of(line.getCoveredConditions()); } else if (line.hasDeprecatedOverallCoveredConditions()) { return Optional.of(line.getDeprecatedOverallCoveredConditions()); } else if (line.hasDeprecatedUtCoveredConditions()) { return Optional.of(line.getDeprecatedUtCoveredConditions()); } else if (line.hasDeprecatedItCoveredConditions()) { return Optional.of(line.getDeprecatedItCoveredConditions()); } return Optional.empty(); } }
4,554
38.608696
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/RawAction.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.source.ws; import com.google.common.io.Resources; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; 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.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; public class RawAction implements SourcesWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_PULL_REQUEST = "pullRequest"; private final DbClient dbClient; private final SourceService sourceService; private final UserSession userSession; private final ComponentFinder componentFinder; public RawAction(DbClient dbClient, SourceService sourceService, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.sourceService = sourceService; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("raw") .setDescription("Get source code as raw text. Require 'See Source Code' permission on file") .setSince("5.0") .setResponseExample(Resources.getResource(getClass(), "example-raw.txt")) .setHandler(this); action .createParam(PARAM_KEY) .setRequired(true) .setDescription("File key") .setExampleValue("my_project:src/foo/Bar.php"); action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setInternal(true) .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id") .setInternal(true) .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam(PARAM_KEY); String branch = request.param(PARAM_BRANCH); String pullRequest = request.param(PARAM_PULL_REQUEST); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, fileKey, branch, pullRequest); userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Optional<Iterable<String>> lines = sourceService.getLinesAsRawText(dbSession, file.uuid(), 1, Integer.MAX_VALUE); response.stream().setMediaType("text/plain"); if (lines.isPresent()) { OutputStream output = response.stream().output(); for (String line : lines.get()) { output.write(line.getBytes(StandardCharsets.UTF_8)); output.write("\n".getBytes(StandardCharsets.UTF_8)); } } } catch (IOException e) { throw new IllegalStateException("Fail to write raw source of file " + fileKey, e); } } }
4,192
37.824074
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.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.source.ws; import com.google.common.base.Strings; import com.google.common.io.Resources; import java.util.Date; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.EqualsBuilder; 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.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.protobuf.DbFileSources; import org.sonar.server.component.ComponentFinder; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; public class ScmAction implements SourcesWsAction { private final DbClient dbClient; private final SourceService sourceService; private final UserSession userSession; private final ComponentFinder componentFinder; public ScmAction(DbClient dbClient, SourceService sourceService, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.sourceService = sourceService; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("scm") .setDescription("Get SCM information of source files. Require See Source Code permission on file's project<br/>" + "Each element of the result array is composed of:" + "<ol>" + "<li>Line number</li>" + "<li>Author of the commit</li>" + "<li>Datetime of the commit (before 5.2 it was only the Date)</li>" + "<li>Revision of the commit (added in 5.2)</li>" + "</ol>") .setSince("4.4") .setResponseExample(Resources.getResource(getClass(), "example-scm.json")) .setHandler(this); action .createParam("key") .setRequired(true) .setDescription("File key") .setExampleValue("my_project:/src/foo/Bar.php"); action .createParam("from") .setDescription("First line to return. Starts at 1") .setExampleValue("10") .setDefaultValue("1"); action .createParam("to") .setDescription("Last line to return (inclusive)") .setExampleValue("20"); action .createParam("commits_by_line") .setDescription("Group lines by SCM commit if value is false, else display commits for each line, even if two " + "consecutive lines relate to the same commit.") .setBooleanPossibleValues() .setDefaultValue("false"); } @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("key"); int from = Math.max(request.mandatoryParamAsInt("from"), 1); int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); boolean commitsByLine = request.mandatoryParamAsBoolean("commits_by_line"); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Iterable<DbFileSources.Line> sourceLines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "File '%s' has no sources", fileKey); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); writeSource(sourceLines, commitsByLine, json); json.endObject().close(); } } } private static void writeSource(Iterable<DbFileSources.Line> lines, boolean showCommitsByLine, JsonWriter json) { json.name("scm").beginArray(); DbFileSources.Line previousLine = null; boolean started = false; for (DbFileSources.Line lineDoc : lines) { if (hasScm(lineDoc) && (!started || showCommitsByLine || !isSameCommit(previousLine, lineDoc))) { json.beginArray() .value(lineDoc.getLine()) .value(lineDoc.getScmAuthor()); json.value(lineDoc.hasScmDate() ? DateUtils.formatDateTime(new Date(lineDoc.getScmDate())) : null); json.value(lineDoc.getScmRevision()); json.endArray(); started = true; } previousLine = lineDoc; } json.endArray(); } private static boolean isSameCommit(DbFileSources.Line previousLine, DbFileSources.Line currentLine) { return new EqualsBuilder() .append(previousLine.getScmAuthor(), currentLine.getScmAuthor()) .append(previousLine.getScmDate(), currentLine.getScmDate()) .append(previousLine.getScmRevision(), currentLine.getScmRevision()) .isEquals(); } private static boolean hasScm(DbFileSources.Line line) { return !Strings.isNullOrEmpty(line.getScmAuthor()) || line.hasScmDate() || !Strings.isNullOrEmpty(line.getScmRevision()); } }
5,871
38.675676
167
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/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.source.ws; import com.google.common.io.Resources; import org.apache.commons.lang.ObjectUtils; 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.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.source.SourceService; import org.sonar.server.user.UserSession; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; public class ShowAction implements SourcesWsAction { private final SourceService sourceService; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public ShowAction(SourceService sourceService, DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.sourceService = sourceService; this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("show") .setDescription("Get source code. Requires See Source Code permission on file's project<br/>" + "Each element of the result array is composed of:" + "<ol>" + "<li>Line number</li>" + "<li>Content of the line</li>" + "</ol>") .setSince("4.4") .setResponseExample(Resources.getResource(getClass(), "example-show.json")) .setHandler(this); action .createParam("key") .setRequired(true) .setDescription("File key") .setExampleValue("my_project:/src/foo/Bar.php"); action .createParam("from") .setDescription("First line to return. Starts at 1") .setExampleValue("10") .setDefaultValue("1"); action .createParam("to") .setDescription("Last line to return (inclusive)") .setExampleValue("20"); } @Override public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("key"); int from = Math.max(request.paramAsInt("from"), 1); int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); userSession.checkComponentPermission(UserRole.CODEVIEWER, file); Iterable<String> linesHtml = checkFoundWithOptional(sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to), "No source found for file '%s'", fileKey); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); writeSource(linesHtml, from, json); json.endObject(); } } } private static void writeSource(Iterable<String> lines, int from, JsonWriter json) { json.name("sources").beginArray(); long index = 0L; for (String line : lines) { json.beginArray(); json.value(index + from); json.value(line); json.endArray(); index++; } json.endArray(); } }
4,131
34.930435
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/SourceWsModule.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.source.ws; import org.sonar.core.platform.Module; import org.sonar.server.source.HtmlSourceDecorator; import org.sonar.server.source.SourceService; public class SourceWsModule extends Module { @Override protected void configureModule() { add( HtmlSourceDecorator.class, LinesJsonWriter.class, SourceService.class, SourcesWs.class, ShowAction.class, IssueSnippetsAction.class, LinesAction.class, RawAction.class, IndexAction.class, ScmAction.class ); } }
1,398
31.534884
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/SourcesWs.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.source.ws; import org.sonar.api.server.ws.WebService; public class SourcesWs implements WebService { private final SourcesWsAction[] actions; public SourcesWs(SourcesWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/sources") .setSince("4.2") .setDescription("Get details on source files. See also api/tests."); for (SourcesWsAction action : actions) { action.define(controller); } controller.done(); } }
1,432
32.325581
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/SourcesWsAction.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.source.ws; import org.sonar.server.ws.WsAction; public interface SourcesWsAction extends WsAction { // Marker interface }
994
35.851852
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/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.source.ws; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/text/Macro.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.text; public interface Macro { String getRegex(); String getReplacement(); }
952
33.035714
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/text/MacroInterpreter.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.text; import org.sonar.api.server.ServerSide; import org.sonar.api.platform.Server; import java.util.List; @ServerSide public class MacroInterpreter { private final List<Macro> macros; public MacroInterpreter(Server server) { this.macros = List.of( new RuleMacro(server.getContextPath()) ); } public String interpret(String text) { String textReplaced = text; for (Macro macro : macros) { textReplaced = textReplaced.replaceAll(macro.getRegex(), macro.getReplacement()); } return textReplaced; } }
1,417
30.511111
87
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/text/RuleMacro.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.text; class RuleMacro implements Macro { private static final String COLON = "%3A"; private final String contextPath; RuleMacro(String contextPath) { this.contextPath = contextPath; } /** * First parameter is the repository, second one is the rule key. Exemple : {rule:java:ArchitecturalConstraint} */ @Override public String getRegex() { return "\\{rule:([a-zA-Z0-9._-]++):([a-zA-Z0-9._-]++)\\}"; } @Override public String getReplacement() { return "<a href='" + contextPath + "/coding_rules#rule_key=$1" + COLON + "$2'>$2</a>"; } }
1,447
31.909091
113
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/text/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.text; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/PageRepository.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.ui; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.web.page.Context; import org.sonar.api.web.page.Page; import org.sonar.api.web.page.Page.Qualifier; import org.sonar.api.web.page.Page.Scope; import org.sonar.api.web.page.PageDefinition; import org.sonar.core.extension.CoreExtensionRepository; import org.sonar.core.platform.PluginRepository; import org.sonar.server.ui.page.CorePageDefinition; import org.springframework.beans.factory.annotation.Autowired; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.copyOf; import static java.util.Collections.emptyList; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; import static org.sonar.api.web.page.Page.Scope.COMPONENT; import static org.sonar.api.web.page.Page.Scope.GLOBAL; @ServerSide public class PageRepository implements Startable { private final PluginRepository pluginRepository; private final CoreExtensionRepository coreExtensionRepository; private final List<PageDefinition> definitions; private final List<CorePageDefinition> corePageDefinitions; private List<Page> pages; /** * Used by the ioc container when there is no {@link PageDefinition}. */ @Autowired(required = false) public PageRepository(PluginRepository pluginRepository, CoreExtensionRepository coreExtensionRepository) { this.pluginRepository = pluginRepository; this.coreExtensionRepository = coreExtensionRepository; // in case there's no page definition this.definitions = emptyList(); this.corePageDefinitions = emptyList(); } /** * Used by the ioc container when there is only {@link PageDefinition} provided both by Plugin(s). */ @Autowired(required = false) public PageRepository(PluginRepository pluginRepository, CoreExtensionRepository coreExtensionRepository, PageDefinition[] pageDefinitions) { this.pluginRepository = pluginRepository; this.coreExtensionRepository = coreExtensionRepository; this.definitions = copyOf(pageDefinitions); this.corePageDefinitions = emptyList(); } /** * Used by the ioc container when there is only {@link PageDefinition} provided both by Core Extension(s). */ @Autowired(required = false) public PageRepository(PluginRepository pluginRepository, CoreExtensionRepository coreExtensionRepository, CorePageDefinition[] corePageDefinitions) { this.pluginRepository = pluginRepository; this.coreExtensionRepository = coreExtensionRepository; this.definitions = emptyList(); this.corePageDefinitions = ImmutableList.copyOf(corePageDefinitions); } /** * Used by the ioc container when there is {@link PageDefinition} provided both by Core Extension(s) and Plugin(s). */ @Autowired(required = false) public PageRepository(PluginRepository pluginRepository, CoreExtensionRepository coreExtensionRepository, PageDefinition[] pageDefinitions, CorePageDefinition[] corePageDefinitions) { this.pluginRepository = pluginRepository; this.coreExtensionRepository = coreExtensionRepository; this.definitions = copyOf(pageDefinitions); this.corePageDefinitions = ImmutableList.copyOf(corePageDefinitions); } @Override public void start() { Context context = new Context(); definitions.forEach(definition -> definition.define(context)); Context coreContext = new Context(); corePageDefinitions.stream() .map(CorePageDefinition::getPageDefinition) .forEach(definition -> definition.define(coreContext)); context.getPages().forEach(this::checkPluginExists); coreContext.getPages().forEach(this::checkCoreExtensionExists); pages = new ArrayList<>(); pages.addAll(context.getPages()); pages.addAll(coreContext.getPages()); pages.sort(comparing(Page::getKey)); } @Override public void stop() { // nothing to do } public List<Page> getGlobalPages(boolean isAdmin) { return getPages(GLOBAL, isAdmin, null); } public List<Page> getComponentPages(boolean isAdmin, String qualifierKey) { Qualifier qualifier = Qualifier.fromKey(qualifierKey); return qualifier == null ? emptyList() : getPages(COMPONENT, isAdmin, qualifier); } private List<Page> getPages(Scope scope, boolean isAdmin, @Nullable Qualifier qualifier) { return getAllPages().stream() .filter(p -> p.getScope().equals(scope)) .filter(p -> p.isAdmin() == isAdmin) .filter(p -> !COMPONENT.equals(p.getScope()) || p.getComponentQualifiers().contains(qualifier)) .toList(); } @VisibleForTesting List<Page> getAllPages() { return requireNonNull(pages, "Pages haven't been initialized yet"); } private void checkPluginExists(Page page) { String pluginKey = page.getPluginKey(); checkState(pluginRepository.hasPlugin(pluginKey), "Page '%s' references plugin '%s' that does not exist", page.getName(), pluginKey); } private void checkCoreExtensionExists(Page page) { String coreExtensionName = page.getPluginKey(); checkState(coreExtensionRepository.isInstalled(coreExtensionName), "Page '%s' references Core Extension '%s' which is not installed", page.getName(), coreExtensionName); } }
6,325
39.037975
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/VersionFormatter.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.ui; import com.google.common.base.Splitter; import java.util.List; public class VersionFormatter { private static final String VERSION_SEQUENCE_SEPARATION = "."; private VersionFormatter() { // prevent instantiation } public static String format(String technicalVersion) { List<String> elements = Splitter.on(VERSION_SEQUENCE_SEPARATION).splitToList(technicalVersion); if (elements.size() != 4) { return technicalVersion; } // version has the form 6.3.1.4563 StringBuilder builder = new StringBuilder(); builder .append(elements.get(0)) .append(VERSION_SEQUENCE_SEPARATION) .append(elements.get(1)); if (!"0".equals(elements.get(2))) { builder.append(VERSION_SEQUENCE_SEPARATION) .append(elements.get(2)); } builder.append(" (build ").append(elements.get(3)).append(")"); return builder.toString(); } }
1,770
31.796296
99
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/WebAnalyticsLoader.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.ui; import java.util.Optional; import org.sonar.api.server.ServerSide; @ServerSide public interface WebAnalyticsLoader { /** * URL path to the JS file to be loaded by webapp, for instance "/static/foo/bar.js". * It always starts with "/" and does not include the optional web context. */ Optional<String> getUrlPathToJs(); }
1,210
33.6
87
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/WebAnalyticsLoaderImpl.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.ui; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.utils.MessageException; import org.sonar.api.web.WebAnalytics; public class WebAnalyticsLoaderImpl implements WebAnalyticsLoader { @Nullable private final WebAnalytics analytics; public WebAnalyticsLoaderImpl(@Nullable WebAnalytics[] analytics) { if (analytics == null) { this.analytics = null; } else { if (analytics.length > 1) { List<String> classes = Arrays.stream(analytics).map(a -> a.getClass().getName()).toList(); throw MessageException.of("Limited to only one web analytics plugin. Found multiple implementations: " + classes); } this.analytics = analytics.length == 1 ? analytics[0] : null; } } @Override public Optional<String> getUrlPathToJs() { return Optional.ofNullable(analytics) .map(WebAnalytics::getUrlPathToJs) .filter(path -> !path.startsWith("/") && !path.contains("..") && !path.contains("://")) .map(path -> "/" + path); } }
1,945
35.037037
122
java