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.project.ProjectDto;
38 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
39 import org.sonar.server.almintegration.ws.ImportHelper;
40 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
41 import org.sonar.server.component.ComponentCreationData;
42 import org.sonar.server.component.ComponentUpdater;
43 import org.sonar.server.component.NewComponent;
44 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
45 import org.sonar.server.project.DefaultBranchNameResolver;
46 import org.sonar.server.project.ProjectDefaultVisibility;
47 import org.sonar.server.user.UserSession;
48 import org.sonarqube.ws.Projects;
50 import static java.util.Objects.requireNonNull;
51 import static org.sonar.api.resources.Qualifiers.PROJECT;
52 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
53 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
54 import static org.sonar.server.component.NewComponent.newComponentBuilder;
55 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
56 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
57 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
58 import static org.sonar.server.ws.WsUtils.writeProtobuf;
59 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
60 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
62 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
64 private static final String PARAM_PROJECT_KEY = "projectKey";
65 private static final String PARAM_REPO_SLUG = "repositorySlug";
67 private final DbClient dbClient;
68 private final UserSession userSession;
69 private final BitbucketServerRestClient bitbucketServerRestClient;
70 private final ProjectDefaultVisibility projectDefaultVisibility;
71 private final ComponentUpdater componentUpdater;
72 private final ImportHelper importHelper;
73 private final ProjectKeyGenerator projectKeyGenerator;
75 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
77 private final DefaultBranchNameResolver defaultBranchNameResolver;
80 public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
81 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
82 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
83 DefaultBranchNameResolver defaultBranchNameResolver) {
84 this.dbClient = dbClient;
85 this.userSession = userSession;
86 this.bitbucketServerRestClient = bitbucketServerRestClient;
87 this.projectDefaultVisibility = projectDefaultVisibility;
88 this.componentUpdater = componentUpdater;
89 this.importHelper = importHelper;
90 this.projectKeyGenerator = projectKeyGenerator;
91 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
92 this.defaultBranchNameResolver = defaultBranchNameResolver;
96 public void define(WebService.NewController context) {
97 WebService.NewAction action = context.createAction("import_bitbucketserver_project")
98 .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
99 "Autoconfigure pull request decoration mechanism.<br/>" +
100 "Requires the 'Create Projects' permission")
106 action.createParam(PARAM_ALM_SETTING)
108 .setMaximumLength(200)
109 .setDescription("DevOps Platform setting key");
111 action.createParam(PARAM_PROJECT_KEY)
113 .setMaximumLength(200)
114 .setDescription("BitbucketServer project key");
116 action.createParam(PARAM_REPO_SLUG)
118 .setMaximumLength(200)
119 .setDescription("BitbucketServer repository slug");
122 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
123 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
126 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
127 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
132 public void handle(Request request, Response response) {
133 Projects.CreateWsResponse createResponse = doHandle(request);
134 writeProtobuf(createResponse, request, response);
137 private Projects.CreateWsResponse doHandle(Request request) {
138 importHelper.checkProvisionProjectPermission();
139 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
141 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
142 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
143 try (DbSession dbSession = dbClient.openSession(false)) {
145 String pat = getPat(dbSession, almSettingDto);
147 String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
148 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
150 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
151 Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
153 String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
155 ComponentCreationData componentCreationData = createProject(dbSession, repo, defaultBranchName);
156 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
158 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
160 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
162 if (newCodeDefinitionType != null) {
163 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(),
164 Optional.ofNullable(defaultBranchName).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
165 newCodeDefinitionType, newCodeDefinitionValue);
168 componentUpdater.commitAndIndex(dbSession, componentCreationData);
170 return toCreateResponse(projectDto);
174 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
175 String userUuid = importHelper.getUserUuid();
177 Optional<AlmPatDto> almPatDot = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
178 return almPatDot.map(AlmPatDto::getPersonalAccessToken)
179 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing",
180 almSettingDto.getKey())));
183 private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
184 BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
185 Optional<Branch> defaultBranch = branches.findDefaultBranch();
186 return defaultBranch.map(Branch::getName).orElse(null);
189 private ComponentCreationData createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
190 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
191 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getKey(), repo.getSlug());
192 NewComponent newProject = newComponentBuilder()
193 .setKey(uniqueProjectKey)
194 .setName(repo.getName())
195 .setPrivate(visibility)
196 .setQualifier(PROJECT)
198 String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null;
199 String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null;
201 return componentUpdater.createWithoutCommit(dbSession, newProject, userUuid, userLogin, defaultBranchName);
204 private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto componentDto, AlmSettingDto almSettingDto) {
205 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
206 .setAlmSettingUuid(almSettingDto.getUuid())
207 .setAlmRepo(repo.getProject().getKey())
208 .setAlmSlug(repo.getSlug())
209 .setProjectUuid(componentDto.getUuid())
211 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
212 componentDto.getName(), componentDto.getKey());