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.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.AlmSettingDto;
37 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
38 import org.sonar.db.component.BranchDto;
39 import org.sonar.db.project.ProjectDto;
40 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
41 import org.sonar.server.almintegration.ws.ImportHelper;
42 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
43 import org.sonar.server.component.ComponentCreationData;
44 import org.sonar.server.component.ComponentCreationParameters;
45 import org.sonar.server.component.ComponentUpdater;
46 import org.sonar.server.component.NewComponent;
47 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
48 import org.sonar.server.project.DefaultBranchNameResolver;
49 import org.sonar.server.project.ProjectDefaultVisibility;
50 import org.sonar.server.user.UserSession;
51 import org.sonarqube.ws.Projects;
53 import static java.util.Objects.requireNonNull;
54 import static org.sonar.api.resources.Qualifiers.PROJECT;
55 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
56 import static org.sonar.db.project.CreationMethod.getCreationMethod;
57 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
58 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
59 import static org.sonar.server.component.NewComponent.newComponentBuilder;
60 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
61 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
62 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
63 import static org.sonar.server.ws.WsUtils.writeProtobuf;
64 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
67 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
69 private static final String PARAM_PROJECT_KEY = "projectKey";
70 private static final String PARAM_REPO_SLUG = "repositorySlug";
72 private final DbClient dbClient;
73 private final UserSession userSession;
74 private final BitbucketServerRestClient bitbucketServerRestClient;
75 private final ProjectDefaultVisibility projectDefaultVisibility;
76 private final ComponentUpdater componentUpdater;
77 private final ImportHelper importHelper;
78 private final ProjectKeyGenerator projectKeyGenerator;
80 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
82 private final DefaultBranchNameResolver defaultBranchNameResolver;
85 public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
86 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
87 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
88 DefaultBranchNameResolver defaultBranchNameResolver) {
89 this.dbClient = dbClient;
90 this.userSession = userSession;
91 this.bitbucketServerRestClient = bitbucketServerRestClient;
92 this.projectDefaultVisibility = projectDefaultVisibility;
93 this.componentUpdater = componentUpdater;
94 this.importHelper = importHelper;
95 this.projectKeyGenerator = projectKeyGenerator;
96 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
97 this.defaultBranchNameResolver = defaultBranchNameResolver;
101 public void define(WebService.NewController context) {
102 WebService.NewAction action = context.createAction("import_bitbucketserver_project")
103 .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
104 "Autoconfigure pull request decoration mechanism.<br/>" +
105 "Requires the 'Create Projects' permission")
110 new Change("10.3", "Endpoint visibility change from internal to public"));
112 action.createParam(PARAM_ALM_SETTING)
114 .setMaximumLength(200)
115 .setDescription("DevOps Platform setting key");
117 action.createParam(PARAM_PROJECT_KEY)
119 .setMaximumLength(200)
120 .setDescription("BitbucketServer project key");
122 action.createParam(PARAM_REPO_SLUG)
124 .setMaximumLength(200)
125 .setDescription("BitbucketServer repository slug");
128 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
129 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
132 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
133 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
138 public void handle(Request request, Response response) {
139 Projects.CreateWsResponse createResponse = doHandle(request);
140 writeProtobuf(createResponse, request, response);
143 private Projects.CreateWsResponse doHandle(Request request) {
144 importHelper.checkProvisionProjectPermission();
145 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
147 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
148 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
149 try (DbSession dbSession = dbClient.openSession(false)) {
151 String pat = getPat(dbSession, almSettingDto);
153 String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
154 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
156 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
157 Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
159 String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
161 ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName);
162 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
163 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
165 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
167 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
169 if (newCodeDefinitionType != null) {
170 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
171 Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
172 newCodeDefinitionType, newCodeDefinitionValue);
175 componentUpdater.commitAndIndex(dbSession, componentCreationData);
177 return toCreateResponse(projectDto);
181 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
182 String userUuid = importHelper.getUserUuid();
184 Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
185 return almPatDot.map(AlmPatDto::getPersonalAccessToken)
186 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing",
187 almSettingDto.getKey())));
190 private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
191 BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
192 Optional<Branch> defaultBranch = branches.findDefaultBranch();
193 return defaultBranch.map(Branch::getName).orElse(null);
196 private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
197 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
198 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug());
199 NewComponent newProject = newComponentBuilder()
200 .setKey(uniqueProjectKey)
201 .setName(repo.getName())
202 .setPrivate(visibility)
203 .setQualifier(PROJECT)
205 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
206 .newComponent(newProject)
207 .userUuid(userSession.getUuid())
208 .userLogin(userSession.getLogin())
209 .mainBranchName(defaultBranchName)
210 .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
212 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
215 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) {
216 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
217 .setAlmSettingUuid(almSettingDto.getUuid())
218 .setAlmRepo(repo.getProject().getKey())
219 .setAlmSlug(repo.getSlug())
220 .setProjectUuid(componentDto.getUuid())
222 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
223 componentDto.getName(), componentDto.getKey());