3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.almintegration.ws.bitbucketserver;
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient;
26 import org.sonar.alm.client.bitbucketserver.Branch;
27 import org.sonar.alm.client.bitbucketserver.BranchesList;
28 import org.sonar.alm.client.bitbucketserver.Repository;
29 import org.sonar.api.server.ws.Request;
30 import org.sonar.api.server.ws.Response;
31 import org.sonar.api.server.ws.WebService;
32 import org.sonar.db.DbClient;
33 import org.sonar.db.DbSession;
34 import org.sonar.db.alm.pat.AlmPatDto;
35 import org.sonar.db.alm.setting.AlmSettingDto;
36 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
37 import org.sonar.db.component.BranchDto;
38 import org.sonar.db.project.ProjectDto;
39 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
40 import org.sonar.server.almintegration.ws.ImportHelper;
41 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
42 import org.sonar.server.component.ComponentCreationData;
43 import org.sonar.server.component.ComponentUpdater;
44 import org.sonar.server.component.NewComponent;
45 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
46 import org.sonar.server.project.DefaultBranchNameResolver;
47 import org.sonar.server.project.ProjectDefaultVisibility;
48 import org.sonar.server.user.UserSession;
49 import org.sonarqube.ws.Projects;
51 import static java.util.Objects.requireNonNull;
52 import static org.sonar.api.resources.Qualifiers.PROJECT;
53 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
54 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
55 import static org.sonar.server.component.NewComponent.newComponentBuilder;
56 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
57 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
58 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
59 import static org.sonar.server.ws.WsUtils.writeProtobuf;
60 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
61 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
63 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
65 private static final String PARAM_PROJECT_KEY = "projectKey";
66 private static final String PARAM_REPO_SLUG = "repositorySlug";
68 private final DbClient dbClient;
69 private final UserSession userSession;
70 private final BitbucketServerRestClient bitbucketServerRestClient;
71 private final ProjectDefaultVisibility projectDefaultVisibility;
72 private final ComponentUpdater componentUpdater;
73 private final ImportHelper importHelper;
74 private final ProjectKeyGenerator projectKeyGenerator;
76 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
78 private final DefaultBranchNameResolver defaultBranchNameResolver;
81 public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
82 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
83 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
84 DefaultBranchNameResolver defaultBranchNameResolver) {
85 this.dbClient = dbClient;
86 this.userSession = userSession;
87 this.bitbucketServerRestClient = bitbucketServerRestClient;
88 this.projectDefaultVisibility = projectDefaultVisibility;
89 this.componentUpdater = componentUpdater;
90 this.importHelper = importHelper;
91 this.projectKeyGenerator = projectKeyGenerator;
92 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
93 this.defaultBranchNameResolver = defaultBranchNameResolver;
97 public void define(WebService.NewController context) {
98 WebService.NewAction action = context.createAction("import_bitbucketserver_project")
99 .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
100 "Autoconfigure pull request decoration mechanism.<br/>" +
101 "Requires the 'Create Projects' permission")
107 action.createParam(PARAM_ALM_SETTING)
109 .setMaximumLength(200)
110 .setDescription("DevOps Platform setting key");
112 action.createParam(PARAM_PROJECT_KEY)
114 .setMaximumLength(200)
115 .setDescription("BitbucketServer project key");
117 action.createParam(PARAM_REPO_SLUG)
119 .setMaximumLength(200)
120 .setDescription("BitbucketServer repository slug");
123 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
124 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
127 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
128 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
133 public void handle(Request request, Response response) {
134 Projects.CreateWsResponse createResponse = doHandle(request);
135 writeProtobuf(createResponse, request, response);
138 private Projects.CreateWsResponse doHandle(Request request) {
139 importHelper.checkProvisionProjectPermission();
140 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
142 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
143 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
144 try (DbSession dbSession = dbClient.openSession(false)) {
146 String pat = getPat(dbSession, almSettingDto);
148 String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
149 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
151 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
152 Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
154 String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
156 ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName);
157 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
158 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
160 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
162 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
164 if (newCodeDefinitionType != null) {
165 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
166 Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
167 newCodeDefinitionType, newCodeDefinitionValue);
170 componentUpdater.commitAndIndex(dbSession, componentCreationData);
172 return toCreateResponse(projectDto);
176 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
177 String userUuid = importHelper.getUserUuid();
179 Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
180 return almPatDot.map(AlmPatDto::getPersonalAccessToken)
181 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing",
182 almSettingDto.getKey())));
185 private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
186 BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
187 Optional<Branch> defaultBranch = branches.findDefaultBranch();
188 return defaultBranch.map(Branch::getName).orElse(null);
191 private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
192 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
193 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug());
194 NewComponent newProject = newComponentBuilder()
195 .setKey(uniqueProjectKey)
196 .setName(repo.getName())
197 .setPrivate(visibility)
198 .setQualifier(PROJECT)
200 String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null;
201 String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null;
203 return componentUpdater.createWithoutCommit(dbSession, newProject, userUuid, userLogin, defaultBranchName);
206 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) {
207 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
208 .setAlmSettingUuid(almSettingDto.getUuid())
209 .setAlmRepo(repo.getProject().getKey())
210 .setAlmSlug(repo.getSlug())
211 .setProjectUuid(componentDto.getUuid())
213 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
214 componentDto.getName(), componentDto.getKey());