3 * Copyright (C) 2009-2021 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 org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient;
25 import org.sonar.alm.client.bitbucketserver.Branch;
26 import org.sonar.alm.client.bitbucketserver.BranchesList;
27 import org.sonar.alm.client.bitbucketserver.Repository;
28 import org.sonar.api.server.ws.Request;
29 import org.sonar.api.server.ws.Response;
30 import org.sonar.api.server.ws.WebService;
31 import org.sonar.db.DbClient;
32 import org.sonar.db.DbSession;
33 import org.sonar.db.alm.pat.AlmPatDto;
34 import org.sonar.db.alm.setting.AlmSettingDto;
35 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
36 import org.sonar.db.component.ComponentDto;
37 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
38 import org.sonar.server.almintegration.ws.ImportHelper;
39 import org.sonar.server.component.ComponentUpdater;
40 import org.sonar.server.component.NewComponent;
41 import org.sonar.server.project.ProjectDefaultVisibility;
42 import org.sonar.server.user.UserSession;
43 import org.sonarqube.ws.Projects;
45 import static java.util.Objects.requireNonNull;
46 import static org.sonar.api.resources.Qualifiers.PROJECT;
47 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
48 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
49 import static org.sonar.server.component.NewComponent.newComponentBuilder;
50 import static org.sonar.server.ws.WsUtils.writeProtobuf;
52 public class ImportBitbucketServerProjectAction implements AlmIntegrationsWsAction {
54 private static final String PARAM_PROJECT_KEY = "projectKey";
55 private static final String PARAM_REPO_SLUG = "repositorySlug";
57 private final DbClient dbClient;
58 private final UserSession userSession;
59 private final BitbucketServerRestClient bitbucketServerRestClient;
60 private final ProjectDefaultVisibility projectDefaultVisibility;
61 private final ComponentUpdater componentUpdater;
62 private final ImportHelper importHelper;
64 public ImportBitbucketServerProjectAction(DbClient dbClient, UserSession userSession, BitbucketServerRestClient bitbucketServerRestClient,
65 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
66 ImportHelper importHelper) {
67 this.dbClient = dbClient;
68 this.userSession = userSession;
69 this.bitbucketServerRestClient = bitbucketServerRestClient;
70 this.projectDefaultVisibility = projectDefaultVisibility;
71 this.componentUpdater = componentUpdater;
72 this.importHelper = importHelper;
76 public void define(WebService.NewController context) {
77 WebService.NewAction action = context.createAction("import_bitbucketserver_project")
78 .setDescription("Create a SonarQube project with the information from the provided BitbucketServer project.<br/>" +
79 "Autoconfigure pull request decoration mechanism.<br/>" +
80 "Requires the 'Create Projects' permission")
86 action.createParam(PARAM_ALM_SETTING)
88 .setMaximumLength(200)
89 .setDescription("ALM setting key");
91 action.createParam(PARAM_PROJECT_KEY)
93 .setMaximumLength(200)
94 .setDescription("BitbucketServer project key");
96 action.createParam(PARAM_REPO_SLUG)
98 .setMaximumLength(200)
99 .setDescription("BitbucketServer repository slug");
103 public void handle(Request request, Response response) {
104 Projects.CreateWsResponse createResponse = doHandle(request);
105 writeProtobuf(createResponse, request, response);
108 private Projects.CreateWsResponse doHandle(Request request) {
109 importHelper.checkProvisionProjectPermission();
110 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
111 String userUuid = importHelper.getUserUuid();
112 try (DbSession dbSession = dbClient.openSession(false)) {
114 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
115 String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken)
116 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
118 String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
119 String repoSlug = request.mandatoryParam(PARAM_REPO_SLUG);
121 String url = requireNonNull(almSettingDto.getUrl(), "ALM url cannot be null");
122 Repository repo = bitbucketServerRestClient.getRepo(url, pat, projectKey, repoSlug);
124 String defaultBranchName = getDefaultBranchName(pat, projectKey, repoSlug, url);
126 ComponentDto componentDto = createProject(dbSession, repo, defaultBranchName);
128 populatePRSetting(dbSession, repo, componentDto, almSettingDto);
130 componentUpdater.commitAndIndex(dbSession, componentDto);
132 return toCreateResponse(componentDto);
136 private String getDefaultBranchName(String pat, String projectKey, String repoSlug, String url) {
137 BranchesList branches = bitbucketServerRestClient.getBranches(url, pat, projectKey, repoSlug);
138 Optional<Branch> defaultBranch = branches.findDefaultBranch();
139 return defaultBranch.map(Branch::getName).orElse(null);
142 private ComponentDto createProject(DbSession dbSession, Repository repo, @Nullable String defaultBranchName) {
143 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
144 NewComponent newProject = newComponentBuilder()
145 .setKey(repo.getProject().getKey() + "_" + repo.getSlug())
146 .setName(repo.getName())
147 .setPrivate(visibility)
148 .setQualifier(PROJECT)
150 String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null;
151 String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null;
153 return componentUpdater.createWithoutCommit(dbSession, newProject, userUuid, userLogin, defaultBranchName, p -> {});
156 private void populatePRSetting(DbSession dbSession, Repository repo, ComponentDto componentDto, AlmSettingDto almSettingDto) {
157 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
158 .setAlmSettingUuid(almSettingDto.getUuid())
159 .setAlmRepo(repo.getProject().getKey())
160 .setAlmSlug(repo.getSlug())
161 .setProjectUuid(componentDto.uuid())
163 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
164 componentDto.name(), componentDto.getKey());