3 * Copyright (C) 2009-2024 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.Change;
30 import org.sonar.api.server.ws.Request;
31 import org.sonar.api.server.ws.Response;
32 import org.sonar.api.server.ws.WebService;
33 import org.sonar.db.DbClient;
34 import org.sonar.db.DbSession;
35 import org.sonar.db.alm.pat.AlmPatDto;
36 import org.sonar.db.alm.setting.ALM;
37 import org.sonar.db.alm.setting.AlmSettingDto;
38 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
39 import org.sonar.db.component.BranchDto;
40 import org.sonar.db.project.ProjectDto;
41 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
42 import org.sonar.server.almintegration.ws.ImportHelper;
43 import org.sonar.server.common.almintegration.ProjectKeyGenerator;
44 import org.sonar.server.common.component.ComponentCreationParameters;
45 import org.sonar.server.common.component.ComponentUpdater;
46 import org.sonar.server.common.component.NewComponent;
47 import org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver;
48 import org.sonar.server.component.ComponentCreationData;
49 import org.sonar.server.project.DefaultBranchNameResolver;
50 import org.sonar.server.project.ProjectDefaultVisibility;
51 import org.sonar.server.user.UserSession;
52 import org.sonarqube.ws.Projects;
54 import static java.util.Objects.requireNonNull;
55 import static org.sonar.api.resources.Qualifiers.PROJECT;
56 import static org.sonar.db.project.CreationMethod.getCreationMethod;
57 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
58 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
59 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
60 import static org.sonar.server.common.component.NewComponent.newComponentBuilder;
61 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
62 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
63 import static org.sonar.server.common.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
64 import static org.sonar.server.ws.WsUtils.writeProtobuf;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
66 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
68 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
70 private static final String PARAM_PROJECT_KEY = "projectKey";
71 private static final String PARAM_REPO_SLUG = "repositorySlug";
73 private final DbClient dbClient;
74 private final UserSession userSession;
75 private final BitbucketServerRestClient bitbucketServerRestClient;
76 private final ProjectDefaultVisibility projectDefaultVisibility;
77 private final ComponentUpdater componentUpdater;
78 private final ImportHelper importHelper;
79 private final ProjectKeyGenerator projectKeyGenerator;
81 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
83 private final DefaultBranchNameResolver defaultBranchNameResolver;
86 public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
87 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
88 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
89 DefaultBranchNameResolver defaultBranchNameResolver) {
90 this.dbClient = dbClient;
91 this.userSession = userSession;
92 this.bitbucketServerRestClient = bitbucketServerRestClient;
93 this.projectDefaultVisibility = projectDefaultVisibility;
94 this.componentUpdater = componentUpdater;
95 this.importHelper = importHelper;
96 this.projectKeyGenerator = projectKeyGenerator;
97 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
98 this.defaultBranchNameResolver = defaultBranchNameResolver;
102 public void define(WebService.NewController context) {
103 WebService.NewAction action = context.createAction("import_bitbucketserver_project")
104 .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
105 "Autoconfigure pull request decoration mechanism.<br/>" +
106 "Requires the 'Create Projects' permission")
111 new Change("10.5", "This endpoint is deprecated, please use its API v2 version /api/v2/dop-translation/bound-projects"),
112 new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for BitBucket Server", PARAM_ALM_SETTING)),
113 new Change("10.3", "Endpoint visibility change from internal to public"))
114 .setDeprecatedSince("10.5");
116 action.createParam(PARAM_ALM_SETTING)
117 .setMaximumLength(200)
118 .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one BitBucket Server integration.");
120 action.createParam(PARAM_PROJECT_KEY)
122 .setMaximumLength(200)
123 .setDescription("BitbucketServer project key");
125 action.createParam(PARAM_REPO_SLUG)
127 .setMaximumLength(200)
128 .setDescription("BitbucketServer repository slug");
131 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
132 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
135 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
136 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
141 public void handle(Request request, Response response) {
142 Projects.CreateWsResponse createResponse = doHandle(request);
143 writeProtobuf(createResponse, request, response);
146 private Projects.CreateWsResponse doHandle(Request request) {
147 importHelper.checkProvisionProjectPermission();
148 AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.BITBUCKET);
150 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
151 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
152 try (DbSession dbSession = dbClient.openSession(false)) {
154 String pat = getPat(dbSession, almSettingDto);
156 String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
157 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
159 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
160 Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
162 String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
164 ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName);
165 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
166 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
168 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
170 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
172 if (newCodeDefinitionType != null) {
173 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
174 Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
175 newCodeDefinitionType, newCodeDefinitionValue);
178 componentUpdater.commitAndIndex(dbSession, componentCreationData);
180 return toCreateResponse(projectDto);
184 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
185 String userUuid = importHelper.getUserUuid();
187 Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
188 return almPatDot.map(AlmPatDto::getPersonalAccessToken)
189 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing",
190 almSettingDto.getKey())));
193 private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
194 BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
195 Optional<Branch> defaultBranch = branches.findDefaultBranch();
196 return defaultBranch.map(Branch::getName).orElse(null);
199 private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
200 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
201 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug());
202 NewComponent newProject = newComponentBuilder()
203 .setKey(uniqueProjectKey)
204 .setName(repo.getName())
205 .setPrivate(visibility)
206 .setQualifier(PROJECT)
208 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
209 .newComponent(newProject)
210 .userUuid(userSession.getUuid())
211 .userLogin(userSession.getLogin())
212 .mainBranchName(defaultBranchName)
213 .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
215 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
218 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) {
219 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
220 .setAlmSettingUuid(almSettingDto.getUuid())
221 .setAlmRepo(repo.getProject().getKey())
222 .setAlmSlug(repo.getSlug())
223 .setProjectUuid(componentDto.getUuid())
225 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
226 componentDto.getName(), componentDto.getKey());