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/almintegration/validator/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.almintegration.validator; import javax.annotation.ParametersAreNonnullByDefault;
982
38.32
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/AlmIntegrationsWSModule.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.almintegration.ws; import org.sonar.core.platform.Module; import org.sonar.server.almintegration.ws.azure.ImportAzureProjectAction; import org.sonar.server.almintegration.ws.azure.ListAzureProjectsAction; import org.sonar.server.almintegration.ws.azure.SearchAzureReposAction; import org.sonar.server.almintegration.ws.bitbucketcloud.ImportBitbucketCloudRepoAction; import org.sonar.server.almintegration.ws.bitbucketcloud.SearchBitbucketCloudReposAction; import org.sonar.server.almintegration.ws.bitbucketserver.ImportBitbucketServerProjectAction; import org.sonar.server.almintegration.ws.bitbucketserver.ListBitbucketServerProjectsAction; import org.sonar.server.almintegration.ws.bitbucketserver.SearchBitbucketServerReposAction; import org.sonar.server.almintegration.ws.github.GetGithubClientIdAction; import org.sonar.server.almintegration.ws.github.ImportGithubProjectAction; import org.sonar.server.almintegration.ws.github.ListGithubOrganizationsAction; import org.sonar.server.almintegration.ws.github.ListGithubRepositoriesAction; import org.sonar.server.almintegration.ws.github.config.CheckAction; import org.sonar.server.almintegration.ws.gitlab.ImportGitLabProjectAction; import org.sonar.server.almintegration.ws.gitlab.SearchGitlabReposAction; public class AlmIntegrationsWSModule extends Module { @Override protected void configureModule() { add( CheckPatAction.class, CheckAction.class, SetPatAction.class, ImportBitbucketServerProjectAction.class, ImportBitbucketCloudRepoAction.class, ListBitbucketServerProjectsAction.class, SearchBitbucketServerReposAction.class, SearchBitbucketCloudReposAction.class, GetGithubClientIdAction.class, ImportGithubProjectAction.class, ListGithubOrganizationsAction.class, ListGithubRepositoriesAction.class, ImportGitLabProjectAction.class, SearchGitlabReposAction.class, ImportAzureProjectAction.class, ListAzureProjectsAction.class, SearchAzureReposAction.class, AlmIntegrationsWs.class); } }
2,940
45.68254
93
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/AlmIntegrationsWs.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.almintegration.ws; import java.util.List; import org.sonar.api.server.ws.WebService; public class AlmIntegrationsWs implements WebService { private final List<AlmIntegrationsWsAction> actions; public AlmIntegrationsWs(List<AlmIntegrationsWsAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/alm_integrations") .setDescription("Manage DevOps Platform Integrations") .setSince("8.2"); actions.forEach(a -> a.define(controller)); controller.done(); } }
1,463
33.046512
79
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/AlmIntegrationsWsAction.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.almintegration.ws; import org.sonar.server.ws.WsAction; public interface AlmIntegrationsWsAction extends WsAction { // marker interface }
1,010
36.444444
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/CheckPatAction.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.almintegration.ws; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.gitlab.GitlabHttpClient; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import static java.util.Objects.requireNonNull; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class CheckPatAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private static final String APP_PASSWORD_CANNOT_BE_NULL = "App Password and Username cannot be null"; private static final String PAT_CANNOT_BE_NULL = "PAT cannot be null"; private static final String URL_CANNOT_BE_NULL = "URL cannot be null"; private static final String WORKSPACE_CANNOT_BE_NULL = "Workspace cannot be null"; private final DbClient dbClient; private final UserSession userSession; private final AzureDevOpsHttpClient azureDevOpsHttpClient; private final BitbucketCloudRestClient bitbucketCloudRestClient; private final BitbucketServerRestClient bitbucketServerRestClient; private final GitlabHttpClient gitlabHttpClient; public CheckPatAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient, BitbucketCloudRestClient bitbucketCloudRestClient, BitbucketServerRestClient bitbucketServerRestClient, GitlabHttpClient gitlabHttpClient) { this.dbClient = dbClient; this.userSession = userSession; this.azureDevOpsHttpClient = azureDevOpsHttpClient; this.bitbucketCloudRestClient = bitbucketCloudRestClient; this.bitbucketServerRestClient = bitbucketServerRestClient; this.gitlabHttpClient = gitlabHttpClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("check_pat") .setDescription("Check validity of a Personal Access Token for the given DevOps Platform setting<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setInternal(true) .setSince("8.2") .setHandler(this) .setChangelog(new Change("9.0", "Bitbucket Cloud support was added")); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); } @Override public void handle(Request request, Response response) { doHandle(request); response.noContent(); } private void doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String userUuid = requireNonNull(userSession.getUuid(), "User cannot be null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); AlmPatDto almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto) .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingKey))); switch (almSettingDto.getAlm()) { case AZURE_DEVOPS: azureDevOpsHttpClient.checkPAT( requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL)); break; case BITBUCKET: // Do an authenticate call to Bitbucket Server to validate that the user's personal access token is valid bitbucketServerRestClient.getRecentRepo( requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL)); break; case GITLAB: gitlabHttpClient.searchProjects( requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL), null, null, null); break; case BITBUCKET_CLOUD: bitbucketCloudRestClient.validateAppPassword( requireNonNull(almPatDto.getPersonalAccessToken(), APP_PASSWORD_CANNOT_BE_NULL), requireNonNull(almSettingDto.getAppId(), WORKSPACE_CANNOT_BE_NULL)); break; case GITHUB: default: throw new IllegalArgumentException(String.format("unsupported DevOps Platform %s", almSettingDto.getAlm())); } } } }
5,967
43.207407
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/CredentialsEncoderHelper.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.almintegration.ws; import java.util.Base64; import javax.annotation.Nullable; import org.sonar.db.alm.setting.ALM; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.db.alm.setting.ALM.BITBUCKET_CLOUD; public class CredentialsEncoderHelper { private CredentialsEncoderHelper() { } public static String encodeCredentials(ALM alm, String pat, @Nullable String username) { if (!alm.equals(BITBUCKET_CLOUD)) { return pat; } return Base64.getEncoder().encodeToString((username + ":" + pat).getBytes(UTF_8)); } }
1,435
33.190476
90
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/ImportHelper.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.almintegration.ws; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.Request; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.project.Visibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects.CreateWsResponse.Project; import static java.util.Objects.requireNonNull; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonarqube.ws.Projects.CreateWsResponse; import static org.sonarqube.ws.Projects.CreateWsResponse.newBuilder; @ServerSide public class ImportHelper { public static final String PARAM_ALM_SETTING = "almSetting"; private final DbClient dbClient; private final UserSession userSession; public ImportHelper(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } public void checkProvisionProjectPermission() { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); } public AlmSettingDto getAlmSetting(Request request) { String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); } } public String getUserUuid() { return requireNonNull(userSession.getUuid(), "User UUID cannot be null"); } public static CreateWsResponse toCreateResponse(ProjectDto projectDto) { return newBuilder() .setProject(Project.newBuilder() .setKey(projectDto.getKey()) .setName(projectDto.getName()) .setQualifier(projectDto.getQualifier()) .setVisibility(Visibility.getLabel(projectDto.isPrivate()))) .build(); } }
2,878
36.881579
122
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/ProjectKeyGenerator.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.almintegration.ws; import com.google.common.annotations.VisibleForTesting; import java.util.List; import org.apache.commons.lang.StringUtils; import org.sonar.core.util.UuidFactory; import static com.google.common.collect.Lists.asList; import static org.sonar.core.component.ComponentKeys.sanitizeProjectKey; public class ProjectKeyGenerator { @VisibleForTesting static final int MAX_PROJECT_KEY_SIZE = 250; @VisibleForTesting static final Character PROJECT_KEY_SEPARATOR = '_'; private final UuidFactory uuidFactory; public ProjectKeyGenerator(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } public String generateUniqueProjectKey(String projectName, String... extraProjectKeyItems) { String sqProjectKey = generateCompleteProjectKey(projectName, extraProjectKeyItems); sqProjectKey = truncateProjectKeyIfNecessary(sqProjectKey); return sanitizeProjectKey(sqProjectKey); } private String generateCompleteProjectKey(String projectName, String[] extraProjectKeyItems) { List<String> projectKeyItems = asList(projectName, extraProjectKeyItems); String projectKey = StringUtils.join(projectKeyItems, PROJECT_KEY_SEPARATOR); String uuid = uuidFactory.create(); return projectKey + PROJECT_KEY_SEPARATOR + uuid; } private static String truncateProjectKeyIfNecessary(String sqProjectKey) { if (sqProjectKey.length() > MAX_PROJECT_KEY_SIZE) { return sqProjectKey.substring(sqProjectKey.length() - MAX_PROJECT_KEY_SIZE); } return sqProjectKey; } }
2,407
36.625
96
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/SetPatAction.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.almintegration.ws; import com.google.common.base.Strings; import java.util.Arrays; import java.util.Optional; 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.Preconditions; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.sonar.db.alm.setting.ALM.AZURE_DEVOPS; import static org.sonar.db.alm.setting.ALM.BITBUCKET; import static org.sonar.db.alm.setting.ALM.BITBUCKET_CLOUD; import static org.sonar.db.alm.setting.ALM.GITLAB; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SetPatAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_PAT = "pat"; private static final String PARAM_USERNAME = "username"; private final DbClient dbClient; private final UserSession userSession; public SetPatAction(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("set_pat") .setDescription("Set a Personal Access Token for the given DevOps Platform setting<br/>" + "Only valid for Azure DevOps, Bitbucket Server, GitLab and Bitbucket Cloud Setting<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setSince("8.2") .setHandler(this) .setChangelog(new Change("9.0", "Bitbucket Cloud support and optional Username parameter were added")); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PAT) .setRequired(true) .setMaximumLength(2000) .setDescription("Personal Access Token"); action.createParam(PARAM_USERNAME) .setRequired(false) .setMaximumLength(2000) .setDescription("Username"); } @Override public void handle(Request request, Response response) { doHandle(request); response.noContent(); } private void doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String pat = request.mandatoryParam(PARAM_PAT); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String username = request.param(PARAM_USERNAME); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); AlmSettingDto almSetting = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(format("DevOps Platform Setting '%s' not found", almSettingKey))); Preconditions.checkArgument(Arrays.asList(AZURE_DEVOPS, BITBUCKET, GITLAB, BITBUCKET_CLOUD) .contains(almSetting.getAlm()), "Only Azure DevOps, Bitbucket Server, GitLab and Bitbucket Cloud Settings are supported."); if(almSetting.getAlm().equals(BITBUCKET_CLOUD)) { Preconditions.checkArgument(!Strings.isNullOrEmpty(username), "Username cannot be null for Bitbucket Cloud"); } String resultingPat = CredentialsEncoderHelper.encodeCredentials(almSetting.getAlm(), pat, username); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSetting); if (almPatDto.isPresent()) { AlmPatDto almPat = almPatDto.get(); almPat.setPersonalAccessToken(resultingPat); dbClient.almPatDao().update(dbSession, almPat, userSession.getLogin(), almSetting.getKey()); } else { AlmPatDto almPat = new AlmPatDto() .setPersonalAccessToken(resultingPat) .setAlmSettingUuid(almSetting.getUuid()) .setUserUuid(userUuid); dbClient.almPatDao().insert(dbSession, almPat, userSession.getLogin(), almSetting.getKey()); } dbSession.commit(); } } }
5,223
40.460317
131
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/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.almintegration.ws; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/azure/ImportAzureProjectAction.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.almintegration.ws.azure; import java.util.Optional; import javax.inject.Inject; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureRepo; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects.CreateWsResponse; import static java.util.Objects.requireNonNull; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportAzureProjectAction implements AlmIntegrationsWsAction { private static final String PARAM_REPOSITORY_NAME = "repositoryName"; private static final String PARAM_PROJECT_NAME = "projectName"; private final DbClient dbClient; private final UserSession userSession; private final AzureDevOpsHttpClient azureDevOpsHttpClient; private final ProjectDefaultVisibility projectDefaultVisibility; private final ComponentUpdater componentUpdater; private final ImportHelper importHelper; private final ProjectKeyGenerator projectKeyGenerator; private final NewCodeDefinitionResolver newCodeDefinitionResolver; private final DefaultBranchNameResolver defaultBranchNameResolver; @Inject public ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient, ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver, DefaultBranchNameResolver defaultBranchNameResolver) { this.dbClient = dbClient; this.userSession = userSession; this.azureDevOpsHttpClient = azureDevOpsHttpClient; this.projectDefaultVisibility = projectDefaultVisibility; this.componentUpdater = componentUpdater; this.importHelper = importHelper; this.projectKeyGenerator = projectKeyGenerator; this.newCodeDefinitionResolver = newCodeDefinitionResolver; this.defaultBranchNameResolver = defaultBranchNameResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("import_azure_project") .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" + "Autoconfigure pull request decoration mechanism.<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setInternal(true) .setSince("8.6") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PROJECT_NAME) .setRequired(true) .setMaximumLength(200) .setDescription("Azure project name"); action.createParam(PARAM_REPOSITORY_NAME) .setRequired(true) .setMaximumLength(200) .setDescription("Azure repository name"); action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE) .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE) .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); } @Override public void handle(Request request, Response response) { CreateWsResponse createResponse = doHandle(request); writeProtobuf(createResponse, request, response); } private CreateWsResponse doHandle(Request request) { importHelper.checkProvisionProjectPermission(); AlmSettingDto almSettingDto = importHelper.getAlmSetting(request); String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE); String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { String pat = getPat(dbSession, almSettingDto); String projectName = request.mandatoryParam(PARAM_PROJECT_NAME); String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME); String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName); ComponentCreationData componentCreationData = createProject(dbSession, repo); ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow(); populatePRSetting(dbSession, repo, projectDto, almSettingDto); checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue); if (newCodeDefinitionType != null) { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue); } componentUpdater.commitAndIndex(dbSession, componentCreationData); return toCreateResponse(projectDto); } } private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) { String userUuid = importHelper.getUserUuid(); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); return almPatDto.map(AlmPatDto::getPersonalAccessToken) .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey()))); } private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) { boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate(); String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName()); return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder() .setKey(uniqueProjectKey) .setName(repo.getName()) .setPrivate(visibility) .setQualifier(PROJECT) .build(), userSession.isLoggedIn() ? userSession.getUuid() : null, userSession.isLoggedIn() ? userSession.getLogin() : null, repo.getDefaultBranchName()); } private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) { ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto() .setAlmSettingUuid(almSettingDto.getUuid()) .setAlmRepo(repo.getName()) .setAlmSlug(repo.getProject().getName()) .setProjectUuid(projectDto.getUuid()) .setMonorepo(false); dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey()); } }
9,232
45.631313
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsAction.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.almintegration.ws.azure; import java.util.List; import java.util.Optional; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureProject; import org.sonar.alm.client.azure.GsonAzureProjectList; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations.AzureProject; import org.sonarqube.ws.AlmIntegrations.ListAzureProjectsWsResponse; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListAzureProjectsAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private final DbClient dbClient; private final UserSession userSession; private final AzureDevOpsHttpClient azureDevOpsHttpClient; public ListAzureProjectsAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient) { this.dbClient = dbClient; this.userSession = userSession; this.azureDevOpsHttpClient = azureDevOpsHttpClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list_azure_projects") .setDescription("List Azure projects<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.6") .setResponseExample(getClass().getResource("example-list_azure_projects.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); } @Override public void handle(Request request, Response response) { ListAzureProjectsWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private ListAzureProjectsWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String url = requireNonNull(almSettingDto.getUrl(), "URL cannot be null"); GsonAzureProjectList projectList = azureDevOpsHttpClient.getProjects(url, pat); List<AzureProject> values = projectList.getValues().stream() .map(ListAzureProjectsAction::toAzureProject) .sorted(comparing(AzureProject::getName, String::compareToIgnoreCase)) .toList(); ListAzureProjectsWsResponse.Builder builder = ListAzureProjectsWsResponse.newBuilder() .addAllProjects(values); return builder.build(); } } private static AzureProject toAzureProject(GsonAzureProject project) { return AzureProject.newBuilder() .setName(project.getName()) .setDescription(Optional.ofNullable(project.getDescription()).orElse("")) .build(); } }
4,835
41.052174
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/azure/SearchAzureReposAction.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.almintegration.ws.azure; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureRepo; import org.sonar.alm.client.azure.GsonAzureRepoList; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations.AzureRepo; import org.sonarqube.ws.AlmIntegrations.SearchAzureReposWsResponse; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang.StringUtils.containsIgnoreCase; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchAzureReposAction implements AlmIntegrationsWsAction { private static final Logger LOG = LoggerFactory.getLogger(SearchAzureReposAction.class); private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_PROJECT_NAME = "projectName"; private static final String PARAM_SEARCH_QUERY = "searchQuery"; private final DbClient dbClient; private final UserSession userSession; private final AzureDevOpsHttpClient azureDevOpsHttpClient; public SearchAzureReposAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient) { this.dbClient = dbClient; this.userSession = userSession; this.azureDevOpsHttpClient = azureDevOpsHttpClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("search_azure_repos") .setDescription("Search the Azure repositories<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.6") .setResponseExample(getClass().getResource("example-search_azure_repos.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PROJECT_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Project name filter"); action.createParam(PARAM_SEARCH_QUERY) .setRequired(false) .setMaximumLength(200) .setDescription("Search query filter"); } @Override public void handle(Request request, Response response) { SearchAzureReposWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private SearchAzureReposWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String projectKey = request.param(PARAM_PROJECT_NAME); String searchQuery = request.param(PARAM_SEARCH_QUERY); String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); GsonAzureRepoList gsonAzureRepoList = azureDevOpsHttpClient.getRepos(url, pat, projectKey); Map<ProjectKeyName, ProjectDto> sqProjectsKeyByAzureKey = getSqProjectsKeyByCustomKey(dbSession, almSettingDto, gsonAzureRepoList); List<AzureRepo> repositories = gsonAzureRepoList.getValues() .stream() .filter(r -> isSearchOnlyByProjectName(searchQuery) || doesSearchCriteriaMatchProjectOrRepo(r, searchQuery)) .map(repo -> toAzureRepo(repo, sqProjectsKeyByAzureKey)) .sorted(comparing(AzureRepo::getName, String::compareToIgnoreCase)) .toList(); LOG.debug(repositories.toString()); return SearchAzureReposWsResponse.newBuilder() .addAllRepositories(repositories) .build(); } } private Map<ProjectKeyName, ProjectDto> getSqProjectsKeyByCustomKey(DbSession dbSession, AlmSettingDto almSettingDto, GsonAzureRepoList azureProjectList) { Set<String> projectNames = azureProjectList.getValues().stream().map(r -> r.getProject().getName()).collect(toSet()); Set<ProjectKeyName> azureProjectsAndRepos = azureProjectList.getValues().stream().map(ProjectKeyName::from).collect(toSet()); List<ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao() .selectByAlmSettingAndSlugs(dbSession, almSettingDto, projectNames); Map<String, ProjectAlmSettingDto> filteredProjectsByUuid = projectAlmSettingDtos .stream() .filter(p -> azureProjectsAndRepos.contains(ProjectKeyName.from(p))) .collect(toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity())); Set<String> projectUuids = filteredProjectsByUuid.values().stream().map(ProjectAlmSettingDto::getProjectUuid).collect(toSet()); return dbClient.projectDao().selectByUuids(dbSession, projectUuids) .stream() .collect(Collectors.toMap( projectDto -> ProjectKeyName.from(filteredProjectsByUuid.get(projectDto.getUuid())), p -> p, resolveNameCollisionOperatorByNaturalOrder())); } private static boolean isSearchOnlyByProjectName(@Nullable String criteria) { return criteria == null || criteria.isEmpty(); } private static boolean doesSearchCriteriaMatchProjectOrRepo(GsonAzureRepo repo, String criteria) { boolean matchProject = containsIgnoreCase(repo.getProject().getName(), criteria); boolean matchRepo = containsIgnoreCase(repo.getName(), criteria); return matchProject || matchRepo; } private static AzureRepo toAzureRepo(GsonAzureRepo azureRepo, Map<ProjectKeyName, ProjectDto> sqProjectsKeyByAzureKey) { AzureRepo.Builder builder = AzureRepo.newBuilder() .setName(azureRepo.getName()) .setProjectName(azureRepo.getProject().getName()); ProjectDto projectDto = sqProjectsKeyByAzureKey.get(ProjectKeyName.from(azureRepo)); if (projectDto != null) { builder.setSqProjectName(projectDto.getName()); builder.setSqProjectKey(projectDto.getKey()); } return builder.build(); } private static BinaryOperator<ProjectDto> resolveNameCollisionOperatorByNaturalOrder() { return (a, b) -> b.getKey().compareTo(a.getKey()) > 0 ? a : b; } static class ProjectKeyName { final String projectName; final String repoName; ProjectKeyName(String projectName, String repoName) { this.projectName = projectName; this.repoName = repoName; } public static ProjectKeyName from(ProjectAlmSettingDto project) { return new ProjectKeyName(project.getAlmSlug(), project.getAlmRepo()); } public static ProjectKeyName from(GsonAzureRepo gsonAzureRepo) { return new ProjectKeyName(gsonAzureRepo.getProject().getName(), gsonAzureRepo.getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProjectKeyName that = (ProjectKeyName) o; return Objects.equals(projectName, that.projectName) && Objects.equals(repoName, that.repoName); } @Override public int hashCode() { return Objects.hash(projectName, repoName); } } }
9,483
39.186441
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/azure/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.almintegration.ws.azure; import javax.annotation.ParametersAreNonnullByDefault;
980
39.875
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketcloud/ImportBitbucketCloudRepoAction.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.almintegration.ws.bitbucketcloud; import java.util.Optional; import javax.annotation.Nullable; import javax.inject.Inject; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.component.NewComponent; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects; import static java.util.Optional.ofNullable; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportBitbucketCloudRepoAction implements AlmIntegrationsWsAction { private static final String PARAM_REPO_SLUG = "repositorySlug"; private final DbClient dbClient; private final UserSession userSession; private final BitbucketCloudRestClient bitbucketCloudRestClient; private final ProjectDefaultVisibility projectDefaultVisibility; private final ComponentUpdater componentUpdater; private final ImportHelper importHelper; private final ProjectKeyGenerator projectKeyGenerator; private final NewCodeDefinitionResolver newCodeDefinitionResolver; private final DefaultBranchNameResolver defaultBranchNameResolver; @Inject public ImportBitbucketCloudRepoAction(DbClient dbClient, UserSession userSession, BitbucketCloudRestClient bitbucketCloudRestClient, ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver, DefaultBranchNameResolver defaultBranchNameResolver) { this.dbClient = dbClient; this.userSession = userSession; this.bitbucketCloudRestClient = bitbucketCloudRestClient; this.projectDefaultVisibility = projectDefaultVisibility; this.componentUpdater = componentUpdater; this.importHelper = importHelper; this.projectKeyGenerator = projectKeyGenerator; this.newCodeDefinitionResolver = newCodeDefinitionResolver; this.defaultBranchNameResolver = defaultBranchNameResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("import_bitbucketcloud_repo") .setDescription("Create a SonarQube project with the information from the provided Bitbucket Cloud repository.<br/>" + "Autoconfigure pull request decoration mechanism.<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setInternal(true) .setSince("9.0") .setHandler(this); action.createParam(PARAM_REPO_SLUG) .setRequired(true) .setMaximumLength(200) .setDescription("Bitbucket Cloud repository slug"); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE) .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE) .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); } @Override public void handle(Request request, Response response) { Projects.CreateWsResponse createResponse = doHandle(request); writeProtobuf(createResponse, request, response); } private Projects.CreateWsResponse doHandle(Request request) { importHelper.checkProvisionProjectPermission(); String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE); String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE); String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG); AlmSettingDto almSettingDto = importHelper.getAlmSetting(request); String workspace = ofNullable(almSettingDto.getAppId()) .orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey()))); try (DbSession dbSession = dbClient.openSession(false)) { String pat = getPat(dbSession, almSettingDto); Repository repo = bitbucketCloudRestClient.getRepo(pat, workspace, repoSlug); ComponentCreationData componentCreationData = createProject(dbSession, workspace, repo, repo.getMainBranch().getName()); ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow(); populatePRSetting(dbSession, repo, projectDto, almSettingDto); checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue); if (newCodeDefinitionType != null) { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), Optional.ofNullable(repo.getMainBranch().getName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue); } componentUpdater.commitAndIndex(dbSession, componentCreationData); return toCreateResponse(projectDto); } } private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) { String userUuid = importHelper.getUserUuid(); return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto) .map(AlmPatDto::getPersonalAccessToken) .orElseThrow(() -> new IllegalArgumentException(String.format("Username and App Password for '%s' is missing", almSettingDto.getKey()))); } private ComponentCreationData createProject(DbSession dbSession, String workspace, Repository repo, @Nullable String defaultBranchName) { boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate(); String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(workspace, repo.getSlug()); NewComponent mainBranch = newComponentBuilder() .setKey(uniqueProjectKey) .setName(repo.getName()) .setPrivate(visibility) .setQualifier(PROJECT) .build(); String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null; String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null; return componentUpdater.createWithoutCommit(dbSession, mainBranch, userUuid, userLogin, defaultBranchName); } private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) { ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto() .setAlmSettingUuid(almSettingDto.getUuid()) // Bitbucket Cloud PR decoration reads almRepo .setAlmRepo(repo.getSlug()) .setProjectUuid(projectDto.getUuid()) .setMonorepo(false); dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey()); } }
9,320
46.075758
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketcloud/SearchBitbucketCloudReposAction.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.almintegration.ws.bitbucketcloud; import java.util.List; import java.util.Map; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository; import org.sonar.alm.client.bitbucket.bitbucketcloud.RepositoryList; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations.BBCRepo; import org.sonarqube.ws.AlmIntegrations.SearchBitbucketcloudReposWsResponse; import org.sonarqube.ws.Common.Paging; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; 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.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchBitbucketCloudReposAction implements AlmIntegrationsWsAction { private static final BinaryOperator<String> resolveCollisionByNaturalOrder = (a, b) -> a.compareTo(b) < 0 ? a : b; private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_REPO_NAME = "repositoryName"; private static final int DEFAULT_PAGE_SIZE = 20; private static final int MAX_PAGE_SIZE = 100; private final DbClient dbClient; private final UserSession userSession; private final BitbucketCloudRestClient bitbucketCloudRestClient; public SearchBitbucketCloudReposAction(DbClient dbClient, UserSession userSession, BitbucketCloudRestClient bitbucketCloudRestClient) { this.dbClient = dbClient; this.userSession = userSession; this.bitbucketCloudRestClient = bitbucketCloudRestClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("search_bitbucketcloud_repos") .setDescription("Search the Bitbucket Cloud repositories<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("9.0") .setResponseExample(getClass().getResource("example-search_bitbucketcloud_repos.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_REPO_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Repository name filter"); action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE); } @Override public void handle(Request request, Response response) { SearchBitbucketcloudReposWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private SearchBitbucketcloudReposWsResponse doHandle(Request request) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String repoName = request.param(PARAM_REPO_NAME); int page = request.mandatoryParamAsInt(PAGE); int pageSize = request.mandatoryParamAsInt(PAGE_SIZE); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); String workspace = ofNullable(almSettingDto.getAppId()) .orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey()))); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); RepositoryList repositoryList = bitbucketCloudRestClient.searchRepos(pat, workspace, repoName, page, pageSize); Map<String, String> sqProjectKeyByRepoSlug = getSqProjectKeyByRepoSlug(dbSession, almSettingDto, repositoryList.getValues()); List<BBCRepo> bbcRepos = repositoryList.getValues().stream() .map(repository -> toBBCRepo(repository, workspace, sqProjectKeyByRepoSlug)) .toList(); SearchBitbucketcloudReposWsResponse.Builder builder = SearchBitbucketcloudReposWsResponse.newBuilder() .setIsLastPage(repositoryList.getNext() == null) .setPaging(Paging.newBuilder().setPageIndex(page).setPageSize(pageSize).build()) .addAllRepositories(bbcRepos); return builder.build(); } } private Map<String, String> getSqProjectKeyByRepoSlug(DbSession dbSession, AlmSettingDto almSettingDto, List<Repository> repositories) { Set<String> repoSlugs = repositories.stream().map(Repository::getSlug).collect(toSet()); List<ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao().selectByAlmSettingAndRepos(dbSession, almSettingDto, repoSlugs); Map<String, String> repoSlugByProjectUuid = projectAlmSettingDtos.stream() .collect(toMap(ProjectAlmSettingDto::getProjectUuid, ProjectAlmSettingDto::getAlmRepo)); return dbClient.projectDao().selectByUuids(dbSession, repoSlugByProjectUuid.keySet()) .stream() .collect(toMap(p -> repoSlugByProjectUuid.get(p.getUuid()), ProjectDto::getKey, resolveCollisionByNaturalOrder)); } private static BBCRepo toBBCRepo(Repository gsonBBCRepo, String workspace, Map<String, String> sqProjectKeyByRepoSlug) { BBCRepo.Builder builder = BBCRepo.newBuilder() .setSlug(gsonBBCRepo.getSlug()) .setUuid(gsonBBCRepo.getUuid()) .setName(gsonBBCRepo.getName()) .setWorkspace(workspace) .setProjectKey(gsonBBCRepo.getProject().getKey()); String sqProjectKey = sqProjectKeyByRepoSlug.get(gsonBBCRepo.getSlug()); ofNullable(sqProjectKey).ifPresent(builder::setSqProjectKey); return builder.build(); } }
7,588
44.993939
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketcloud/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.almintegration.ws.bitbucketcloud; import javax.annotation.ParametersAreNonnullByDefault;
989
40.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectAction.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.almintegration.ws.bitbucketserver; import java.util.Optional; import javax.annotation.Nullable; import javax.inject.Inject; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Branch; import org.sonar.alm.client.bitbucketserver.BranchesList; import org.sonar.alm.client.bitbucketserver.Repository; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.component.NewComponent; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects; import static java.util.Objects.requireNonNull; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction { private static final String PARAM_PROJECT_KEY = "projectKey"; private static final String PARAM_REPO_SLUG = "repositorySlug"; private final DbClient dbClient; private final UserSession userSession; private final BitbucketServerRestClient bitbucketServerRestClient; private final ProjectDefaultVisibility projectDefaultVisibility; private final ComponentUpdater componentUpdater; private final ImportHelper importHelper; private final ProjectKeyGenerator projectKeyGenerator; private final NewCodeDefinitionResolver newCodeDefinitionResolver; private final DefaultBranchNameResolver defaultBranchNameResolver; @Inject public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient, ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver, DefaultBranchNameResolver defaultBranchNameResolver) { this.dbClient = dbClient; this.userSession = userSession; this.bitbucketServerRestClient = bitbucketServerRestClient; this.projectDefaultVisibility = projectDefaultVisibility; this.componentUpdater = componentUpdater; this.importHelper = importHelper; this.projectKeyGenerator = projectKeyGenerator; this.newCodeDefinitionResolver = newCodeDefinitionResolver; this.defaultBranchNameResolver = defaultBranchNameResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("import_bitbucketserver_project") .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" + "Autoconfigure pull request decoration mechanism.<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setInternal(true) .setSince("8.2") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PROJECT_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("BitbucketServer project key"); action.createParam(PARAM_REPO_SLUG) .setRequired(true) .setMaximumLength(200) .setDescription("BitbucketServer repository slug"); action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE) .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE) .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); } @Override public void handle(Request request, Response response) { Projects.CreateWsResponse createResponse = doHandle(request); writeProtobuf(createResponse, request, response); } private Projects.CreateWsResponse doHandle(Request request) { importHelper.checkProvisionProjectPermission(); AlmSettingDto almSettingDto = importHelper.getAlmSetting(request); String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE); String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { String pat = getPat(dbSession, almSettingDto); String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY); String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG); String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug); String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url); ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName); ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow(); populatePRSetting(dbSession, repo, projectDto, almSettingDto); checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue); if (newCodeDefinitionType != null) { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue); } componentUpdater.commitAndIndex(dbSession, componentCreationData); return toCreateResponse(projectDto); } } private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) { String userUuid = importHelper.getUserUuid(); Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); return almPatDot.map(AlmPatDto::getPersonalAccessToken) .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey()))); } private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) { BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug); Optional<Branch> defaultBranch = branches.findDefaultBranch(); return defaultBranch.map(Branch::getName).orElse(null); } private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) { boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate(); String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug()); NewComponent newProject = newComponentBuilder() .setKey(uniqueProjectKey) .setName(repo.getName()) .setPrivate(visibility) .setQualifier(PROJECT) .build(); String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null; String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null; return componentUpdater.createWithoutCommit(dbSession, newProject, userUuid, userLogin, defaultBranchName); } private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) { ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto() .setAlmSettingUuid(almSettingDto.getUuid()) .setAlmRepo(repo.getProject().getKey()) .setAlmSlug(repo.getSlug()) .setProjectUuid(componentDto.getUuid()) .setMonorepo(false); dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), componentDto.getName(), componentDto.getKey()); } }
10,044
45.50463
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketserver/ListBitbucketServerProjectsAction.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.almintegration.ws.bitbucketserver; import java.util.List; import java.util.Optional; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Project; import org.sonar.alm.client.bitbucketserver.ProjectList; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations.AlmProject; import org.sonarqube.ws.AlmIntegrations.ListBitbucketserverProjectsWsResponse; import static java.util.Objects.requireNonNull; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListBitbucketServerProjectsAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private final DbClient dbClient; private final UserSession userSession; private final BitbucketServerRestClient bitbucketServerRestClient; public ListBitbucketServerProjectsAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient) { this.dbClient = dbClient; this.userSession = userSession; this.bitbucketServerRestClient = bitbucketServerRestClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list_bitbucketserver_projects") .setDescription("List the Bitbucket Server projects<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.2") .setResponseExample(getClass().getResource("example-list_bitbucketserver_projects.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); } @Override public void handle(Request request, Response response) { ListBitbucketserverProjectsWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private ListBitbucketserverProjectsWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String url = requireNonNull(almSettingDto.getUrl(), "URL cannot be null"); ProjectList projectList = bitbucketServerRestClient.getProjects(url, pat); List<AlmProject> values = projectList.getValues().stream().map(ListBitbucketServerProjectsAction::toAlmProject).toList(); ListBitbucketserverProjectsWsResponse.Builder builder = ListBitbucketserverProjectsWsResponse.newBuilder() .addAllProjects(values); return builder.build(); } } private static AlmProject toAlmProject(Project project) { return AlmProject.newBuilder() .setKey(project.getKey()) .setName(project.getName()) .build(); } }
4,782
42.481818
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposAction.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.almintegration.ws.bitbucketserver; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.BinaryOperator; import java.util.function.Function; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Repository; import org.sonar.alm.client.bitbucketserver.RepositoryList; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDao; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDao; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations.BBSRepo; import org.sonarqube.ws.AlmIntegrations.SearchBitbucketserverReposWsResponse; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchBitbucketServerReposAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_REPO_NAME = "repositoryName"; private static final String PARAM_PROJECT_NAME = "projectName"; private final DbClient dbClient; private final UserSession userSession; private final BitbucketServerRestClient bitbucketServerRestClient; private final ProjectAlmSettingDao projectAlmSettingDao; private final ProjectDao projectDao; public SearchBitbucketServerReposAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient, ProjectAlmSettingDao projectAlmSettingDao, ProjectDao projectDao) { this.dbClient = dbClient; this.userSession = userSession; this.bitbucketServerRestClient = bitbucketServerRestClient; this.projectAlmSettingDao = projectAlmSettingDao; this.projectDao = projectDao; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("search_bitbucketserver_repos") .setDescription("Search the Bitbucket Server repositories with REPO_ADMIN access<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.2") .setResponseExample(getClass().getResource("example-search_bitbucketserver_repos.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PROJECT_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Project name filter"); action.createParam(PARAM_REPO_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Repository name filter"); } @Override public void handle(Request request, Response response) { SearchBitbucketserverReposWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private SearchBitbucketserverReposWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String projectKey = request.param(PARAM_PROJECT_NAME); String repoName = request.param(PARAM_REPO_NAME); String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); RepositoryList gsonBBSRepoList = bitbucketServerRestClient.getRepos(url, pat, projectKey, repoName); Map<String, String> sqProjectsKeyByBBSKey = getSqProjectsKeyByBBSKey(dbSession, almSettingDto, gsonBBSRepoList); List<BBSRepo> bbsRepos = gsonBBSRepoList.getValues().stream().map(gsonBBSRepo -> toBBSRepo(gsonBBSRepo, sqProjectsKeyByBBSKey)) .toList(); SearchBitbucketserverReposWsResponse.Builder builder = SearchBitbucketserverReposWsResponse.newBuilder() .setIsLastPage(gsonBBSRepoList.isLastPage()) .addAllRepositories(bbsRepos); return builder.build(); } } private Map<String, String> getSqProjectsKeyByBBSKey(DbSession dbSession, AlmSettingDto almSettingDto, RepositoryList gsonBBSRepoList) { Set<String> slugs = gsonBBSRepoList.getValues().stream().map(Repository::getSlug).collect(toSet()); List<ProjectAlmSettingDto> projectAlmSettingDtos = projectAlmSettingDao.selectByAlmSettingAndSlugs(dbSession, almSettingDto, slugs); // As the previous request return bbs only filtered by slug, we need to do an additional filtering on bitbucketServer projectKey + slug Set<String> bbsProjectsAndRepos = gsonBBSRepoList.getValues().stream().map(SearchBitbucketServerReposAction::customKey).collect(toSet()); Map<String, ProjectAlmSettingDto> filteredProjectsByUuid = projectAlmSettingDtos.stream() .filter(p -> bbsProjectsAndRepos.contains(customKey(p))) .collect(toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity())); Set<String> projectUuids = filteredProjectsByUuid.values().stream().map(ProjectAlmSettingDto::getProjectUuid).collect(toSet()); return projectDao.selectByUuids(dbSession, projectUuids).stream() .collect(toMap(p -> customKey(filteredProjectsByUuid.get(p.getUuid())), ProjectDto::getKey, resolveNameCollisionOperatorByNaturalOrder())); } private static BBSRepo toBBSRepo(Repository gsonBBSRepo, Map<String, String> sqProjectsKeyByBBSKey) { BBSRepo.Builder builder = BBSRepo.newBuilder() .setSlug(gsonBBSRepo.getSlug()) .setId(gsonBBSRepo.getId()) .setName(gsonBBSRepo.getName()) .setProjectKey(gsonBBSRepo.getProject().getKey()); String sqProjectKey = sqProjectsKeyByBBSKey.get(customKey(gsonBBSRepo)); if (sqProjectKey != null) { builder.setSqProjectKey(sqProjectKey); } return builder.build(); } private static String customKey(ProjectAlmSettingDto project) { return project.getAlmRepo() + "/" + project.getAlmSlug(); } private static String customKey(Repository gsonBBSRepo) { return gsonBBSRepo.getProject().getKey() + "/" + gsonBBSRepo.getSlug(); } private static BinaryOperator<String> resolveNameCollisionOperatorByNaturalOrder() { return (a, b) -> new TreeSet<>(Arrays.asList(a, b)).first(); } }
8,327
46.050847
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/bitbucketserver/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.almintegration.ws.bitbucketserver; import javax.annotation.ParametersAreNonnullByDefault;
990
40.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/GetGithubClientIdAction.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.almintegration.ws.github; 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.alm.setting.AlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class GetGithubClientIdAction implements AlmIntegrationsWsAction { public static final String PARAM_ALM_SETTING = "almSetting"; private final DbClient dbClient; private final UserSession userSession; public GetGithubClientIdAction(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("get_github_client_id") .setDescription("Get the client id of a Github Integration.") .setInternal(true) .setSince("8.4") .setResponseExample(getClass().getResource("example-get_github_client_id.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); } @Override public void handle(Request request, Response response) { AlmIntegrations.GithubClientIdWsResponse getResponse = doHandle(request); writeProtobuf(getResponse, request, response); } private AlmIntegrations.GithubClientIdWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); AlmSettingDto almSetting = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("Github Setting '%s' not found", almSettingKey))); if (almSetting.getClientId() == null) { throw new NotFoundException(String.format("No client ID for setting with key '%s'", almSettingKey)); } return AlmIntegrations.GithubClientIdWsResponse.newBuilder() .setClientId(almSetting.getClientId()) .build(); } } }
3,371
38.209302
113
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/GithubProvisioningAction.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.almintegration.ws.github; import org.sonar.server.ws.WsAction; public interface GithubProvisioningAction extends WsAction { }
996
37.346154
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/GithubProvisioningWs.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.almintegration.ws.github; import java.util.Set; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.WebService; @ServerSide public class GithubProvisioningWs implements WebService { public static final String API_ENDPOINT = "api/github_provisioning"; private final Set<GithubProvisioningAction> actions; public GithubProvisioningWs(Set<GithubProvisioningAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(API_ENDPOINT) .setDescription("Manage GitHub provisioning.") .setSince("10.1"); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,592
32.893617
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/ImportGithubProjectAction.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.almintegration.ws.github; import java.util.Optional; import javax.inject.Inject; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClient.Repository; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.alm.client.github.security.AccessToken; import org.sonar.alm.client.github.security.UserAccessToken; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects; import static java.util.Objects.requireNonNull; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING; import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportGithubProjectAction implements AlmIntegrationsWsAction { public static final String PARAM_ORGANIZATION = "organization"; public static final String PARAM_REPOSITORY_KEY = "repositoryKey"; private final DbClient dbClient; private final UserSession userSession; private final ProjectDefaultVisibility projectDefaultVisibility; private final GithubApplicationClient githubApplicationClient; private final ComponentUpdater componentUpdater; private final ImportHelper importHelper; private final ProjectKeyGenerator projectKeyGenerator; private final NewCodeDefinitionResolver newCodeDefinitionResolver; private final DefaultBranchNameResolver defaultBranchNameResolver; @Inject public ImportGithubProjectAction(DbClient dbClient, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility, GithubApplicationClientImpl githubApplicationClient, ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver, DefaultBranchNameResolver defaultBranchNameResolver) { this.dbClient = dbClient; this.userSession = userSession; this.projectDefaultVisibility = projectDefaultVisibility; this.githubApplicationClient = githubApplicationClient; this.componentUpdater = componentUpdater; this.importHelper = importHelper; this.projectKeyGenerator = projectKeyGenerator; this.newCodeDefinitionResolver = newCodeDefinitionResolver; this.defaultBranchNameResolver = defaultBranchNameResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("import_github_project") .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" + "Autoconfigure pull request decoration mechanism.<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setInternal(true) .setSince("8.4") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_ORGANIZATION) .setRequired(true) .setMaximumLength(200) .setDescription("GitHub organization"); action.createParam(PARAM_REPOSITORY_KEY) .setRequired(true) .setMaximumLength(256) .setDescription("GitHub repository key"); action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE) .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE) .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); } @Override public void handle(Request request, Response response) { Projects.CreateWsResponse createResponse = doHandle(request); writeProtobuf(createResponse, request, response); } private Projects.CreateWsResponse doHandle(Request request) { importHelper.checkProvisionProjectPermission(); AlmSettingDto almSettingDto = importHelper.getAlmSetting(request); String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE); String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { AccessToken accessToken = getAccessToken(dbSession, almSettingDto); String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION); String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY); String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey) .orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey))); ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch()); ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow(); populatePRSetting(dbSession, repository, projectDto, almSettingDto); checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue); if (newCodeDefinitionType != null) { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue); } componentUpdater.commitAndIndex(dbSession, componentCreationData); return toCreateResponse(projectDto); } } private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) { String userUuid = importHelper.getUserUuid(); return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto) .map(AlmPatDto::getPersonalAccessToken) .map(UserAccessToken::new) .orElseThrow(() -> new IllegalArgumentException("No personal access token found")); } private ComponentCreationData createProject(DbSession dbSession, Repository repo, String mainBranchName) { boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate(); String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getFullName()); return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder() .setKey(uniqueProjectKey) .setName(repo.getName()) .setPrivate(visibility) .setQualifier(PROJECT) .build(), userSession.getUuid(), userSession.getLogin(), mainBranchName); } private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) { ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto() .setAlmSettingUuid(almSettingDto.getUuid()) .setAlmRepo(repo.getFullName()) .setAlmSlug(null) .setProjectUuid(projectDto.getUuid()) .setSummaryCommentEnabled(true) .setMonorepo(false); dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey()); } }
9,596
45.814634
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/ListGithubOrganizationsAction.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.almintegration.ws.github; import java.util.List; import java.util.Optional; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClient.Organization; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.alm.client.github.security.AccessToken; import org.sonar.alm.client.github.security.UserAccessToken; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.ListGithubOrganizationsWsResponse; import org.sonarqube.ws.Common; import static java.util.Objects.requireNonNull; 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.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListGithubOrganizationsAction implements AlmIntegrationsWsAction { public static final String PARAM_ALM_SETTING = "almSetting"; public static final String PARAM_TOKEN = "token"; private final DbClient dbClient; private final Encryption encryption; private final UserSession userSession; private final GithubApplicationClient githubApplicationClient; public ListGithubOrganizationsAction(DbClient dbClient, Settings settings, UserSession userSession, GithubApplicationClientImpl githubApplicationClient) { this.dbClient = dbClient; this.encryption = settings.getEncryption(); this.userSession = userSession; this.githubApplicationClient = githubApplicationClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list_github_organizations") .setDescription("List GitHub organizations<br/>" + "Requires the 'Create Projects' permission") .setInternal(true) .setResponseExample(getClass().getResource("example-list_github_organizations.json")) .setSince("8.4") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_TOKEN) .setMaximumLength(200) .setDescription("Github authorization code"); action.createParam(PAGE) .setDescription("Index of the page to display") .setDefaultValue(1); action.createParam(PAGE_SIZE) .setDescription("Size for the paging to apply") .setDefaultValue(100); } @Override public void handle(Request request, Response response) { ListGithubOrganizationsWsResponse getResponse = doHandle(request); writeProtobuf(getResponse, request, response); } private ListGithubOrganizationsWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("GitHub Setting '%s' not found", almSettingKey))); String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null"); String url = requireNonNull(almSettingDto.getUrl(), String.format("No URL set for GitHub '%s'", almSettingKey)); AccessToken accessToken; if (request.hasParam(PARAM_TOKEN)) { String code = request.mandatoryParam(PARAM_TOKEN); String clientId = requireNonNull(almSettingDto.getClientId(), String.format("No clientId set for GitHub '%s'", almSettingKey)); String clientSecret = requireNonNull(almSettingDto.getDecryptedClientSecret(encryption), String.format("No clientSecret set for GitHub '%s'", almSettingKey)); try { accessToken = githubApplicationClient.createUserAccessToken(url, clientId, clientSecret, code); } catch (IllegalArgumentException e) { // it could also be that the code has expired! throw BadRequestException.create("Unable to authenticate with GitHub. " + "Check the GitHub App client ID and client secret configured in the Global Settings and try again."); } Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); if (almPatDto.isPresent()) { AlmPatDto almPat = almPatDto.get(); almPat.setPersonalAccessToken(accessToken.getValue()); dbClient.almPatDao().update(dbSession, almPat, userSession.getLogin(), almSettingDto.getKey()); } else { AlmPatDto almPat = new AlmPatDto() .setPersonalAccessToken(accessToken.getValue()) .setAlmSettingUuid(almSettingDto.getUuid()) .setUserUuid(userUuid); dbClient.almPatDao().insert(dbSession, almPat, userSession.getLogin(), almSettingDto.getKey()); } dbSession.commit(); } else { accessToken = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto) .map(AlmPatDto::getPersonalAccessToken) .map(UserAccessToken::new) .orElseThrow(() -> new IllegalArgumentException("No personal access token found")); } int page = request.hasParam(PAGE) ? request.mandatoryParamAsInt(PAGE) : 1; int pageSize = request.hasParam(PAGE_SIZE) ? request.mandatoryParamAsInt(PAGE_SIZE) : 100; GithubApplicationClient.Organizations githubOrganizations = githubApplicationClient.listOrganizations(url, accessToken, page, pageSize); ListGithubOrganizationsWsResponse.Builder response = ListGithubOrganizationsWsResponse.newBuilder() .setPaging(Common.Paging.newBuilder() .setPageIndex(page) .setPageSize(pageSize) .setTotal(githubOrganizations.getTotal()) .build()); List<Organization> organizations = githubOrganizations.getOrganizations(); if (organizations != null) { organizations .forEach(githubOrganization -> response.addOrganizations(AlmIntegrations.GithubOrganization.newBuilder() .setKey(githubOrganization.getLogin()) .setName(githubOrganization.getLogin()) .build())); } return response.build(); } } }
7,817
44.453488
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/ListGithubRepositoriesAction.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.almintegration.ws.github; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collectors; import org.sonar.alm.client.github.GithubApplicationClient; import org.sonar.alm.client.github.GithubApplicationClient.Repository; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.alm.client.github.security.AccessToken; import org.sonar.alm.client.github.security.UserAccessToken; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDao; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.Common; import static java.util.Objects.requireNonNull; 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.TEXT_QUERY; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListGithubRepositoriesAction implements AlmIntegrationsWsAction { public static final String PARAM_ALM_SETTING = "almSetting"; public static final String PARAM_ORGANIZATION = "organization"; private final DbClient dbClient; private final UserSession userSession; private final GithubApplicationClient githubApplicationClient; private final ProjectAlmSettingDao projectAlmSettingDao; public ListGithubRepositoriesAction(DbClient dbClient, UserSession userSession, GithubApplicationClientImpl githubApplicationClient, ProjectAlmSettingDao projectAlmSettingDao) { this.dbClient = dbClient; this.userSession = userSession; this.githubApplicationClient = githubApplicationClient; this.projectAlmSettingDao = projectAlmSettingDao; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list_github_repositories") .setDescription("List the GitHub repositories for an organization<br/>" + "Requires the 'Create Projects' permission") .setInternal(true) .setSince("8.4") .setResponseExample(getClass().getResource("example-list_github_repositories.json")) .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_ORGANIZATION) .setRequired(true) .setMaximumLength(200) .setDescription("Github organization"); action.createParam(TEXT_QUERY) .setDescription("Limit search to repositories that contain the supplied string") .setExampleValue("Apache"); action.createParam(PAGE) .setDescription("Index of the page to display") .setDefaultValue(1); action.createParam(PAGE_SIZE) .setDescription("Size for the paging to apply") .setDefaultValue(100); } @Override public void handle(Request request, Response response) { AlmIntegrations.ListGithubRepositoriesWsResponse getResponse = doHandle(request); writeProtobuf(getResponse, request, response); } private AlmIntegrations.ListGithubRepositoriesWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("GitHub Setting '%s' not found", almSettingKey))); String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null"); String url = requireNonNull(almSettingDto.getUrl(), String.format("No URL set for GitHub '%s'", almSettingKey)); AccessToken accessToken = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto) .map(AlmPatDto::getPersonalAccessToken) .map(UserAccessToken::new) .orElseThrow(() -> new IllegalArgumentException("No personal access token found")); int pageIndex = request.hasParam(PAGE) ? request.mandatoryParamAsInt(PAGE) : 1; int pageSize = request.hasParam(PAGE_SIZE) ? request.mandatoryParamAsInt(PAGE_SIZE) : 100; GithubApplicationClient.Repositories repositories = githubApplicationClient .listRepositories(url, accessToken, request.mandatoryParam(PARAM_ORGANIZATION), request.param(TEXT_QUERY), pageIndex, pageSize); AlmIntegrations.ListGithubRepositoriesWsResponse.Builder response = AlmIntegrations.ListGithubRepositoriesWsResponse.newBuilder() .setPaging(Common.Paging.newBuilder() .setPageIndex(pageIndex) .setPageSize(pageSize) .setTotal(repositories.getTotal()) .build()); List<Repository> repositoryList = repositories.getRepositories(); if (repositoryList != null) { Set<String> repo = repositoryList.stream().map(Repository::getFullName).collect(Collectors.toSet()); List<ProjectAlmSettingDto> projectAlmSettingDtos = projectAlmSettingDao.selectByAlmSettingAndRepos(dbSession, almSettingDto, repo); Map<String, ProjectDto> projectsDtoByAlmRepo = getProjectDtoByAlmRepo(dbSession, projectAlmSettingDtos); for (Repository repository : repositoryList) { AlmIntegrations.GithubRepository.Builder builder = AlmIntegrations.GithubRepository.newBuilder() .setId(repository.getId()) .setKey(repository.getFullName()) .setName(repository.getName()) .setUrl(repository.getUrl()); if (projectsDtoByAlmRepo.containsKey(repository.getFullName())) { Optional.ofNullable(projectsDtoByAlmRepo.get(repository.getFullName())) .ifPresent(p -> builder.setSqProjectKey(p.getKey())); } response.addRepositories(builder.build()); } } return response.build(); } } private Map<String, ProjectDto> getProjectDtoByAlmRepo(DbSession dbSession, List<ProjectAlmSettingDto> projectAlmSettingDtos) { Map<String, ProjectAlmSettingDto> projectAlmSettingDtoByProjectUuid = projectAlmSettingDtos.stream() .collect(Collectors.toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity())); Set<String> projectUuids = projectAlmSettingDtos.stream().map(ProjectAlmSettingDto::getProjectUuid).collect(Collectors.toSet()); return dbClient.projectDao().selectByUuids(dbSession, projectUuids) .stream() .collect(Collectors.toMap(projectDto -> projectAlmSettingDtoByProjectUuid.get(projectDto.getUuid()).getAlmRepo(), Function.identity(), resolveNameCollisionOperatorByNaturalOrder())); } private static BinaryOperator<ProjectDto> resolveNameCollisionOperatorByNaturalOrder() { Comparator<ProjectDto> comparator = Comparator.comparing(ProjectDto::getKey); return (a, b) -> comparator.compare(a, b) > 0 ? b : a; } }
8,478
44.342246
179
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/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.almintegration.ws.github; import javax.annotation.ParametersAreNonnullByDefault;
981
39.916667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/config/CheckAction.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.almintegration.ws.github.config; import com.google.gson.GsonBuilder; import java.nio.charset.StandardCharsets; import javax.servlet.http.HttpServletResponse; import org.sonar.alm.client.github.config.ConfigCheckResult; import org.sonar.alm.client.github.config.GithubProvisioningConfigValidator; import org.sonar.api.server.ServerSide; 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.almintegration.ws.github.GithubProvisioningAction; import org.sonar.server.user.UserSession; import org.sonarqube.ws.MediaTypes; @ServerSide public class CheckAction implements GithubProvisioningAction { private final UserSession userSession; private final GithubProvisioningConfigValidator githubProvisioningConfigValidator; public CheckAction(UserSession userSession, GithubProvisioningConfigValidator githubProvisioningConfigValidator) { this.userSession = userSession; this.githubProvisioningConfigValidator = githubProvisioningConfigValidator; } @Override public void define(WebService.NewController controller) { controller .createAction("check") .setPost(true) .setDescription("Validate Github provisioning configuration.") .setHandler(this) .setInternal(true) .setResponseExample(getClass().getResource("check-example.json")) .setSince("10.1"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); ConfigCheckResult result = githubProvisioningConfigValidator.checkConfig(); response.stream().setStatus(HttpServletResponse.SC_OK); response.stream().setMediaType(MediaTypes.JSON); response.stream().output().write(new GsonBuilder().create().toJson(result).getBytes(StandardCharsets.UTF_8)); response.stream().output().flush(); } }
2,770
38.585714
116
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/github/config/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.almintegration.ws.github.config; import javax.annotation.ParametersAreNonnullByDefault;
988
40.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/gitlab/ImportGitLabProjectAction.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.almintegration.ws.gitlab; import java.util.Optional; import javax.annotation.Nullable; import javax.inject.Inject; import org.sonar.alm.client.gitlab.GitLabBranch; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.alm.client.gitlab.Project; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Projects.CreateWsResponse; import static java.util.Objects.requireNonNull; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; public class ImportGitLabProjectAction implements AlmIntegrationsWsAction { public static final String PARAM_GITLAB_PROJECT_ID = "gitlabProjectId"; private final DbClient dbClient; private final UserSession userSession; private final ProjectDefaultVisibility projectDefaultVisibility; private final GitlabHttpClient gitlabHttpClient; private final ComponentUpdater componentUpdater; private final ImportHelper importHelper; private final ProjectKeyGenerator projectKeyGenerator; private final NewCodeDefinitionResolver newCodeDefinitionResolver; private final DefaultBranchNameResolver defaultBranchNameResolver; @Inject public ImportGitLabProjectAction(DbClient dbClient, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility, GitlabHttpClient gitlabHttpClient, ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver, DefaultBranchNameResolver defaultBranchNameResolver) { this.dbClient = dbClient; this.userSession = userSession; this.projectDefaultVisibility = projectDefaultVisibility; this.gitlabHttpClient = gitlabHttpClient; this.componentUpdater = componentUpdater; this.importHelper = importHelper; this.projectKeyGenerator = projectKeyGenerator; this.newCodeDefinitionResolver = newCodeDefinitionResolver; this.defaultBranchNameResolver = defaultBranchNameResolver; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("import_gitlab_project") .setDescription("Import a GitLab project to SonarQube, creating a new project and configuring MR decoration<br/>" + "Requires the 'Create Projects' permission") .setPost(true) .setSince("8.5") .setHandler(this); action.createParam(ImportHelper.PARAM_ALM_SETTING) .setRequired(true) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_GITLAB_PROJECT_ID) .setRequired(true) .setDescription("GitLab project ID"); action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE) .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE) .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION) .setSince("10.1"); } @Override public void handle(Request request, Response response) throws Exception { CreateWsResponse createResponse = doHandle(request); writeProtobuf(createResponse, request, response); } private CreateWsResponse doHandle(Request request) { importHelper.checkProvisionProjectPermission(); String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE); String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = importHelper.getAlmSetting(request); String pat = getPat(dbSession, almSettingDto); long gitlabProjectId = request.mandatoryParamAsLong(PARAM_GITLAB_PROJECT_ID); String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null"); Project gitlabProject = gitlabHttpClient.getProject(gitlabUrl, pat, gitlabProjectId); Optional<String> almMainBranchName = getAlmDefaultBranch(pat, gitlabProjectId, gitlabUrl); ComponentCreationData componentCreationData = createProject(dbSession, gitlabProject, almMainBranchName.orElse(null)); ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow(); populateMRSetting(dbSession, gitlabProjectId, projectDto, almSettingDto); checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue); if (newCodeDefinitionType != null) { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), almMainBranchName.orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue); } componentUpdater.commitAndIndex(dbSession, componentCreationData); return ImportHelper.toCreateResponse(projectDto); } } private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) { String userUuid = importHelper.getUserUuid(); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); return almPatDto.map(AlmPatDto::getPersonalAccessToken) .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey()))); } private Optional<String> getAlmDefaultBranch(String pat, long gitlabProjectId, String gitlabUrl) { Optional<GitLabBranch> almMainBranch = gitlabHttpClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst(); return almMainBranch.map(GitLabBranch::getName); } private void populateMRSetting(DbSession dbSession, Long gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto) { dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, new ProjectAlmSettingDto() .setProjectUuid(projectDto.getUuid()) .setAlmSettingUuid(almSettingDto.getUuid()) .setAlmRepo(gitlabProjectId.toString()) .setAlmSlug(null) .setMonorepo(false), almSettingDto.getKey(), projectDto.getName(), projectDto.getKey()); } private ComponentCreationData createProject(DbSession dbSession, Project gitlabProject, @Nullable String mainBranchName) { boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate(); String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace()); return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder() .setKey(uniqueProjectKey) .setName(gitlabProject.getName()) .setPrivate(visibility) .setQualifier(PROJECT) .build(), userSession.getUuid(), userSession.getLogin(), mainBranchName); } }
9,060
46.689474
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/gitlab/SearchGitlabReposAction.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.almintegration.ws.gitlab; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collectors; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.alm.client.gitlab.Project; import org.sonar.alm.client.gitlab.ProjectList; 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.alm.pat.AlmPatDto; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.GitlabRepository; import org.sonarqube.ws.Common.Paging; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toSet; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchGitlabReposAction implements AlmIntegrationsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private static final String PARAM_PROJECT_NAME = "projectName"; private static final int DEFAULT_PAGE_SIZE = 20; private static final int MAX_PAGE_SIZE = 500; private final DbClient dbClient; private final UserSession userSession; private final GitlabHttpClient gitlabHttpClient; public SearchGitlabReposAction(DbClient dbClient, UserSession userSession, GitlabHttpClient gitlabHttpClient) { this.dbClient = dbClient; this.userSession = userSession; this.gitlabHttpClient = gitlabHttpClient; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("search_gitlab_repos") .setDescription("Search the GitLab projects.<br/>" + "Requires the 'Create Projects' permission") .setPost(false) .setSince("8.5") .setHandler(this); action.createParam(PARAM_ALM_SETTING) .setRequired(true) .setMaximumLength(200) .setDescription("DevOps Platform setting key"); action.createParam(PARAM_PROJECT_NAME) .setRequired(false) .setMaximumLength(200) .setDescription("Project name filter"); action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE); action.setResponseExample(getClass().getResource("search_gitlab_repos.json")); } @Override public void handle(Request request, Response response) { AlmIntegrations.SearchGitlabReposWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private AlmIntegrations.SearchGitlabReposWsResponse doHandle(Request request) { String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); String projectName = request.param(PARAM_PROJECT_NAME); int pageNumber = request.mandatoryParamAsInt("p"); int pageSize = request.mandatoryParamAsInt("ps"); try (DbSession dbSession = dbClient.openSession(false)) { userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS); String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null"); AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey) .orElseThrow(() -> new NotFoundException(String.format("DevOps Platform Setting '%s' not found", almSettingKey))); Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto); String personalAccessToken = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found")); String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null"); ProjectList gitlabProjectList = gitlabHttpClient .searchProjects(gitlabUrl, personalAccessToken, projectName, pageNumber, pageSize); Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId = getSqProjectsKeyByGitlabProjectId(dbSession, almSettingDto, gitlabProjectList); List<GitlabRepository> gitlabRepositories = gitlabProjectList.getProjects().stream() .map(project -> toGitlabRepository(project, sqProjectsKeyByGitlabProjectId)) .toList(); Paging.Builder pagingBuilder = Paging.newBuilder() .setPageIndex(gitlabProjectList.getPageNumber()) .setPageSize(gitlabProjectList.getPageSize()); Integer gitlabProjectListTotal = gitlabProjectList.getTotal(); if (gitlabProjectListTotal != null) { pagingBuilder.setTotal(gitlabProjectListTotal); } return AlmIntegrations.SearchGitlabReposWsResponse.newBuilder() .addAllRepositories(gitlabRepositories) .setPaging(pagingBuilder.build()) .build(); } } private Map<String, ProjectKeyName> getSqProjectsKeyByGitlabProjectId(DbSession dbSession, AlmSettingDto almSettingDto, ProjectList gitlabProjectList) { Set<String> gitlabProjectIds = gitlabProjectList.getProjects().stream().map(Project::getId).map(String::valueOf) .collect(toSet()); Map<String, ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao() .selectByAlmSettingAndRepos(dbSession, almSettingDto, gitlabProjectIds) .stream().collect(Collectors.toMap(ProjectAlmSettingDto::getProjectUuid, Function.identity())); return dbClient.projectDao().selectByUuids(dbSession, projectAlmSettingDtos.keySet()) .stream() .collect(Collectors.toMap(projectDto -> projectAlmSettingDtos.get(projectDto.getUuid()).getAlmRepo(), p -> new ProjectKeyName(p.getKey(), p.getName()), resolveNameCollisionOperatorByNaturalOrder())); } private static BinaryOperator<ProjectKeyName> resolveNameCollisionOperatorByNaturalOrder() { return (a, b) -> b.key.compareTo(a.key) > 0 ? a : b; } private static GitlabRepository toGitlabRepository(Project project, Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId) { String name = project.getName(); String pathName = removeLastOccurrenceOfString(project.getNameWithNamespace(), " / " + name); String slug = project.getPath(); String pathSlug = removeLastOccurrenceOfString(project.getPathWithNamespace(), "/" + slug); GitlabRepository.Builder builder = GitlabRepository.newBuilder() .setId(project.getId()) .setName(name) .setPathName(pathName) .setSlug(slug) .setPathSlug(pathSlug) .setUrl(project.getWebUrl()); String projectIdAsString = String.valueOf(project.getId()); Optional.ofNullable(sqProjectsKeyByGitlabProjectId.get(projectIdAsString)) .ifPresent(p -> builder .setSqProjectKey(p.key) .setSqProjectName(p.name)); return builder.build(); } private static String removeLastOccurrenceOfString(String string, String stringToRemove) { StringBuilder resultString = new StringBuilder(string); int index = resultString.lastIndexOf(stringToRemove); if (index > -1) { resultString.delete(index, string.length() + index); } return resultString.toString(); } static class ProjectKeyName { String key; String name; ProjectKeyName(String key, String name) { this.key = key; this.name = name; } } }
8,422
41.115
166
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almintegration/ws/gitlab/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.almintegration.ws.gitlab; import javax.annotation.ParametersAreNonnullByDefault;
981
39.916667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/AlmSettingsSupport.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.almsettings.ws; import java.util.regex.Pattern; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.almsettings.MultipleAlmFeature; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmSettings; import static java.lang.String.format; import static org.sonar.api.web.UserRole.ADMIN; @ServerSide public class AlmSettingsSupport { private static final Pattern WORKSPACE_ID_PATTERN = Pattern.compile("^[a-z0-9\\-_]+$"); private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; private final MultipleAlmFeature multipleAlmFeature; public AlmSettingsSupport(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, MultipleAlmFeature multipleAlmFeature) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; this.multipleAlmFeature = multipleAlmFeature; } public void checkAlmSettingDoesNotAlreadyExist(DbSession dbSession, String almSetting) { dbClient.almSettingDao().selectByKey(dbSession, almSetting) .ifPresent(a -> { throw new IllegalArgumentException(format("An DevOps Platform setting with key '%s' already exists", a.getKey())); }); } public void checkAlmMultipleFeatureEnabled(ALM alm) { try (DbSession dbSession = dbClient.openSession(false)) { if (!multipleAlmFeature.isAvailable() && !dbClient.almSettingDao().selectByAlm(dbSession, alm).isEmpty()) { throw BadRequestException.create("A " + alm + " setting is already defined"); } } } public void checkBitbucketCloudWorkspaceIDFormat(String workspaceId) { if (!WORKSPACE_ID_PATTERN.matcher(workspaceId).matches()) { throw BadRequestException.create(String.format( "Workspace ID '%s' has an incorrect format. Should only contain lowercase letters, numbers, dashes, and underscores.", workspaceId )); } } public ProjectDto getProjectAsAdmin(DbSession dbSession, String projectKey) { return getProject(dbSession, projectKey, ADMIN); } public ProjectDto getProject(DbSession dbSession, String projectKey, String projectPermission) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); userSession.checkEntityPermission(projectPermission, project); return project; } public AlmSettingDto getAlmSetting(DbSession dbSession, String almSetting) { return dbClient.almSettingDao().selectByKey(dbSession, almSetting) .orElseThrow(() -> new NotFoundException(format("DevOps Platform setting with key '%s' cannot be found", almSetting))); } public static AlmSettings.Alm toAlmWs(ALM alm) { switch (alm) { case GITHUB: return AlmSettings.Alm.github; case BITBUCKET: return AlmSettings.Alm.bitbucket; case BITBUCKET_CLOUD: return AlmSettings.Alm.bitbucketcloud; case AZURE_DEVOPS: return AlmSettings.Alm.azure; case GITLAB: return AlmSettings.Alm.gitlab; default: throw new IllegalStateException(format("Unknown DevOps Platform '%s'", alm.name())); } } }
4,373
37.707965
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/AlmSettingsWs.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.almsettings.ws; import java.util.List; import org.sonar.api.server.ws.WebService; public class AlmSettingsWs implements WebService { private final List<AlmSettingsWsAction> actions; public AlmSettingsWs(List<AlmSettingsWsAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/alm_settings") .setDescription("Manage DevOps Platform Settings") .setSince("8.1"); actions.forEach(a -> a.define(controller)); controller.done(); } }
1,436
32.418605
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/AlmSettingsWsAction.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.almsettings.ws; import org.sonar.server.ws.WsAction; public interface AlmSettingsWsAction extends WsAction { // marker interface }
1,003
36.185185
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/AlmSettingsWsModule.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.almsettings.ws; import org.sonar.core.platform.Module; public class AlmSettingsWsModule extends Module { @Override protected void configureModule() { add( AlmSettingsWs.class, AlmSettingsSupport.class, DeleteAction.class, ListAction.class, ListDefinitionsAction.class, ValidateAction.class, CountBindingAction.class, GetBindingAction.class, //Azure alm settings, CreateAzureAction.class, UpdateAzureAction.class, //Github alm settings CreateGithubAction.class, UpdateGithubAction.class, //Gitlab alm settings CreateGitlabAction.class, UpdateGitlabAction.class, //Bitbucket alm settings CreateBitBucketAction.class, UpdateBitbucketAction.class, //BitbucketCloud alm settings CreateBitbucketCloudAction.class, UpdateBitbucketCloudAction.class ); } }
1,770
31.796296
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CountBindingAction.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.almsettings.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmSettings.CountBindingWsResponse; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class CountBindingAction implements AlmSettingsWsAction { private static final String PARAM_ALM_SETTING = "almSetting"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CountBindingAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("count_binding") .setDescription("Count number of project bound to an DevOps Platform setting.<br/>" + "Requires the 'Administer System' permission") .setSince("8.1") .setResponseExample(getClass().getResource("example-count_binding.json")) .setHandler(this); action .createParam(PARAM_ALM_SETTING) .setDescription("DevOps Platform setting key") .setRequired(true); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); CountBindingWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private CountBindingWsResponse doHandle(Request request) { String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSetting = almSettingsSupport.getAlmSetting(dbSession, almSettingKey); int projectsBound = dbClient.projectAlmSettingDao().countByAlmSetting(dbSession, almSetting); return CountBindingWsResponse.newBuilder() .setKey(almSetting.getKey()) .setProjects(projectsBound) .build(); } } }
3,111
37.419753
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CreateAzureAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.sonar.db.alm.setting.ALM.AZURE_DEVOPS; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_URL; public class CreateAzureAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CreateAzureAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("create_azure") .setDescription("Create Azure instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog(new Change("8.6", "Parameter 'URL' was added")) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Azure Devops instance setting"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(true) .setMaximumLength(2000) .setDescription("Azure Devops personal access token"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("Azure API URL"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String pat = request.mandatoryParam(PARAM_PERSONAL_ACCESS_TOKEN); String url = request.mandatoryParam(PARAM_URL); try (DbSession dbSession = dbClient.openSession(false)) { almSettingsSupport.checkAlmMultipleFeatureEnabled(AZURE_DEVOPS); almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, key); dbClient.almSettingDao().insert(dbSession, new AlmSettingDto() .setAlm(AZURE_DEVOPS) .setKey(key) .setPersonalAccessToken(pat) .setUrl(url)); dbSession.commit(); } } }
3,574
35.479592
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CreateBitBucketAction.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.almsettings.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.sonar.db.alm.setting.ALM.BITBUCKET; import static org.sonar.db.alm.setting.ALM.BITBUCKET_CLOUD; public class CreateBitBucketAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_URL = "url"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CreateBitBucketAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("create_bitbucket") .setDescription("Create Bitbucket instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Bitbucket instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("BitBucket server API URL"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(true) .setMaximumLength(2000) .setDescription("Bitbucket personal access token"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String url = request.mandatoryParam(PARAM_URL); String pat = request.mandatoryParam(PARAM_PERSONAL_ACCESS_TOKEN); try (DbSession dbSession = dbClient.openSession(false)) { // We do not treat Bitbucket Server and Bitbucket Cloud as different ALMs when it comes to limiting the // number of connections. almSettingsSupport.checkAlmMultipleFeatureEnabled(BITBUCKET); almSettingsSupport.checkAlmMultipleFeatureEnabled(BITBUCKET_CLOUD); almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, key); dbClient.almSettingDao().insert(dbSession, new AlmSettingDto() .setAlm(BITBUCKET) .setKey(key) .setUrl(url) .setPersonalAccessToken(pat)); dbSession.commit(); } } }
3,721
36.59596
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CreateBitbucketCloudAction.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.almsettings.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.sonar.db.alm.setting.ALM.BITBUCKET; import static org.sonar.db.alm.setting.ALM.BITBUCKET_CLOUD; public class CreateBitbucketCloudAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_CLIENT_ID = "clientId"; private static final String PARAM_CLIENT_SECRET = "clientSecret"; private static final String PARAM_WORKSPACE = "workspace"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CreateBitbucketCloudAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("create_bitbucketcloud") .setDescription("Configure a new instance of Bitbucket Cloud. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.7") .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Bitbucket Cloud setting"); action.createParam(PARAM_WORKSPACE) .setRequired(true) .setDescription("Bitbucket Cloud workspace ID"); action.createParam(PARAM_CLIENT_ID) .setRequired(true) .setMaximumLength(2000) .setDescription("Bitbucket Cloud Client ID"); action.createParam(PARAM_CLIENT_SECRET) .setRequired(true) .setMaximumLength(2000) .setDescription("Bitbucket Cloud Client Secret"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String clientId = request.mandatoryParam(PARAM_CLIENT_ID); String clientSecret = request.mandatoryParam(PARAM_CLIENT_SECRET); String workspace = request.mandatoryParam(PARAM_WORKSPACE); try (DbSession dbSession = dbClient.openSession(false)) { // We do not treat Bitbucket Server and Bitbucket Cloud as different ALMs when it comes to limiting the // number of connections. almSettingsSupport.checkAlmMultipleFeatureEnabled(BITBUCKET); almSettingsSupport.checkAlmMultipleFeatureEnabled(BITBUCKET_CLOUD); almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, key); almSettingsSupport.checkBitbucketCloudWorkspaceIDFormat(workspace); dbClient.almSettingDao().insert(dbSession, new AlmSettingDto() .setAlm(BITBUCKET_CLOUD) .setKey(key) .setAppId(workspace) .setClientId(clientId) .setClientSecret(clientSecret)); dbSession.commit(); } } }
4,119
38.238095
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CreateGithubAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.removeEnd; import static org.sonar.db.alm.setting.ALM.GITHUB; public class CreateGithubAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_URL = "url"; private static final String PARAM_APP_ID = "appId"; private static final String PARAM_CLIENT_ID = "clientId"; private static final String PARAM_CLIENT_SECRET = "clientSecret"; private static final String PARAM_PRIVATE_KEY = "privateKey"; private static final String PARAM_WEBHOOK_SECRET = "webhookSecret"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CreateGithubAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("create_github") .setDescription("Create GitHub instance Setting. <br/>" + "Requires the 'Administer System' permission") .setChangelog(new Change("9.7", String.format("Optional parameter '%s' was added", PARAM_WEBHOOK_SECRET))) .setPost(true) .setSince("8.1") .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the GitHub instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("GitHub API URL"); action.createParam(PARAM_APP_ID) .setRequired(true) .setMaximumLength(80) .setDescription("GitHub App ID"); action.createParam(PARAM_PRIVATE_KEY) .setRequired(true) .setMaximumLength(2500) .setDescription("GitHub App private key"); action.createParam(PARAM_CLIENT_ID) .setRequired(true) .setMaximumLength(80) .setDescription("GitHub App Client ID"); action.createParam(PARAM_CLIENT_SECRET) .setRequired(true) .setMaximumLength(160) .setDescription("GitHub App Client Secret"); action.createParam(PARAM_WEBHOOK_SECRET) .setRequired(false) .setMaximumLength(160) .setDescription("GitHub App Webhook Secret"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); tryDoHandle(request); response.noContent(); } private void tryDoHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { doHandle(request, dbSession); } } private void doHandle(Request request, DbSession dbSession) { almSettingsSupport.checkAlmMultipleFeatureEnabled(GITHUB); String key = request.mandatoryParam(PARAM_KEY); almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, key); dbClient.almSettingDao().insert(dbSession, new AlmSettingDto() .setAlm(GITHUB) .setKey(key) .setUrl(removeEnd(request.mandatoryParam(PARAM_URL), "/")) .setAppId(request.mandatoryParam(PARAM_APP_ID)) .setPrivateKey(request.mandatoryParam(PARAM_PRIVATE_KEY)) .setClientId(request.mandatoryParam(PARAM_CLIENT_ID)) .setClientSecret(request.mandatoryParam(PARAM_CLIENT_SECRET)) .setWebhookSecret(request.getParam(PARAM_WEBHOOK_SECRET).emptyAsNull().or(() -> null))); dbSession.commit(); } }
4,744
36.362205
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/CreateGitlabAction.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.almsettings.ws; import org.apache.commons.lang.StringUtils; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.sonar.db.alm.setting.ALM.GITLAB; public class CreateGitlabAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_URL = "url"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public CreateGitlabAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("create_gitlab") .setDescription("Create GitLab instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog(new Change("8.2", "Parameter 'URL' was added")) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the GitLab instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("GitLab API URL"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(true) .setMaximumLength(2000) .setDescription("GitLab personal access token"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String url = StringUtils.trim(request.mandatoryParam(PARAM_URL)); String pat = request.mandatoryParam(PARAM_PERSONAL_ACCESS_TOKEN); try (DbSession dbSession = dbClient.openSession(false)) { almSettingsSupport.checkAlmMultipleFeatureEnabled(GITLAB); almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, key); dbClient.almSettingDao().insert(dbSession, new AlmSettingDto() .setAlm(GITLAB) .setUrl(url) .setKey(key) .setPersonalAccessToken(pat)); dbSession.commit(); } } }
3,577
35.510204
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/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.almsettings.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; public class DeleteAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public DeleteAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction("delete") .setDescription("Delete an DevOps Platform Setting.<br/>" + "Requires the 'Administer System' permission") .setSince("8.1") .setPost(true) .setHandler(this); action .createParam(PARAM_KEY) .setDescription("DevOps Platform Setting key") .setRequired(true); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); dbClient.projectAlmSettingDao().deleteByAlmSetting(dbSession, almSettingDto); dbClient.almPatDao().deleteByAlmSetting(dbSession, almSettingDto); dbClient.almSettingDao().delete(dbSession, almSettingDto); dbSession.commit(); } } }
2,761
34.410256
106
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/GetBindingAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmSettings.GetBindingWsResponse; import static java.lang.String.format; import static java.util.Optional.ofNullable; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.almsettings.ws.AlmSettingsSupport.toAlmWs; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class GetBindingAction implements AlmSettingsWsAction { private static final String PARAM_PROJECT = "project"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public GetBindingAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("get_binding") .setDescription("Get DevOps Platform binding of a given project.<br/>" + "Requires the 'Browse' permission on the project") .setSince("8.1") .setResponseExample(getClass().getResource("example-get_binding.json")) .setChangelog( new Change("8.6", "Azure binding now contains the project and repository names"), new Change("8.7", "Azure binding now contains a monorepo flag for monorepo feature in Enterprise Edition and above"), new Change("10.1", "Permission needed changed from 'Administer' to 'Browse'")) .setHandler(this); action .createParam(PARAM_PROJECT) .setDescription("Project key") .setRequired(true); } @Override public void handle(Request request, Response response) { GetBindingWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private GetBindingWsResponse doHandle(Request request) { String projectKey = request.mandatoryParam(PARAM_PROJECT); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); userSession.checkEntityPermission(USER, project); ProjectAlmSettingDto projectAlmSetting = dbClient.projectAlmSettingDao().selectByProject(dbSession, project) .orElseThrow(() -> new NotFoundException(format("Project '%s' is not bound to any DevOps Platform", project.getKey()))); AlmSettingDto almSetting = dbClient.almSettingDao().selectByUuid(dbSession, projectAlmSetting.getAlmSettingUuid()) .orElseThrow(() -> new IllegalStateException(format("DevOps Platform setting with uuid '%s' cannot be found", projectAlmSetting.getAlmSettingUuid()))); GetBindingWsResponse.Builder builder = GetBindingWsResponse.newBuilder() .setAlm(toAlmWs(almSetting.getAlm())) .setKey(almSetting.getKey()); ofNullable(projectAlmSetting.getAlmRepo()).ifPresent(builder::setRepository); ofNullable(almSetting.getUrl()).ifPresent(builder::setUrl); ofNullable(projectAlmSetting.getAlmSlug()).ifPresent(builder::setSlug); ofNullable(projectAlmSetting.getSummaryCommentEnabled()).ifPresent(builder::setSummaryCommentEnabled); ofNullable(projectAlmSetting.getMonorepo()).ifPresent(builder::setMonorepo); return builder.build(); } } }
4,685
44.495146
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/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.almsettings.ws; import java.util.Comparator; 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.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmSettings.AlmSetting; import org.sonarqube.ws.AlmSettings.ListWsResponse; import static java.util.Optional.ofNullable; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ListAction implements AlmSettingsWsAction { private static final String PARAM_PROJECT = "project"; private static final String BITBUCKETCLOUD_ROOT_URL = "https://bitbucket.org/"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public ListAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("list") .setDescription("List DevOps Platform setting available for a given project, sorted by DevOps Platform key<br/>" + "Requires the 'Administer project' permission if the '" + PARAM_PROJECT + "' parameter is provided, requires the 'Create Projects' permission otherwise.") .setSince("8.1") .setResponseExample(getClass().getResource("example-list.json")) .setHandler(this); action .createParam(PARAM_PROJECT) .setDescription("Project key") .setRequired(false); action.setChangelog( new Change("8.3", "Permission needed changed to 'Administer project' or 'Create Projects'"), new Change("8.2", "Permission needed changed from 'Administer project' to 'Create Projects'"), new Change("8.6", "Field 'URL' added for Azure definitions")); } @Override public void handle(Request request, Response response) { ListWsResponse wsResponse = doHandle(request); writeProtobuf(wsResponse, request, response); } private ListWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { Request.StringParam projectKey = request.getParam(PARAM_PROJECT); if (projectKey.isPresent()) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey.getValue()); userSession.checkEntityPermission(ADMIN, project); } else { userSession.checkPermission(PROVISION_PROJECTS); } List<AlmSettingDto> settings = dbClient.almSettingDao().selectAll(dbSession); List<AlmSetting> wsAlmSettings = settings .stream() .sorted(Comparator.comparing(AlmSettingDto::getKey)) .map(almSetting -> { AlmSetting.Builder almSettingBuilder = AlmSetting.newBuilder() .setKey(almSetting.getKey()) .setAlm(AlmSettingsSupport.toAlmWs(almSetting.getAlm())); if (almSetting.getAlm() == ALM.BITBUCKET_CLOUD) { almSettingBuilder.setUrl(BITBUCKETCLOUD_ROOT_URL + almSetting.getAppId() + "/"); } else { ofNullable(almSetting.getUrl()).ifPresent(almSettingBuilder::setUrl); } return almSettingBuilder.build(); }) .toList(); return ListWsResponse.newBuilder() .addAllAlmSettings(wsAlmSettings).build(); } } }
4,694
39.128205
162
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/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.almsettings.ws; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; 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.alm.setting.ALM; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import org.sonarqube.ws.AlmSettings.AlmSettingBitbucketCloud; import org.sonarqube.ws.AlmSettings.AlmSettingGithub; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.AlmSettings.AlmSettingAzure; import static org.sonarqube.ws.AlmSettings.AlmSettingBitbucket; import static org.sonarqube.ws.AlmSettings.AlmSettingGitlab; import static org.sonarqube.ws.AlmSettings.ListDefinitionsWsResponse; public class ListDefinitionsAction implements AlmSettingsWsAction { private final DbClient dbClient; private final UserSession userSession; public ListDefinitionsAction(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } @Override public void define(WebService.NewController context) { context.createAction("list_definitions") .setDescription("List DevOps Platform Settings, sorted by created date.<br/>" + "Requires the 'Administer System' permission") .setSince("8.1") .setResponseExample(getClass().getResource("list_definitions-example.json")) .setChangelog(new Change("8.2", "Field 'URL' added for GitLab definitions"), new Change("8.6", "Field 'URL' added for Azure definitions"), new Change("8.7", "Fields 'personalAccessToken', 'privateKey', and 'clientSecret' are no longer returned")) .setHandler(this) .setResponseExample(getClass().getResource("example-list_definitions.json")); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); ListDefinitionsWsResponse wsResponse = doHandle(); writeProtobuf(wsResponse, request, response); } private ListDefinitionsWsResponse doHandle() { try (DbSession dbSession = dbClient.openSession(false)) { List<AlmSettingDto> settings = dbClient.almSettingDao().selectAll(dbSession); Map<ALM, List<AlmSettingDto>> settingsByAlm = settings.stream().collect(Collectors.groupingBy(AlmSettingDto::getAlm)); List<AlmSettingGithub> githubSettings = settingsByAlm.getOrDefault(ALM.GITHUB, emptyList()) .stream() .sorted(Comparator.comparing(AlmSettingDto::getCreatedAt)) .map(ListDefinitionsAction::toGitHub).toList(); List<AlmSettingAzure> azureSettings = settingsByAlm.getOrDefault(ALM.AZURE_DEVOPS, emptyList()) .stream() .sorted(Comparator.comparing(AlmSettingDto::getCreatedAt)) .map(ListDefinitionsAction::toAzure).toList(); List<AlmSettingBitbucket> bitbucketSettings = settingsByAlm.getOrDefault(ALM.BITBUCKET, emptyList()) .stream() .sorted(Comparator.comparing(AlmSettingDto::getCreatedAt)) .map(ListDefinitionsAction::toBitbucket).toList(); List<AlmSettingBitbucketCloud> bitbucketCloudSettings = settingsByAlm.getOrDefault(ALM.BITBUCKET_CLOUD, emptyList()) .stream() .sorted(Comparator.comparing(AlmSettingDto::getCreatedAt)) .map(ListDefinitionsAction::toBitbucketCloud).toList(); List<AlmSettingGitlab> gitlabSettings = settingsByAlm.getOrDefault(ALM.GITLAB, emptyList()) .stream() .sorted(Comparator.comparing(AlmSettingDto::getCreatedAt)) .map(ListDefinitionsAction::toGitlab).toList(); return ListDefinitionsWsResponse.newBuilder() .addAllGithub(githubSettings) .addAllAzure(azureSettings) .addAllBitbucket(bitbucketSettings) .addAllBitbucketcloud(bitbucketCloudSettings) .addAllGitlab(gitlabSettings) .build(); } } private static AlmSettingGithub toGitHub(AlmSettingDto settingDto) { AlmSettingGithub.Builder builder = AlmSettingGithub .newBuilder() .setKey(settingDto.getKey()) .setUrl(requireNonNull(settingDto.getUrl(), "URL cannot be null for GitHub setting")) .setAppId(requireNonNull(settingDto.getAppId(), "App ID cannot be null for GitHub setting")); // Don't fail if clientId is not set for migration cases Optional.ofNullable(settingDto.getClientId()).ifPresent(builder::setClientId); return builder.build(); } private static AlmSettingAzure toAzure(AlmSettingDto settingDto) { AlmSettingAzure.Builder builder = AlmSettingAzure .newBuilder() .setKey(settingDto.getKey()); if (settingDto.getUrl() != null) { builder.setUrl(settingDto.getUrl()); } return builder.build(); } private static AlmSettingGitlab toGitlab(AlmSettingDto settingDto) { AlmSettingGitlab.Builder builder = AlmSettingGitlab.newBuilder() .setKey(settingDto.getKey()); if (settingDto.getUrl() != null) { builder.setUrl(settingDto.getUrl()); } return builder.build(); } private static AlmSettingBitbucket toBitbucket(AlmSettingDto settingDto) { return AlmSettingBitbucket .newBuilder() .setKey(settingDto.getKey()) .setUrl(requireNonNull(settingDto.getUrl(), "URL cannot be null for Bitbucket setting")) .build(); } private static AlmSettingBitbucketCloud toBitbucketCloud(AlmSettingDto settingDto) { AlmSettingBitbucketCloud.Builder builder = AlmSettingBitbucketCloud .newBuilder() .setKey(settingDto.getKey()) .setWorkspace(requireNonNull(settingDto.getAppId())) .setClientId(requireNonNull(settingDto.getClientId(), "Client ID cannot be null for Bitbucket Cloud setting")); return builder.build(); } }
6,870
41.41358
124
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/UpdateAzureAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_URL; public class UpdateAzureAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_NEW_KEY = "newKey"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public UpdateAzureAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("update_azure") .setDescription("Update Azure instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog(new Change("8.6", "Parameter 'URL' was added"), new Change("8.7", String.format("Parameter '%s' is no longer required", PARAM_PERSONAL_ACCESS_TOKEN))) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Azure instance setting"); action.createParam(PARAM_NEW_KEY) .setRequired(false) .setMaximumLength(200) .setDescription("Optional new value for an unique key of the Azure Devops instance setting"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(false) .setMaximumLength(2000) .setDescription("Azure Devops personal access token"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("Azure API URL"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String newKey = request.param(PARAM_NEW_KEY); String pat = request.param(PARAM_PERSONAL_ACCESS_TOKEN); String url = request.mandatoryParam(PARAM_URL); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); if (isNotBlank(newKey) && !newKey.equals(key)) { almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, newKey); } if (isNotBlank(pat)) { almSettingDto.setPersonalAccessToken(pat); } dbClient.almSettingDao().update(dbSession, almSettingDto .setKey(isNotBlank(newKey) ? newKey : key) .setUrl(url), pat != null); dbSession.commit(); } } }
4,142
36.324324
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/UpdateBitbucketAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isNotBlank; public class UpdateBitbucketAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_NEW_KEY = "newKey"; private static final String PARAM_URL = "url"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public UpdateBitbucketAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("update_bitbucket") .setDescription("Update Bitbucket instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog(new Change("8.7", String.format("Parameter '%s' is no longer required", PARAM_PERSONAL_ACCESS_TOKEN))) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Bitbucket instance setting"); action.createParam(PARAM_NEW_KEY) .setRequired(false) .setMaximumLength(200) .setDescription("Optional new value for an unique key of the Bitbucket instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("Bitbucket API URL"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(false) .setMaximumLength(2000) .setDescription("Bitbucket personal access token"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String newKey = request.param(PARAM_NEW_KEY); String url = request.mandatoryParam(PARAM_URL); String pat = request.param(PARAM_PERSONAL_ACCESS_TOKEN); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); if (isNotBlank(newKey) && !newKey.equals(key)) { almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, newKey); } if (isNotBlank(pat)) { almSettingDto.setPersonalAccessToken(pat); } dbClient.almSettingDao().update(dbSession, almSettingDto .setKey(isNotBlank(newKey) ? newKey : key) .setUrl(url), pat != null); dbSession.commit(); } } }
4,071
36.018182
122
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/UpdateBitbucketCloudAction.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.almsettings.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isNotBlank; public class UpdateBitbucketCloudAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_NEW_KEY = "newKey"; private static final String PARAM_CLIENT_ID = "clientId"; private static final String PARAM_CLIENT_SECRET = "clientSecret"; private static final String PARAM_WORKSPACE = "workspace"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public UpdateBitbucketCloudAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("update_bitbucketcloud") .setDescription("Update Bitbucket Cloud Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.7") .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the Bitbucket Cloud setting"); action.createParam(PARAM_NEW_KEY) .setRequired(false) .setMaximumLength(200) .setDescription("Optional new value for an unique key of the Bitbucket Cloud setting"); action.createParam(PARAM_WORKSPACE) .setRequired(true) .setMaximumLength(80) .setDescription("Bitbucket Cloud workspace ID"); action.createParam(PARAM_CLIENT_ID) .setRequired(true) .setMaximumLength(80) .setDescription("Bitbucket Cloud Client ID"); action.createParam(PARAM_CLIENT_SECRET) .setRequired(false) .setMaximumLength(160) .setDescription("Optional new value for the Bitbucket Cloud client secret"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String newKey = request.param(PARAM_NEW_KEY); String workspace = request.mandatoryParam(PARAM_WORKSPACE); String clientId = request.mandatoryParam(PARAM_CLIENT_ID); String clientSecret = request.param(PARAM_CLIENT_SECRET); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); if (isNotBlank(newKey) && !newKey.equals(key)) { almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, newKey); } if (isNotBlank(clientSecret)) { almSettingDto.setClientSecret(clientSecret); } almSettingsSupport.checkBitbucketCloudWorkspaceIDFormat(workspace); dbClient.almSettingDao().update(dbSession, almSettingDto .setKey(isNotBlank(newKey) ? newKey : key) .setClientId(clientId) .setAppId(workspace), clientSecret != null); dbSession.commit(); } } }
4,364
36.307692
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/UpdateGithubAction.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.almsettings.ws; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.apache.commons.lang.StringUtils.removeEnd; public class UpdateGithubAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_NEW_KEY = "newKey"; private static final String PARAM_URL = "url"; private static final String PARAM_APP_ID = "appId"; private static final String PARAM_CLIENT_ID = "clientId"; private static final String PARAM_CLIENT_SECRET = "clientSecret"; private static final String PARAM_PRIVATE_KEY = "privateKey"; private static final String PARAM_WEBHOOK_SECRET = "webhookSecret"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public UpdateGithubAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("update_github") .setDescription("Update GitHub instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog( new Change("9.7", String.format("Optional parameter '%s' was added", PARAM_WEBHOOK_SECRET)), new Change("8.7", String.format("Parameter '%s' is no longer required", PARAM_PRIVATE_KEY)), new Change("8.7", String.format("Parameter '%s' is no longer required", PARAM_CLIENT_SECRET))) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the GitHub instance setting"); action.createParam(PARAM_NEW_KEY) .setRequired(false) .setMaximumLength(200) .setDescription("Optional new value for an unique key of the GitHub instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("GitHub API URL"); action.createParam(PARAM_APP_ID) .setRequired(true) .setMaximumLength(80) .setDescription("GitHub API ID"); action.createParam(PARAM_PRIVATE_KEY) .setRequired(false) .setMaximumLength(2500) .setDescription("GitHub App private key"); action.createParam(PARAM_CLIENT_ID) .setRequired(true) .setMaximumLength(80) .setDescription("GitHub App Client ID"); action.createParam(PARAM_CLIENT_SECRET) .setRequired(false) .setMaximumLength(160) .setDescription("GitHub App Client Secret"); action.createParam(PARAM_WEBHOOK_SECRET) .setRequired(false) .setMaximumLength(160) .setDescription("GitHub App Webhook Secret"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); tryDoHandle(request); response.noContent(); } private void tryDoHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { doHandle(request, dbSession); } } private void doHandle(Request request, DbSession dbSession) { String key = request.mandatoryParam(PARAM_KEY); String newKey = request.param(PARAM_NEW_KEY); if (isNotBlank(newKey) && !newKey.equals(key)) { almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, newKey); } AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); String privateKey = request.param(PARAM_PRIVATE_KEY); if (isNotBlank(privateKey)) { almSettingDto.setPrivateKey(privateKey); } String clientSecret = request.param(PARAM_CLIENT_SECRET); if (isNotBlank(clientSecret)) { almSettingDto.setClientSecret(clientSecret); } boolean hasWebhookSecretParam = request.hasParam(PARAM_WEBHOOK_SECRET); if (hasWebhookSecretParam) { String webhookSecret = request.getParam(PARAM_WEBHOOK_SECRET).getValue(); almSettingDto.setWebhookSecret(isBlank(webhookSecret) ? null : webhookSecret); } almSettingDto .setKey(isNotBlank(newKey) ? newKey : key) .setUrl(removeEnd(request.mandatoryParam(PARAM_URL), "/")) .setAppId(request.mandatoryParam(PARAM_APP_ID)) .setClientId(request.mandatoryParam(PARAM_CLIENT_ID)); boolean isAnySecretUpdated = clientSecret != null || privateKey != null || hasWebhookSecretParam; dbClient.almSettingDao().update(dbSession, almSettingDto, isAnySecretUpdated); dbSession.commit(); } }
5,922
37.712418
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/UpdateGitlabAction.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.almsettings.ws; import org.apache.commons.lang.StringUtils; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; import static org.apache.commons.lang.StringUtils.isNotBlank; public class UpdateGitlabAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_NEW_KEY = "newKey"; private static final String PARAM_URL = "url"; private static final String PARAM_PERSONAL_ACCESS_TOKEN = "personalAccessToken"; private final DbClient dbClient; private UserSession userSession; private final AlmSettingsSupport almSettingsSupport; public UpdateGitlabAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("update_gitlab") .setDescription("Update GitLab instance Setting. <br/>" + "Requires the 'Administer System' permission") .setPost(true) .setSince("8.1") .setChangelog(new Change("8.2", "Parameter 'URL' was added"), new Change("8.7", String.format("Parameter '%s' is no longer required", PARAM_PERSONAL_ACCESS_TOKEN))) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the GitLab instance setting"); action.createParam(PARAM_NEW_KEY) .setRequired(false) .setMaximumLength(200) .setDescription("Optional new value for an unique key of the GitLab instance setting"); action.createParam(PARAM_URL) .setRequired(true) .setMaximumLength(2000) .setDescription("GitLab API URL"); action.createParam(PARAM_PERSONAL_ACCESS_TOKEN) .setRequired(false) .setMaximumLength(2000) .setDescription("GitLab personal access token"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); String newKey = request.param(PARAM_NEW_KEY); String url = StringUtils.trim(request.mandatoryParam(PARAM_URL)); String pat = request.param(PARAM_PERSONAL_ACCESS_TOKEN); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); if (isNotBlank(newKey) && !newKey.equals(key)) { almSettingsSupport.checkAlmSettingDoesNotAlreadyExist(dbSession, newKey); } if (isNotBlank(pat)) { almSettingDto.setPersonalAccessToken(pat); } dbClient.almSettingDao().update(dbSession, almSettingDto .setKey(isNotBlank(newKey) ? newKey : key) .setUrl(url), pat != null); dbSession.commit(); } } }
4,148
36.044643
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/ValidateAction.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.almsettings.ws; import org.sonar.alm.client.azure.AzureDevOpsValidator; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudValidator; import org.sonar.alm.client.bitbucketserver.BitbucketServerSettingsValidator; import org.sonar.alm.client.github.GithubGlobalSettingsValidator; import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator; 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.alm.setting.AlmSettingDto; import org.sonar.server.user.UserSession; public class ValidateAction implements AlmSettingsWsAction { private static final String PARAM_KEY = "key"; private final DbClient dbClient; private final UserSession userSession; private final AlmSettingsSupport almSettingsSupport; private final GitlabGlobalSettingsValidator gitlabSettingsValidator; private final GithubGlobalSettingsValidator githubGlobalSettingsValidator; private final BitbucketServerSettingsValidator bitbucketServerSettingsValidator; private final BitbucketCloudValidator bitbucketCloudValidator; private final AzureDevOpsValidator azureDevOpsValidator; public ValidateAction(DbClient dbClient, UserSession userSession, AlmSettingsSupport almSettingsSupport, GithubGlobalSettingsValidator githubGlobalSettingsValidator, GitlabGlobalSettingsValidator gitlabSettingsValidator, BitbucketServerSettingsValidator bitbucketServerSettingsValidator, BitbucketCloudValidator bitbucketCloudValidator, AzureDevOpsValidator azureDevOpsValidator) { this.dbClient = dbClient; this.userSession = userSession; this.almSettingsSupport = almSettingsSupport; this.githubGlobalSettingsValidator = githubGlobalSettingsValidator; this.gitlabSettingsValidator = gitlabSettingsValidator; this.bitbucketServerSettingsValidator = bitbucketServerSettingsValidator; this.bitbucketCloudValidator = bitbucketCloudValidator; this.azureDevOpsValidator = azureDevOpsValidator; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("validate") .setDescription("Validate an DevOps Platform Setting by checking connectivity and permissions<br/>" + "Requires the 'Administer System' permission") .setSince("8.6") .setResponseExample(getClass().getResource("example-validate.json")) .setHandler(this); action.createParam(PARAM_KEY) .setRequired(true) .setMaximumLength(200) .setDescription("Unique key of the DevOps Platform settings"); } @Override public void handle(Request request, Response response) { userSession.checkIsSystemAdministrator(); doHandle(request); response.noContent(); } private void doHandle(Request request) { String key = request.mandatoryParam(PARAM_KEY); try (DbSession dbSession = dbClient.openSession(false)) { AlmSettingDto almSettingDto = almSettingsSupport.getAlmSetting(dbSession, key); switch (almSettingDto.getAlm()) { case GITLAB: gitlabSettingsValidator.validate(almSettingDto); break; case GITHUB: githubGlobalSettingsValidator.validate(almSettingDto); break; case BITBUCKET: bitbucketServerSettingsValidator.validate(almSettingDto); break; case BITBUCKET_CLOUD: bitbucketCloudValidator.validate(almSettingDto); break; case AZURE_DEVOPS: azureDevOpsValidator.validate(almSettingDto); break; } } } }
4,535
39.141593
107
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/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.almsettings.ws; import javax.annotation.ParametersAreNonnullByDefault;
972
37.92
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/AuthenticationWs.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.authentication.ws; import java.util.List; import org.sonar.api.server.ws.WebService; public class AuthenticationWs implements WebService { public static final String AUTHENTICATION_CONTROLLER = "api/authentication"; private final List<AuthenticationWsAction> actions; public AuthenticationWs(List<AuthenticationWsAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(AUTHENTICATION_CONTROLLER); controller.setDescription("Handle authentication."); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,523
35.285714
83
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/AuthenticationWsAction.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.authentication.ws; import org.sonar.api.server.ws.WebService; @FunctionalInterface public interface AuthenticationWsAction { // marker interface void define(WebService.NewController controller); }
1,072
34.766667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/AuthenticationWsModule.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.authentication.ws; import org.sonar.core.platform.Module; public class AuthenticationWsModule extends Module { @Override protected void configureModule() { add( AuthenticationWs.class, LoginAction.class, LogoutAction.class, ValidateAction.class ); } }
1,160
32.171429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/LoginAction.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.authentication.ws; 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.db.user.UserDto; import org.sonar.server.authentication.Credentials; import org.sonar.server.authentication.CredentialsAuthentication; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.user.UserSessionFactory; import org.sonar.server.ws.ServletFilterHandler; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.sonar.server.authentication.event.AuthenticationEvent.Method; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; import static org.sonar.server.authentication.ws.AuthenticationWs.AUTHENTICATION_CONTROLLER; import static org.sonarqube.ws.client.WsRequest.Method.POST; public class LoginAction extends HttpFilter implements AuthenticationWsAction { private static final String LOGIN_ACTION = "login"; public static final String LOGIN_URL = "/" + AUTHENTICATION_CONTROLLER + "/" + LOGIN_ACTION; private final CredentialsAuthentication credentialsAuthentication; private final JwtHttpHandler jwtHttpHandler; private final ThreadLocalUserSession threadLocalUserSession; private final AuthenticationEvent authenticationEvent; private final UserSessionFactory userSessionFactory; public LoginAction(CredentialsAuthentication credentialsAuthentication, JwtHttpHandler jwtHttpHandler, ThreadLocalUserSession threadLocalUserSession, AuthenticationEvent authenticationEvent, UserSessionFactory userSessionFactory) { this.credentialsAuthentication = credentialsAuthentication; this.jwtHttpHandler = jwtHttpHandler; this.threadLocalUserSession = threadLocalUserSession; this.authenticationEvent = authenticationEvent; this.userSessionFactory = userSessionFactory; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(LOGIN_ACTION) .setDescription("Authenticate a user.") .setSince("6.0") .setPost(true) .setHandler(ServletFilterHandler.INSTANCE); action.createParam("login") .setDescription("Login of the user") .setRequired(true); action.createParam("password") .setDescription("Password of the user") .setRequired(true); } @Override public UrlPattern doGetPattern() { return UrlPattern.create(LOGIN_URL); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { if (!request.getMethod().equals(POST.name())) { response.setStatus(HTTP_BAD_REQUEST); return; } try { UserDto userDto = authenticate(request); jwtHttpHandler.generateToken(userDto, request, response); threadLocalUserSession.set(userSessionFactory.create(userDto)); } catch (AuthenticationException e) { authenticationEvent.loginFailure(request, e); response.setStatus(HTTP_UNAUTHORIZED); } catch (UnauthorizedException e) { response.setStatus(e.httpCode()); } } private UserDto authenticate(HttpRequest request) { String login = request.getParameter("login"); String password = request.getParameter("password"); if (isEmpty(login) || isEmpty(password)) { throw AuthenticationException.newBuilder() .setSource(Source.local(Method.FORM)) .setLogin(login) .setMessage("Empty login and/or password") .build(); } return credentialsAuthentication.authenticate(new Credentials(login, password), request, Method.FORM); } @Override public void init() { // Nothing to do } @Override public void destroy() { // Nothing to do } }
5,101
38.550388
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/LogoutAction.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.authentication.ws; import java.util.Optional; 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.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.ws.ServletFilterHandler; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static org.sonar.server.authentication.ws.AuthenticationWs.AUTHENTICATION_CONTROLLER; import static org.sonarqube.ws.client.WsRequest.Method.POST; public class LogoutAction extends HttpFilter implements AuthenticationWsAction { private static final String LOGOUT_ACTION = "logout"; public static final String LOGOUT_URL = "/" + AUTHENTICATION_CONTROLLER + "/" + LOGOUT_ACTION; private final JwtHttpHandler jwtHttpHandler; private final AuthenticationEvent authenticationEvent; public LogoutAction(JwtHttpHandler jwtHttpHandler, AuthenticationEvent authenticationEvent) { this.jwtHttpHandler = jwtHttpHandler; this.authenticationEvent = authenticationEvent; } @Override public void define(WebService.NewController controller) { controller.createAction(LOGOUT_ACTION) .setDescription("Logout a user.") .setSince("6.3") .setPost(true) .setHandler(ServletFilterHandler.INSTANCE); } @Override public UrlPattern doGetPattern() { return UrlPattern.create(LOGOUT_URL); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { if (!request.getMethod().equals(POST.name())) { response.setStatus(HTTP_BAD_REQUEST); return; } logout(request, response); } private void logout(HttpRequest request, HttpResponse response) { generateAuthenticationEvent(request, response); jwtHttpHandler.removeToken(request, response); } /** * The generation of the authentication event should not prevent the removal of JWT cookie, that's why it's done in a separate method */ private void generateAuthenticationEvent(HttpRequest request, HttpResponse response) { try { Optional<JwtHttpHandler.Token> token = jwtHttpHandler.getToken(request, response); String userLogin = token.map(value -> value.getUserDto().getLogin()).orElse(null); authenticationEvent.logoutSuccess(request, userLogin); } catch (AuthenticationException e) { authenticationEvent.logoutFailure(request, e.getMessage()); } } @Override public void init() { // Nothing to do } @Override public void destroy() { // Nothing to do } }
3,663
34.921569
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/ws/ValidateAction.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.authentication.ws; import com.google.common.io.Resources; import java.io.IOException; import java.util.Optional; import org.sonar.api.config.Configuration; 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.utils.text.JsonWriter; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.BasicAuthentication; import org.sonar.server.authentication.JwtHttpHandler; import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.ws.ServletFilterHandler; import org.sonarqube.ws.MediaTypes; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY; import static org.sonar.server.authentication.ws.AuthenticationWs.AUTHENTICATION_CONTROLLER; public class ValidateAction extends HttpFilter implements AuthenticationWsAction { private static final String VALIDATE_ACTION = "validate"; public static final String VALIDATE_URL = "/" + AUTHENTICATION_CONTROLLER + "/" + VALIDATE_ACTION; private final Configuration config; private final JwtHttpHandler jwtHttpHandler; private final BasicAuthentication basicAuthentication; public ValidateAction(Configuration config, BasicAuthentication basicAuthentication, JwtHttpHandler jwtHttpHandler) { this.config = config; this.basicAuthentication = basicAuthentication; this.jwtHttpHandler = jwtHttpHandler; } @Override public void define(WebService.NewController controller) { controller.createAction(VALIDATE_ACTION) .setDescription("Check credentials.") .setSince("3.3") .setHandler(ServletFilterHandler.INSTANCE) .setResponseExample(Resources.getResource(this.getClass(), "example-validate.json")); } @Override public UrlPattern doGetPattern() { return UrlPattern.create(VALIDATE_URL); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) throws IOException { boolean isAuthenticated = authenticate(request, response); response.setContentType(MediaTypes.JSON); try (JsonWriter jsonWriter = JsonWriter.of(response.getWriter())) { jsonWriter.beginObject(); jsonWriter.prop("valid", isAuthenticated); jsonWriter.endObject(); } } private boolean authenticate(HttpRequest request, HttpResponse response) { try { Optional<UserDto> user = jwtHttpHandler.validateToken(request, response); if (user.isPresent()) { return true; } user = basicAuthentication.authenticate(request); if (user.isPresent()) { return true; } return !config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE); } catch (AuthenticationException e) { return false; } } @Override public void init() { // Nothing to do } @Override public void destroy() { // Nothing to do } }
4,027
35.288288
119
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/authentication/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.authentication.ws; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ETagUtils.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.badge.ws; import static java.nio.charset.StandardCharsets.UTF_8; public class ETagUtils { // Format for Expires Header static final String RFC1123_DATE = "EEE, dd MMM yyyy HH:mm:ss zzz"; private static final long FNV1_INIT = 0xcbf29ce484222325L; private static final long FNV1_PRIME = 0x100000001b3L; private ETagUtils() { // Utility class no instantiation allowed } /** * hash method of a String independant of the JVM * FNV-1a hash method @see <a href="https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash"></a> */ private static long hash(byte[] input) { long hash = FNV1_INIT; for (byte b : input) { hash ^= b & 0xff; hash *= FNV1_PRIME; } return hash; } /** * Calculate the ETag of the badge * * @see <a href="https://en.wikipedia.org/wiki/HTTP_ETag"></a> * <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11"></a> */ static String getETag(String output) { return "W/" + hash(output.getBytes(UTF_8)); } }
1,923
32.172414
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/MeasureAction.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.badge.ws; import com.google.common.collect.ImmutableMap; import com.google.common.io.Resources; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumMap; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.function.Function; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.server.badge.ws.SvgGenerator.Color; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.measure.Rating; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.write; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS_KEY; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY; import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY; import static org.sonar.api.measures.Metric.Level; import static org.sonar.api.measures.Metric.ValueType; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.badge.ws.ETagUtils.RFC1123_DATE; import static org.sonar.server.badge.ws.ETagUtils.getETag; import static org.sonar.server.badge.ws.SvgFormatter.formatDuration; import static org.sonar.server.badge.ws.SvgFormatter.formatNumeric; import static org.sonar.server.badge.ws.SvgFormatter.formatPercent; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; import static org.sonar.server.measure.Rating.C; import static org.sonar.server.measure.Rating.D; import static org.sonar.server.measure.Rating.E; import static org.sonar.server.measure.Rating.valueOf; import static org.sonarqube.ws.MediaTypes.SVG; public class MeasureAction implements ProjectBadgesWsAction { private static final String PARAM_METRIC = "metric"; private static final Map<String, String> METRIC_NAME_BY_KEY = ImmutableMap.<String, String>builder() .put(BUGS_KEY, "bugs") .put(CODE_SMELLS_KEY, "code smells") .put(COVERAGE_KEY, "coverage") .put(DUPLICATED_LINES_DENSITY_KEY, "duplicated lines") .put(NCLOC_KEY, "lines of code") .put(SQALE_RATING_KEY, "maintainability") .put(ALERT_STATUS_KEY, "quality gate") .put(RELIABILITY_RATING_KEY, "reliability") .put(SECURITY_HOTSPOTS_KEY, "security hotspots") .put(SECURITY_RATING_KEY, "security") .put(TECHNICAL_DEBT_KEY, "technical debt") .put(VULNERABILITIES_KEY, "vulnerabilities") .build(); private static final Map<Level, String> QUALITY_GATE_MESSAGE_BY_STATUS = new EnumMap<>(Map.of( OK, "passed", WARN, "warning", ERROR, "failed")); private static final Map<Level, Color> COLOR_BY_QUALITY_GATE_STATUS = new EnumMap<>(Map.of( OK, Color.QUALITY_GATE_OK, WARN, Color.QUALITY_GATE_WARN, ERROR, Color.QUALITY_GATE_ERROR)); private static final Map<Rating, Color> COLOR_BY_RATING = new EnumMap<>(Map.of( A, Color.RATING_A, B, Color.RATING_B, C, Color.RATING_C, D, Color.RATING_D, E, Color.RATING_E)); private final DbClient dbClient; private final ProjectBadgesSupport support; private final SvgGenerator svgGenerator; public MeasureAction(DbClient dbClient, ProjectBadgesSupport support, SvgGenerator svgGenerator) { this.dbClient = dbClient; this.support = support; this.svgGenerator = svgGenerator; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("measure") .setHandler(this) .setDescription("Generate badge for project's measure as an SVG.<br/>" + "Requires 'Browse' permission on the specified project.") .setSince("7.1") .setResponseExample(Resources.getResource(getClass(), "measure-example.svg")); support.addProjectAndBranchParams(action); action.createParam(PARAM_METRIC) .setDescription("Metric key") .setRequired(true) .setPossibleValues(METRIC_NAME_BY_KEY.keySet()); } @Override public void handle(Request request, Response response) throws Exception { response.setHeader("Cache-Control", "no-cache"); response.stream().setMediaType(SVG); String metricKey = request.mandatoryParam(PARAM_METRIC); try (DbSession dbSession = dbClient.openSession(false)) { support.validateToken(request); BranchDto branch = support.getBranch(dbSession, request); MetricDto metric = dbClient.metricDao().selectByKey(dbSession, metricKey); checkState(metric != null && metric.isEnabled(), "Metric '%s' hasn't been found", metricKey); LiveMeasureDto measure = getMeasure(dbSession, branch, metricKey); String result = generateSvg(metric, measure); String eTag = getETag(result); Optional<String> requestedETag = request.header("If-None-Match"); if (requestedETag.filter(eTag::equals).isPresent()) { response.stream().setStatus(304); return; } response.setHeader("ETag", eTag); write(result, response.stream().output(), UTF_8); } catch (ProjectBadgesException | ForbiddenException | NotFoundException e) { // There is an issue, so do not return any ETag but make this response expire now SimpleDateFormat sdf = new SimpleDateFormat(RFC1123_DATE, Locale.US); response.setHeader("Expires", sdf.format(new Date())); write(svgGenerator.generateError(e.getMessage()), response.stream().output(), UTF_8); } } private LiveMeasureDto getMeasure(DbSession dbSession, BranchDto branch, String metricKey) { return dbClient.liveMeasureDao().selectMeasure(dbSession, branch.getUuid(), metricKey) .orElseThrow(() -> new ProjectBadgesException("Measure has not been found")); } private String generateSvg(MetricDto metric, LiveMeasureDto measure) { String metricType = metric.getValueType(); switch (ValueType.valueOf(metricType)) { case INT: return generateBadge(metric, formatNumeric(getNonNullValue(measure, LiveMeasureDto::getValue).longValue()), Color.DEFAULT); case PERCENT: return generateBadge(metric, formatPercent(getNonNullValue(measure, LiveMeasureDto::getValue)), Color.DEFAULT); case LEVEL: return generateQualityGate(metric, measure); case WORK_DUR: return generateBadge(metric, formatDuration(getNonNullValue(measure, LiveMeasureDto::getValue).longValue()), Color.DEFAULT); case RATING: return generateRating(metric, measure); default: throw new IllegalStateException(format("Invalid metric type '%s'", metricType)); } } private String generateQualityGate(MetricDto metric, LiveMeasureDto measure) { Level qualityGate = Level.valueOf(getNonNullValue(measure, LiveMeasureDto::getTextValue)); return generateBadge(metric, QUALITY_GATE_MESSAGE_BY_STATUS.get(qualityGate), COLOR_BY_QUALITY_GATE_STATUS.get(qualityGate)); } private String generateRating(MetricDto metric, LiveMeasureDto measure) { Rating rating = valueOf(getNonNullValue(measure, LiveMeasureDto::getValue).intValue()); return generateBadge(metric, rating.name(), COLOR_BY_RATING.get(rating)); } private String generateBadge(MetricDto metric, String value, Color color) { return svgGenerator.generateBadge(METRIC_NAME_BY_KEY.get(metric.getKey()), value, color); } private static <P> P getNonNullValue(LiveMeasureDto measure, Function<LiveMeasureDto, P> function) { P value = function.apply(measure); checkState(value != null, "Measure has not been found"); return value; } }
9,514
43.882075
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ProjectBadgesException.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.badge.ws; class ProjectBadgesException extends RuntimeException { ProjectBadgesException(String message) { super(message); } }
1,006
33.724138
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ProjectBadgesSupport.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.badge.ws; import javax.annotation.Nullable; import org.sonar.api.config.Configuration; 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.component.BranchDto; import org.sonar.db.project.ProjectBadgeTokenDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.PROJECT_BADGE_TOKEN_EXAMPLE; public class ProjectBadgesSupport { private static final String PARAM_PROJECT = "project"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_TOKEN = "token"; public static final String PROJECT_HAS_NOT_BEEN_FOUND = "Project has not been found"; private final ComponentFinder componentFinder; private final DbClient dbClient; private final Configuration config; public ProjectBadgesSupport(ComponentFinder componentFinder, DbClient dbClient, Configuration config) { this.componentFinder = componentFinder; this.dbClient = dbClient; this.config = config; } void addProjectAndBranchParams(WebService.NewAction action) { action.createParam(PARAM_PROJECT) .setDescription("Project or application key") .setRequired(true) .setExampleValue(KEY_PROJECT_EXAMPLE_001); action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_TOKEN) .setDescription("Project badge token") .setExampleValue(PROJECT_BADGE_TOKEN_EXAMPLE); } BranchDto getBranch(DbSession dbSession, Request request) { try { String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchName = request.param(PARAM_BRANCH); ProjectDto project = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); BranchDto branch = componentFinder.getBranchOrPullRequest(dbSession, project, branchName, null); if (!branch.getBranchType().equals(BRANCH)) { throw generateInvalidProjectException(); } return branch; } catch (NotFoundException e) { throw new NotFoundException(PROJECT_HAS_NOT_BEEN_FOUND); } } private static ProjectBadgesException generateInvalidProjectException() { return new ProjectBadgesException("Project is invalid"); } public void validateToken(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { String projectKey = request.mandatoryParam(PARAM_PROJECT); ProjectDto projectDto; try { projectDto = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); } catch (NotFoundException e) { throw new NotFoundException(PROJECT_HAS_NOT_BEEN_FOUND); } boolean tokenInvalid = !isTokenValid(dbSession, projectDto, request.param(PARAM_TOKEN)); boolean forceAuthEnabled = config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE); if ((projectDto.isPrivate() || forceAuthEnabled) && tokenInvalid) { throw new NotFoundException(PROJECT_HAS_NOT_BEEN_FOUND); } } } private boolean isTokenValid(DbSession dbSession, ProjectDto projectDto, @Nullable String token) { ProjectBadgeTokenDto projectBadgeTokenDto = dbClient.projectBadgeTokenDao().selectTokenByProject(dbSession, projectDto); return token != null && projectBadgeTokenDto != null && token.equals(projectBadgeTokenDto.getToken()); } }
4,820
40.205128
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ProjectBadgesWs.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.badge.ws; import java.util.List; import org.sonar.api.server.ws.WebService; public class ProjectBadgesWs implements WebService { static final String PROJECT_OR_APP_NOT_FOUND = "Project or Application not found"; private final List<ProjectBadgesWsAction> actions; public ProjectBadgesWs(List<ProjectBadgesWsAction> actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/project_badges"); controller.setDescription("Generate badges based on quality gates or measures"); controller.setSince("7.1"); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,575
34.022222
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ProjectBadgesWsAction.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.badge.ws; import org.sonar.server.ws.WsAction; interface ProjectBadgesWsAction extends WsAction { // Marker interface }
992
35.777778
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/ProjectBadgesWsModule.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.badge.ws; import org.sonar.core.platform.Module; public class ProjectBadgesWsModule extends Module { @Override protected void configureModule() { add( ProjectBadgesWs.class, QualityGateAction.class, MeasureAction.class, TokenAction.class, SvgGenerator.class, ProjectBadgesSupport.class, TokenRenewAction.class); } }
1,239
31.631579
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/QualityGateAction.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.badge.ws; import com.google.common.io.Resources; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Optional; import org.sonar.api.measures.Metric.Level; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.write; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.server.badge.ws.ETagUtils.RFC1123_DATE; import static org.sonar.server.badge.ws.ETagUtils.getETag; import static org.sonarqube.ws.MediaTypes.SVG; public class QualityGateAction implements ProjectBadgesWsAction { private final DbClient dbClient; private final ProjectBadgesSupport support; private final SvgGenerator svgGenerator; public QualityGateAction(DbClient dbClient, ProjectBadgesSupport support, SvgGenerator svgGenerator) { this.dbClient = dbClient; this.support = support; this.svgGenerator = svgGenerator; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("quality_gate") .setHandler(this) .setSince("7.1") .setDescription("Generate badge for project's quality gate as an SVG.<br/>" + "Requires 'Browse' permission on the specified project.") .setResponseExample(Resources.getResource(getClass(), "quality_gate-example.svg")); support.addProjectAndBranchParams(action); } @Override public void handle(Request request, Response response) throws Exception { response.setHeader("Cache-Control", "no-cache"); response.stream().setMediaType(SVG); try (DbSession dbSession = dbClient.openSession(false)) { support.validateToken(request); BranchDto branch = support.getBranch(dbSession, request); Level qualityGateStatus = getQualityGate(dbSession, branch); String result = svgGenerator.generateQualityGate(qualityGateStatus); String eTag = getETag(result); Optional<String> requestedETag = request.header("If-None-Match"); if (requestedETag.filter(eTag::equals).isPresent()) { response.stream().setStatus(304); return; } response.setHeader("ETag", eTag); write(result, response.stream().output(), UTF_8); } catch (ProjectBadgesException | ForbiddenException | NotFoundException e) { // There is an issue, so do not return any ETag but make this response expire now SimpleDateFormat sdf = new SimpleDateFormat(RFC1123_DATE, Locale.US); response.setHeader("Expires", sdf.format(new Date())); write(svgGenerator.generateError(e.getMessage()), response.stream().output(), UTF_8); } } private Level getQualityGate(DbSession dbSession, BranchDto branch) { return Level.valueOf(dbClient.liveMeasureDao().selectMeasure(dbSession, branch.getUuid(), ALERT_STATUS_KEY) .map(LiveMeasureDto::getTextValue) .orElseThrow(() -> new ProjectBadgesException("Quality gate has not been found"))); } }
4,272
41.306931
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgFormatter.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.badge.ws; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.trim; class SvgFormatter { private static final String ZERO = "0"; private static final String NUMERIC_SUFFIX_LIST = " kmbt"; private static final String NUMERIC_REGEXP = "\\.[0-9]+"; private static final String DURATION_MINUTES_FORMAT = "%smin"; private static final String DURATION_HOURS_FORMAT = "%sh"; private static final String DURATION_DAYS_FORMAT = "%sd"; private static final int DURATION_HOURS_IN_DAY = 8; private static final double DURATION_ALMOST_ONE = 0.9; private static final int DURATION_OF_ONE_HOUR_IN_MINUTES = 60; private SvgFormatter() { // Only static methods } static String formatNumeric(long value) { if (value == 0) { return ZERO; } NumberFormat numericFormatter = DecimalFormat.getInstance(Locale.ENGLISH); numericFormatter.setMaximumFractionDigits(1); int power = (int) StrictMath.log10(value); double valueToFormat = value / (Math.pow(10, Math.floorDiv(power, 3) * 3D)); String formattedNumber = numericFormatter.format(valueToFormat); formattedNumber = formattedNumber + NUMERIC_SUFFIX_LIST.charAt(power / 3); return formattedNumber.length() > 4 ? trim(formattedNumber.replaceAll(NUMERIC_REGEXP, "")) : trim(formattedNumber); } static String formatPercent(double value) { DecimalFormat percentFormatter = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); return percentFormatter.format(value) + "%"; } static String formatDuration(long durationInMinutes) { if (durationInMinutes == 0) { return ZERO; } double days = (double) durationInMinutes / DURATION_HOURS_IN_DAY / DURATION_OF_ONE_HOUR_IN_MINUTES; if (days > DURATION_ALMOST_ONE) { return format(DURATION_DAYS_FORMAT, Math.round(days)); } double remainingDuration = durationInMinutes - (Math.floor(days) * DURATION_HOURS_IN_DAY * DURATION_OF_ONE_HOUR_IN_MINUTES); double hours = remainingDuration / DURATION_OF_ONE_HOUR_IN_MINUTES; if (hours > DURATION_ALMOST_ONE) { return format(DURATION_HOURS_FORMAT, Math.round(hours)); } double minutes = remainingDuration - (Math.floor(hours) * DURATION_OF_ONE_HOUR_IN_MINUTES); return format(DURATION_MINUTES_FORMAT, Math.round(minutes)); } }
3,348
38.869048
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.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.badge.ws; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.sonar.api.measures.Metric; import org.sonar.api.server.ServerSide; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.valueOf; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; import static org.sonar.api.measures.Metric.Level.WARN; @ServerSide public class SvgGenerator { private static final Map<Character, Integer> CHAR_LENGTH = ImmutableMap.<Character, Integer>builder() .put('0', 7) .put('1', 7) .put('2', 7) .put('3', 7) .put('4', 7) .put('5', 7) .put('6', 7) .put('7', 7) .put('8', 7) .put('9', 7) .put('a', 7) .put('b', 7) .put('c', 6) .put('d', 7) .put('e', 6) .put('f', 4) .put('g', 7) .put('h', 7) .put('i', 3) .put('j', 5) .put('k', 6) .put('l', 3) .put('m', 11) .put('n', 7) .put('o', 7) .put('p', 7) .put('q', 7) .put('r', 5) .put('s', 6) .put('t', 4) .put('u', 7) .put('v', 6) .put('w', 9) .put('x', 6) .put('y', 6) .put('z', 6) .put('A', 7) .put('B', 7) .put('C', 8) .put('D', 8) .put('E', 7) .put('F', 6) .put('G', 8) .put('H', 8) .put('I', 5) .put('J', 5) .put('K', 7) .put('L', 6) .put('M', 9) .put('N', 8) .put('O', 9) .put('P', 7) .put('Q', 9) .put('R', 8) .put('S', 7) .put('T', 7) .put('U', 8) .put('V', 10) .put('W', 10) .put('X', 7) .put('Y', 7) .put('Z', 7) .put('%', 12) .put(' ', 4) .put('.', 4) .put('_', 7) .put('\'', 3) .build(); private static final String TEMPLATES_PATH = "templates/sonarqube"; private static final int MARGIN = 6; private static final int ICON_WIDTH = 20; private static final String PARAMETER_ICON_WIDTH_PLUS_MARGIN = "iconWidthPlusMargin"; private static final String PARAMETER_TOTAL_WIDTH = "totalWidth"; private static final String PARAMETER_LEFT_WIDTH = "leftWidth"; private static final String PARAMETER_LEFT_WIDTH_PLUS_MARGIN = "leftWidthPlusMargin"; private static final String PARAMETER_RIGHT_WIDTH = "rightWidth"; private static final String PARAMETER_LABEL_WIDTH = "labelWidth"; private static final String PARAMETER_VALUE_WIDTH = "valueWidth"; private static final String PARAMETER_COLOR = "color"; private static final String PARAMETER_LABEL = "label"; private static final String PARAMETER_VALUE = "value"; private final String errorTemplate; private final String badgeTemplate; private final Map<Metric.Level, String> qualityGateTemplates; public SvgGenerator() { this.errorTemplate = readTemplate("templates/error.svg"); this.badgeTemplate = readTemplate(TEMPLATES_PATH + "/badge.svg"); this.qualityGateTemplates = Map.of( OK, readTemplate(TEMPLATES_PATH + "/quality_gate_passed.svg"), WARN, readTemplate(TEMPLATES_PATH + "/quality_gate_warn.svg"), ERROR, readTemplate(TEMPLATES_PATH + "/quality_gate_failed.svg")); } public String generateBadge(String label, String value, Color backgroundValueColor) { int labelWidth = computeWidth(label); int valueWidth = computeWidth(value); Map<String, String> values = ImmutableMap.<String, String>builder() .put(PARAMETER_TOTAL_WIDTH, valueOf(MARGIN * 4 + ICON_WIDTH + labelWidth + valueWidth)) .put(PARAMETER_LABEL_WIDTH, valueOf(labelWidth)) .put(PARAMETER_VALUE_WIDTH, valueOf(valueWidth)) .put(PARAMETER_LEFT_WIDTH, valueOf(MARGIN * 2 + ICON_WIDTH + labelWidth)) .put(PARAMETER_LEFT_WIDTH_PLUS_MARGIN, valueOf(MARGIN * 3 + ICON_WIDTH + labelWidth)) .put(PARAMETER_RIGHT_WIDTH, valueOf(MARGIN * 2 + valueWidth)) .put(PARAMETER_ICON_WIDTH_PLUS_MARGIN, valueOf(MARGIN + ICON_WIDTH)) .put(PARAMETER_COLOR, backgroundValueColor.getValue()) .put(PARAMETER_LABEL, label) .put(PARAMETER_VALUE, value) .build(); StrSubstitutor strSubstitutor = new StrSubstitutor(values); return strSubstitutor.replace(badgeTemplate); } public String generateQualityGate(Metric.Level level) { return qualityGateTemplates.get(level); } public String generateError(String error) { Map<String, String> values = ImmutableMap.of( PARAMETER_TOTAL_WIDTH, valueOf(MARGIN + computeWidth(error) + MARGIN), PARAMETER_LABEL, error); StrSubstitutor strSubstitutor = new StrSubstitutor(values); return strSubstitutor.replace(errorTemplate); } private static int computeWidth(String text) { return text.chars() .mapToObj(i -> (char) i) .mapToInt(c -> { Integer length = CHAR_LENGTH.get(c); checkState(length != null, "Invalid character '%s'", c); return length; }) .sum(); } private String readTemplate(String template) { try { return IOUtils.toString(getClass().getResource(template), UTF_8); } catch (IOException e) { throw new IllegalStateException(String.format("Can't read svg template '%s'", template), e); } } static class Color { static final Color DEFAULT = new Color("#999999"); static final Color QUALITY_GATE_OK = new Color("#00aa00"); static final Color QUALITY_GATE_WARN = new Color("#ed7d20"); static final Color QUALITY_GATE_ERROR = new Color("#d4333f"); static final Color RATING_A = new Color("#00aa00"); static final Color RATING_B = new Color("#b0d513"); static final Color RATING_C = new Color("#eabe06"); static final Color RATING_D = new Color("#ed7d20"); static final Color RATING_E = new Color("#d4333f"); private final String value; private Color(String value) { this.value = value; } String getValue() { return value; } } }
6,899
31.54717
103
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/TokenAction.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.badge.ws; import com.google.common.io.Resources; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.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.ProjectBadgeTokenDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.TokenType; import org.sonar.server.user.UserSession; import org.sonar.server.usertoken.TokenGenerator; import org.sonarqube.ws.ProjectBadgeToken.TokenWsResponse; import static java.lang.String.format; import static org.sonar.server.badge.ws.ProjectBadgesWs.PROJECT_OR_APP_NOT_FOUND; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class TokenAction implements ProjectBadgesWsAction { private static final String PROJECT_KEY_PARAM = "project"; private final DbClient dbClient; private final TokenGenerator tokenGenerator; private final UserSession userSession; public TokenAction(DbClient dbClient, TokenGenerator tokenGenerator, UserSession userSession) { this.dbClient = dbClient; this.tokenGenerator = tokenGenerator; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("token") .setHandler(this) .setSince("9.2") .setChangelog(new Change("10.1", format("Application key can be used for %s parameter.", PROJECT_KEY_PARAM))) .setDescription("Retrieve a token to use for project or application badge access for private projects or applications.<br/>" + "This token can be used to authenticate with api/project_badges/quality_gate and api/project_badges/measure endpoints.<br/>" + "Requires 'Browse' permission on the specified project or application.") .setResponseExample(Resources.getResource(getClass(), "token-example.json")); action.createParam(PROJECT_KEY_PARAM) .setDescription("Project or application key") .setRequired(true) .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { TokenWsResponse tokenWsResponse = doHandle(request); writeProtobuf(tokenWsResponse, request, response); } private TokenWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { String projectKey = request.mandatoryParam(PROJECT_KEY_PARAM); ProjectDto projectDto = dbClient.projectDao().selectProjectOrAppByKey(dbSession, projectKey) .orElseThrow(() -> new IllegalArgumentException(PROJECT_OR_APP_NOT_FOUND)); userSession.checkEntityPermission(UserRole.USER, projectDto); ProjectBadgeTokenDto projectBadgeTokenDto = dbClient.projectBadgeTokenDao().selectTokenByProject(dbSession, projectDto); if (projectBadgeTokenDto == null) { String token = tokenGenerator.generate(TokenType.PROJECT_BADGE_TOKEN); projectBadgeTokenDto = dbClient.projectBadgeTokenDao().insert(dbSession, token, projectDto, userSession.getUuid(), userSession.getLogin()); dbSession.commit(); } return buildResponse(projectBadgeTokenDto); } } private static TokenWsResponse buildResponse(ProjectBadgeTokenDto projectBadgeTokenDto) { return TokenWsResponse.newBuilder() .setToken(projectBadgeTokenDto.getToken()) .build(); } }
4,453
41.826923
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/TokenRenewAction.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.badge.ws; 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.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.TokenType; import org.sonar.server.user.UserSession; import org.sonar.server.usertoken.TokenGenerator; import static java.lang.String.format; import static org.sonar.server.badge.ws.ProjectBadgesWs.PROJECT_OR_APP_NOT_FOUND; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; public class TokenRenewAction implements ProjectBadgesWsAction { private static final String PROJECT_KEY_PARAM = "project"; private final DbClient dbClient; private final TokenGenerator tokenGenerator; private final UserSession userSession; public TokenRenewAction(DbClient dbClient, TokenGenerator tokenGenerator, UserSession userSession) { this.dbClient = dbClient; this.tokenGenerator = tokenGenerator; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { NewAction action = controller.createAction("renew_token") .setHandler(this) .setSince("9.2") .setPost(true) .setChangelog(new Change("10.1", format("Application key can be used for %s parameter.", PROJECT_KEY_PARAM))) .setDescription("Creates new token replacing any existing token for project or application badge access for private projects and " + "applications.<br/>" + "This token can be used to authenticate with api/project_badges/quality_gate and api/project_badges/measure endpoints.<br/>" + "Requires 'Administer' permission on the specified project or application."); action.createParam(PROJECT_KEY_PARAM) .setDescription("Project or application key") .setRequired(true) .setExampleValue(KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { doHandle(request); response.noContent(); } private void doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { String projectKey = request.mandatoryParam(PROJECT_KEY_PARAM); ProjectDto projectDto = dbClient.projectDao().selectProjectOrAppByKey(dbSession, projectKey) .orElseThrow(() -> new IllegalArgumentException(PROJECT_OR_APP_NOT_FOUND)); userSession.checkEntityPermission(UserRole.ADMIN, projectDto); String newGeneratedToken = tokenGenerator.generate(TokenType.PROJECT_BADGE_TOKEN); dbClient.projectBadgeTokenDao().upsert(dbSession, newGeneratedToken, projectDto, userSession.getUuid(), userSession.getLogin()); dbSession.commit(); } } }
3,734
40.966292
138
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/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.badge.ws; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/BatchIndex.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.batch; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Collection; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.HiddenFileFilter; import org.apache.commons.lang.CharUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.platform.ServerFileSystem; /** * Scanner Engine JAR file(s) to be downloaded by sonar-scanner-api. There is currently only one JAR (see assembly.xml) * but let's keep possibility to pass several files for possible future evolutions. */ @ServerSide public class BatchIndex implements Startable { private final ServerFileSystem fs; private String index; private File batchDir; public BatchIndex(ServerFileSystem fs) { this.fs = fs; } @Override public void start() { StringBuilder sb = new StringBuilder(); batchDir = new File(fs.getHomeDir(), "lib/scanner"); if (batchDir.exists()) { Collection<File> files = FileUtils.listFiles(batchDir, HiddenFileFilter.VISIBLE, FileFilterUtils.directoryFileFilter()); for (File file : files) { String filename = file.getName(); if (StringUtils.endsWith(filename, ".jar")) { try (FileInputStream fis = new FileInputStream(file)) { sb.append(filename).append('|').append(DigestUtils.md5Hex(fis)).append(CharUtils.LF); } catch (IOException e) { throw new IllegalStateException("Fail to compute hash", e); } } } } this.index = sb.toString(); } @Override public void stop() { // Nothing to do } String getIndex() { return index; } File getFile(String filename) { try { File input = new File(batchDir, filename); if (!FilenameUtils.directoryContains(batchDir.getCanonicalPath(), input.getCanonicalPath()) || !input.exists()) { throw new NotFoundException("Bad filename: " + filename); } return input; } catch (IOException e) { throw new IllegalStateException("Can get file " + filename, e); } } }
3,217
33.234043
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/BatchWs.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.batch; import org.sonar.api.server.ws.WebService; import static java.util.Arrays.stream; public class BatchWs implements WebService { public static final String API_ENDPOINT = "batch"; private final BatchWsAction[] actions; public BatchWs(BatchWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(API_ENDPOINT) .setSince("4.4") .setDescription("Get JAR files and referentials for batch"); stream(actions).forEach(action -> action.define(controller)); controller.done(); } }
1,488
31.369565
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/BatchWsAction.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.batch; import org.sonar.server.ws.WsAction; public interface BatchWsAction extends WsAction { // Marker interface }
988
35.62963
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/BatchWsModule.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.batch; import org.sonar.core.platform.Module; public class BatchWsModule extends Module { @Override protected void configureModule() { add( BatchIndex.class, ProjectAction.class, ProjectDataLoader.class, IndexAction.class, FileAction.class, BatchWs.class); } }
1,177
31.722222
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/FileAction.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.batch; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; public class FileAction implements BatchWsAction { private final BatchIndex batchIndex; public FileAction(BatchIndex batchIndex) { this.batchIndex = batchIndex; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("file") .setInternal(true) .setSince("4.4") .setDescription("Download a JAR file listed in the index (see batch/index)") .setResponseExample(getClass().getResource("batch-file-example.txt")) .setHandler(this); action .createParam("name") .setDescription("File name") .setExampleValue("batch-library-2.3.jar"); } @Override public void handle(Request request, Response response) throws Exception { String filename = request.mandatoryParam("name"); try { response.stream().setMediaType("application/java-archive"); File file = batchIndex.getFile(filename); FileUtils.copyFile(file, response.stream().output()); } catch (IOException e) { throw new IllegalStateException(e); } } }
2,167
33.412698
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/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.batch; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static com.google.common.base.Preconditions.checkState; import static java.nio.charset.StandardCharsets.UTF_8; public class IndexAction implements BatchWsAction { private final BatchIndex batchIndex; public IndexAction(BatchIndex batchIndex) { this.batchIndex = batchIndex; } @Override public void define(WebService.NewController context) { context.createAction("index") .setInternal(true) .setSince("4.4") .setDescription("List the JAR files to be downloaded by scanners") .setHandler(this) .setResponseExample(getClass().getResource("index-example.txt")); } @Override public void handle(Request request, Response response) throws Exception { try { response.stream().setMediaType("text/plain"); String index = batchIndex.getIndex(); checkState(index != null, "No available files"); IOUtils.write(index, response.stream().output(), UTF_8); } catch (IOException e) { throw new IllegalStateException(e); } } }
2,085
33.196721
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/ProjectAction.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.batch; import java.util.Map; import java.util.stream.Collectors; 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.scanner.protocol.input.FileData; import org.sonar.scanner.protocol.input.ProjectRepositories; import org.sonarqube.ws.Batch.WsProjectResponse; import org.sonarqube.ws.Batch.WsProjectResponse.FileData.Builder; import static java.util.Optional.ofNullable; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ProjectAction implements BatchWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_PROFILE = "profile"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_PULL_REQUEST = "pullRequest"; private final ProjectDataLoader projectDataLoader; public ProjectAction(ProjectDataLoader projectDataLoader) { this.projectDataLoader = projectDataLoader; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("project") .setDescription("Return project repository") .setResponseExample(getClass().getResource("project-example.json")) .setSince("4.5") .setChangelog( new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_KEY)), new Change("7.6", "Stop returning settings"), new Change("7.7", "Stop supporting preview mode, removed timestamp and last analysis date"), new Change("10.0", String.format("No longer possible to use module keys with parameter '%s'", PARAM_KEY))) .setInternal(true) .setHandler(this); action .createParam(PARAM_KEY) .setRequired(true) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001); action .createParam(PARAM_PROFILE) .setDescription("Profile name") .setExampleValue("SonarQube Way"); action .createParam(PARAM_BRANCH) .setSince("6.6") .setDescription("Branch key") .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_PULL_REQUEST) .setSince("7.1") .setDescription("Pull request id") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { ProjectRepositories data = projectDataLoader.load(ProjectDataQuery.create() .setProjectKey(wsRequest.mandatoryParam(PARAM_KEY)) .setProfileName(wsRequest.param(PARAM_PROFILE)) .setBranch(wsRequest.param(PARAM_BRANCH)) .setPullRequest(wsRequest.param(PARAM_PULL_REQUEST))); WsProjectResponse projectResponse = buildResponse(data); writeProtobuf(projectResponse, wsRequest, wsResponse); } private static WsProjectResponse buildResponse(ProjectRepositories data) { WsProjectResponse.Builder response = WsProjectResponse.newBuilder(); response.putAllFileDataByPath(buildFileDataByPath(data)); return response.build(); } private static Map<String, WsProjectResponse.FileData> buildFileDataByPath(ProjectRepositories data) { return data.fileData().entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> toFileDataResponse(e.getValue()))); } private static WsProjectResponse.FileData toFileDataResponse(FileData fileData) { Builder fileDataBuilder = WsProjectResponse.FileData.newBuilder(); ofNullable(fileData.hash()).ifPresent(fileDataBuilder::setHash); ofNullable(fileData.revision()).ifPresent(fileDataBuilder::setRevision); return fileDataBuilder.build(); } }
4,805
38.719008
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/ProjectDataLoader.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.batch; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; 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.FilePathWithHashDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.scanner.protocol.input.FileData; import org.sonar.scanner.protocol.input.ProjectRepositories; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.user.UserSession; import static org.sonar.server.exceptions.BadRequestException.checkRequest; @ServerSide public class ProjectDataLoader { private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public ProjectDataLoader(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } public ProjectRepositories load(ProjectDataQuery query) { try (DbSession session = dbClient.openSession(false)) { String projectKey = query.getProjectKey(); String branch = query.getBranch(); String pullRequest = query.getPullRequest(); ComponentDto project = componentFinder.getByKey(session, projectKey); checkRequest(project.isRootProject(), "Key '%s' belongs to a component which is not a Project", projectKey); boolean hasScanPerm = userSession.hasComponentPermission(UserRole.SCAN, project) || userSession.hasPermission(GlobalPermission.SCAN); checkPermission(hasScanPerm); ComponentDto branchComponent = (branch == null && pullRequest == null) ? project : componentFinder.getByKeyAndOptionalBranchOrPullRequest(session, projectKey, branch, pullRequest); List<FilePathWithHashDto> files = searchFilesWithHashAndRevision(session, branchComponent); ProjectRepositories repository = new ProjectRepositories(); addFileData(repository, files); return repository; } } private List<FilePathWithHashDto> searchFilesWithHashAndRevision(DbSession session, @Nullable ComponentDto branchComponent) { if (branchComponent == null) { return Collections.emptyList(); } return dbClient.componentDao().selectEnabledFilesFromProject(session, branchComponent.uuid()); } private static void addFileData(ProjectRepositories data, List<FilePathWithHashDto> files) { for (FilePathWithHashDto file : files) { FileData fileData = new FileData(file.getSrcHash(), file.getRevision()); data.addFileData(file.getPath(), fileData); } } private static void checkPermission(boolean hasScanPerm) { if (!hasScanPerm) { throw new ForbiddenException("You're not authorized to push analysis results to the SonarQube server. " + "Please contact your SonarQube administrator."); } } }
3,893
40.425532
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/ProjectDataQuery.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.batch; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class ProjectDataQuery { private String projectKey; private String profileName; private String branch; private String pullRequest; private ProjectDataQuery() { // No direct call } @CheckForNull public String getProfileName() { return profileName; } public ProjectDataQuery setProfileName(@Nullable String profileName) { this.profileName = profileName; return this; } public String getProjectKey() { return projectKey; } public ProjectDataQuery setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } @CheckForNull public String getBranch() { return branch; } public ProjectDataQuery setBranch(@Nullable String branch) { this.branch = branch; return this; } @CheckForNull public String getPullRequest() { return pullRequest; } public ProjectDataQuery setPullRequest(@Nullable String pullRequest) { this.pullRequest = pullRequest; return this; } public static ProjectDataQuery create() { return new ProjectDataQuery(); } }
2,022
24.607595
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/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.batch; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/ws/BranchWsAction.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.branch.ws; import org.sonar.server.ws.WsAction; public interface BranchWsAction extends WsAction { // marker interface }
993
35.814815
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/ws/BranchWsModule.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.branch.ws; import org.sonar.core.platform.Module; public class BranchWsModule extends Module { @Override protected void configureModule() { add( ListAction.class, DeleteAction.class, RenameAction.class, SetAutomaticDeletionProtectionAction.class, BranchesWs.class); } }
1,180
32.742857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/ws/BranchesWs.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.branch.ws; import java.util.Arrays; import org.sonar.api.server.ws.WebService; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.branch.ws.ProjectBranchesParameters.CONTROLLER; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_BRANCH; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT; public class BranchesWs implements WebService { private final BranchWsAction[] actions; public BranchesWs(BranchWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(CONTROLLER) .setSince("6.6") .setDescription("Manage branch"); Arrays.stream(actions).forEach(action -> action.define(controller)); controller.done(); } static void addProjectParam(NewAction action) { action .createParam(PARAM_PROJECT) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001) .setRequired(true); } static void addBranchParam(NewAction action) { action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setExampleValue("feature/my_branch") .setRequired(true); } }
2,137
32.936508
81
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/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.branch.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.NewController; 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.project.ProjectDto; import org.sonar.server.component.ComponentCleanerService; import org.sonar.server.component.ComponentFinder; import org.sonar.server.project.Project; import org.sonar.server.project.ProjectLifeCycleListeners; import org.sonar.server.user.UserSession; import static java.util.Collections.singleton; import static org.sonar.server.branch.ws.BranchesWs.addBranchParam; import static org.sonar.server.branch.ws.BranchesWs.addProjectParam; import static org.sonar.server.branch.ws.ProjectBranchesParameters.ACTION_DELETE; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_BRANCH; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; public class DeleteAction implements BranchWsAction { private final DbClient dbClient; private final UserSession userSession; private final ComponentCleanerService componentCleanerService; private final ComponentFinder componentFinder; private final ProjectLifeCycleListeners projectLifeCycleListeners; public DeleteAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, ComponentCleanerService componentCleanerService, ProjectLifeCycleListeners projectLifeCycleListeners) { this.dbClient = dbClient; this.componentFinder = componentFinder; this.userSession = userSession; this.componentCleanerService = componentCleanerService; this.projectLifeCycleListeners = projectLifeCycleListeners; } @Override public void define(NewController context) { WebService.NewAction action = context.createAction(ACTION_DELETE) .setSince("6.6") .setDescription("Delete a non-main branch of a project or application.<br/>" + "Requires 'Administer' rights on the specified project or application.") .setPost(true) .setHandler(this); addProjectParam(action); addBranchParam(action); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); checkPermission(project); BranchDto branch = checkFoundWithOptional( dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), branchKey), "Branch '%s' not found for project '%s'", branchKey, projectKey); componentCleanerService.deleteBranch(dbSession, branch); projectLifeCycleListeners.onProjectBranchesDeleted(singleton(Project.fromProjectDtoWithTags(project))); response.noContent(); } } private void checkPermission(ProjectDto project) { userSession.checkEntityPermission(UserRole.ADMIN, project); } }
4,177
41.20202
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/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.branch.ws; import com.google.common.io.Resources; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonar.server.ws.WsUtils; import org.sonarqube.ws.Common; import org.sonarqube.ws.ProjectBranches; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.server.branch.ws.BranchesWs.addProjectParam; import static org.sonar.server.branch.ws.ProjectBranchesParameters.ACTION_LIST; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; public class ListAction implements BranchWsAction { private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public ListAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_LIST) .setSince("6.6") .setDescription("List the branches of a project or application.<br/>" + "Requires 'Browse' or 'Execute analysis' rights on the specified project or application.") .setResponseExample(Resources.getResource(getClass(), "list-example.json")) .setChangelog(new Change("7.2", "Application can be used on this web service")) .setHandler(this); addProjectParam(action); } @Override public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto projectOrApp = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); checkPermission(projectOrApp); Collection<BranchDto> branches = dbClient.branchDao().selectByProject(dbSession, projectOrApp).stream() .filter(b -> b.getBranchType() == BRANCH) .toList(); List<String> branchUuids = branches.stream().map(BranchDto::getUuid).toList(); Map<String, LiveMeasureDto> qualityGateMeasuresByComponentUuids = dbClient.liveMeasureDao() .selectByComponentUuidsAndMetricKeys(dbSession, branchUuids, singletonList(ALERT_STATUS_KEY)).stream() .collect(Collectors.toMap(LiveMeasureDto::getComponentUuid, Function.identity())); Map<String, String> analysisDateByBranchUuid = dbClient.snapshotDao() .selectLastAnalysesByRootComponentUuids(dbSession, branchUuids).stream() .collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, s -> formatDateTime(s.getCreatedAt()))); ProjectBranches.ListWsResponse.Builder protobufResponse = ProjectBranches.ListWsResponse.newBuilder(); branches.forEach(b -> addBranch(protobufResponse, b, qualityGateMeasuresByComponentUuids.get(b.getUuid()), analysisDateByBranchUuid.get(b.getUuid()))); WsUtils.writeProtobuf(protobufResponse.build(), request, response); } } private static void addBranch(ProjectBranches.ListWsResponse.Builder response, BranchDto branch, @Nullable LiveMeasureDto qualityGateMeasure, @Nullable String analysisDate) { ProjectBranches.Branch.Builder builder = toBranchBuilder(branch); setBranchStatus(builder, qualityGateMeasure); if (analysisDate != null) { builder.setAnalysisDate(analysisDate); } response.addBranches(builder); } private static ProjectBranches.Branch.Builder toBranchBuilder(BranchDto branch) { ProjectBranches.Branch.Builder builder = ProjectBranches.Branch.newBuilder(); String branchKey = branch.getKey(); ofNullable(branchKey).ifPresent(builder::setName); builder.setIsMain(branch.isMain()); builder.setType(Common.BranchType.valueOf(branch.getBranchType().name())); builder.setExcludedFromPurge(branch.isExcludeFromPurge()); return builder; } private static void setBranchStatus(ProjectBranches.Branch.Builder builder, @Nullable LiveMeasureDto qualityGateMeasure) { ProjectBranches.Status.Builder statusBuilder = ProjectBranches.Status.newBuilder(); if (qualityGateMeasure != null) { ofNullable(qualityGateMeasure.getDataAsString()).ifPresent(statusBuilder::setQualityGateStatus); } builder.setStatus(statusBuilder); } private void checkPermission(ProjectDto project) { if (!userSession.hasEntityPermission(USER, project) && !userSession.hasEntityPermission(UserRole.SCAN, project) && !userSession.hasPermission(SCAN)) { throw insufficientPrivilegesException(); } } }
6,519
43.657534
124
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/ws/ProjectBranchesParameters.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.branch.ws; public class ProjectBranchesParameters { public static final String CONTROLLER = "api/project_branches"; // actions public static final String ACTION_LIST = "list"; public static final String ACTION_DELETE = "delete"; public static final String ACTION_RENAME = "rename"; public static final String ACTION_SET_AUTOMATIC_DELETION_PROTECTION = "set_automatic_deletion_protection"; // parameters public static final String PARAM_PROJECT = "project"; public static final String PARAM_COMPONENT = "component"; public static final String PARAM_BRANCH = "branch"; public static final String PARAM_NAME = "name"; public static final String PARAM_VALUE = "value"; private ProjectBranchesParameters() { // static utility class } }
1,636
37.069767
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/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.branch.ws; import java.util.Optional; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewController; 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.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.branch.ws.BranchesWs.addProjectParam; import static org.sonar.server.branch.ws.ProjectBranchesParameters.ACTION_RENAME; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_NAME; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT; public class RenameAction implements BranchWsAction { private final ComponentFinder componentFinder; private final UserSession userSession; private final DbClient dbClient; public RenameAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession) { this.dbClient = dbClient; this.componentFinder = componentFinder; this.userSession = userSession; } @Override public void define(NewController context) { WebService.NewAction action = context.createAction(ACTION_RENAME) .setSince("6.6") .setDescription("Rename the main branch of a project or application.<br/>" + "Requires 'Administer' permission on the specified project or application.") .setPost(true) .setHandler(this); addProjectParam(action); action .createParam(PARAM_NAME) .setRequired(true) .setMaximumLength(255) .setDescription("New name of the main branch") .setExampleValue("branch1"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String newBranchName = request.mandatoryParam(PARAM_NAME); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); checkPermission(project); Optional<BranchDto> existingBranch = dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), newBranchName); checkArgument(!existingBranch.filter(b -> !b.isMain()).isPresent(), "Impossible to update branch name: a branch with name \"%s\" already exists in the project.", newBranchName); BranchDto mainBranchDto = dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, project.getUuid()) .orElseThrow(() -> new NotFoundException("Cannot find main branch for project: " + project.getUuid())); dbClient.branchDao().updateBranchName(dbSession, mainBranchDto.getUuid(), newBranchName); dbSession.commit(); response.noContent(); } } private void checkPermission(ProjectDto project) { userSession.checkEntityPermission(UserRole.ADMIN, project); } }
4,043
39.848485
127
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/ws/SetAutomaticDeletionProtectionAction.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.branch.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; 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.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static org.sonar.server.branch.ws.BranchesWs.addBranchParam; import static org.sonar.server.branch.ws.BranchesWs.addProjectParam; import static org.sonar.server.branch.ws.ProjectBranchesParameters.ACTION_SET_AUTOMATIC_DELETION_PROTECTION; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_BRANCH; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_PROJECT; import static org.sonar.server.branch.ws.ProjectBranchesParameters.PARAM_VALUE; public class SetAutomaticDeletionProtectionAction implements BranchWsAction { private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; public SetAutomaticDeletionProtectionAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SET_AUTOMATIC_DELETION_PROTECTION) .setSince("8.1") .setDescription("Protect a specific branch from automatic deletion. Protection can't be disabled for the main branch.<br/>" + "Requires 'Administer' permission on the specified project or application.") .setPost(true) .setHandler(this); addProjectParam(action); addBranchParam(action); action.createParam(PARAM_VALUE) .setRequired(true) .setBooleanPossibleValues() .setDescription("Sets whether the branch should be protected from automatic deletion when it hasn't been analyzed for a set period of time.") .setExampleValue("true"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); boolean excludeFromPurge = request.mandatoryParamAsBoolean(PARAM_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectOrApplicationByKey(dbSession, projectKey); checkPermission(project); BranchDto branch = dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), branchKey) .orElseThrow(() -> new NotFoundException(format("Branch '%s' not found for project '%s'", branchKey, projectKey))); checkArgument(!branch.isMain() || excludeFromPurge, "Main branch of the project is always excluded from automatic deletion."); dbClient.branchDao().updateExcludeFromPurge(dbSession, branch.getUuid(), excludeFromPurge); dbSession.commit(); response.noContent(); } } private void checkPermission(ProjectDto project) { userSession.checkEntityPermission(UserRole.ADMIN, project); } }
4,323
42.676768
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/branch/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.branch.ws; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/projectdump/ExportSubmitter.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.ce.projectdump; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.ce.task.CeTask; @ServerSide public interface ExportSubmitter { /** * Adds a Project Export CE task for the specified project. * * @throws NullPointerException if {@code projectKey} is {@code null} * @throws IllegalArgumentException if the specified project does not exist */ CeTask submitProjectExport(String projectKey, @Nullable String submitterUuid); }
1,353
35.594595
80
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/projectdump/ExportSubmitterImpl.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.ce.projectdump; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.ce.queue.CeQueue; import org.sonar.ce.queue.CeTaskSubmit; import org.sonar.ce.task.CeTask; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.project.ProjectDto; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.emptyMap; import static java.util.Objects.requireNonNull; import static org.sonar.ce.queue.CeTaskSubmit.Component.fromDto; public class ExportSubmitterImpl implements ExportSubmitter { private final CeQueue ceQueue; private final DbClient dbClient; public ExportSubmitterImpl(CeQueue ceQueue, DbClient dbClient) { this.ceQueue = ceQueue; this.dbClient = dbClient; } @Override public CeTask submitProjectExport(String projectKey, @Nullable String submitterUuid) { requireNonNull(projectKey, "Project key can not be null"); try (DbSession dbSession = dbClient.openSession(false)) { Optional<ProjectDto> project = dbClient.projectDao().selectProjectByKey(dbSession, projectKey); checkArgument(project.isPresent(), "Project with key [%s] does not exist", projectKey); CeTaskSubmit submit = ceQueue.prepareSubmit() .setComponent(fromDto(project.get().getUuid(), project.get().getUuid())) .setType(CeTaskTypes.PROJECT_EXPORT) .setSubmitterUuid(submitterUuid) .setCharacteristics(emptyMap()) .build(); return ceQueue.submit(submit); } } }
2,429
36.96875
101
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/projectdump/ProjectExportWsModule.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.ce.projectdump; import org.sonar.core.platform.Module; import org.sonar.server.projectdump.ws.ExportAction; import org.sonar.server.projectdump.ws.ProjectDumpWs; import org.sonar.server.projectdump.ws.ProjectDumpWsSupport; import org.sonar.server.projectdump.ws.StatusAction; public class ProjectExportWsModule extends Module { @Override protected void configureModule() { super.add( ProjectDumpWsSupport.class, ProjectDumpWs.class, ExportAction.class, ExportSubmitterImpl.class, StatusAction.class ); } }
1,421
33.682927
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/projectdump/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.ce.projectdump; import javax.annotation.ParametersAreNonnullByDefault;
972
37.92
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/BranchSupport.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.ce.queue; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import static com.google.common.base.Preconditions.checkState; /** * Branch code for {@link ReportSubmitter}. * <p> * Does not support branches unless an implementation of {@link BranchSupportDelegate} is available. */ @ServerSide public class BranchSupport { @CheckForNull private final BranchSupportDelegate delegate; public BranchSupport(@Nullable BranchSupportDelegate delegate) { this.delegate = delegate; } ComponentKey createComponentKey(String projectKey, Map<String, String> characteristics) { if (characteristics.isEmpty()) { return new ComponentKeyImpl(projectKey); } else { checkState(delegate != null, "Current edition does not support branch feature"); } return delegate.createComponentKey(projectKey, characteristics); } ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto) { checkState(delegate != null, "Current edition does not support branch feature"); return delegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto); } public abstract static class ComponentKey { public abstract String getKey(); public abstract Optional<String> getBranchName(); public abstract Optional<String> getPullRequestKey(); public final boolean isMainBranch() { return !getBranchName().isPresent() && !getPullRequestKey().isPresent(); } } private static final class ComponentKeyImpl extends ComponentKey { private final String key; public ComponentKeyImpl(String key) { this.key = key; } @Override public String getKey() { return key; } @Override public Optional<String> getBranchName() { return Optional.empty(); } @Override public Optional<String> getPullRequestKey() { return Optional.empty(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ComponentKeyImpl that = (ComponentKeyImpl) o; return Objects.equals(key, that.key); } @Override public int hashCode() { return Objects.hash(key); } } }
3,470
28.922414
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/BranchSupportDelegate.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.ce.queue; import java.util.Map; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.server.ce.queue.BranchSupport.ComponentKey; @ServerSide public interface BranchSupportDelegate { /** * Creates a {@link ComponentKey} for the specified projectKey and the specified {@code characteristics}. * * @throws IllegalArgumentException if {@code characteristics} is empty * @throws IllegalArgumentException if does not contain a supported value for {@link CeTaskCharacteristicDto#BRANCH_TYPE_KEY BRANCH_TYPE_KEY} * @throws IllegalArgumentException if does not contain a value for expected * {@link CeTaskCharacteristicDto#BRANCH_KEY BRANCH_KEY} or {@link CeTaskCharacteristicDto#PULL_REQUEST PULL_REQUEST} * given the value of {@link CeTaskCharacteristicDto#BRANCH_TYPE_KEY BRANCH_TYPE_KEY} * @throws IllegalArgumentException if incorrectly contains a value in * {@link CeTaskCharacteristicDto#BRANCH_KEY BRANCH_KEY} or {@link CeTaskCharacteristicDto#PULL_REQUEST PULL_REQUEST} * given the value of {@link CeTaskCharacteristicDto#BRANCH_TYPE_KEY BRANCH_TYPE_KEY} */ ComponentKey createComponentKey(String projectKey, Map<String, String> characteristics); /** * Creates the ComponentDto for the branch described in {@code componentKey} which belongs to the specified * {@code mainComponentDto} * * @throws IllegalArgumentException if arguments are inconsistent (such as {@code mainComponentDto} not having the same * key as {@code componentKey.getKey()}, ...) */ ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto); }
2,743
48.890909
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/CeQueueCleaner.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.ce.queue; import java.util.List; import org.sonar.api.Startable; import org.sonar.api.platform.ServerUpgradeStatus; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.ce.queue.CeQueue; import org.sonar.db.DbClient; import org.sonar.db.DbSession; /** * Cleans-up the Compute Engine queue. */ @ServerSide public class CeQueueCleaner implements Startable { private static final Logger LOGGER = LoggerFactory.getLogger(CeQueueCleaner.class); private final DbClient dbClient; private final ServerUpgradeStatus serverUpgradeStatus; private final CeQueue queue; public CeQueueCleaner(DbClient dbClient, ServerUpgradeStatus serverUpgradeStatus, CeQueue queue) { this.dbClient = dbClient; this.serverUpgradeStatus = serverUpgradeStatus; this.queue = queue; } @Override public void start() { if (serverUpgradeStatus.isUpgraded()) { cleanOnUpgrade(); } cleanUpTaskInputOrphans(); } private void cleanOnUpgrade() { // we assume that pending tasks are not compatible with the new version // and can't be processed LOGGER.info("Cancel all pending tasks (due to upgrade)"); queue.clear(); } private void cleanUpTaskInputOrphans() { try (DbSession dbSession = dbClient.openSession(false)) { // Reports that have been processed are not kept in database yet. // They are supposed to be systematically dropped. // Let's clean-up orphans if any. List<String> uuids = dbClient.ceTaskInputDao().selectUuidsNotInQueue(dbSession); dbClient.ceTaskInputDao().deleteByUuids(dbSession, uuids); dbSession.commit(); } } @Override public void stop() { // nothing to do } }
2,610
31.234568
100
java