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.bitbucketcloud;
22 import java.util.List;
24 import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient;
25 import java.util.Optional;
27 import java.util.function.BinaryOperator;
28 import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository;
29 import org.sonar.alm.client.bitbucket.bitbucketcloud.RepositoryList;
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.project.ProjectDto;
39 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
40 import org.sonar.server.exceptions.NotFoundException;
41 import org.sonar.server.user.UserSession;
42 import org.sonarqube.ws.AlmIntegrations.BBCRepo;
43 import org.sonarqube.ws.AlmIntegrations.SearchBitbucketcloudReposWsResponse;
44 import org.sonarqube.ws.Common.Paging;
46 import static java.util.Objects.requireNonNull;
47 import static java.util.Optional.ofNullable;
48 import static java.util.stream.Collectors.toList;
49 import static java.util.stream.Collectors.toMap;
50 import static java.util.stream.Collectors.toSet;
51 import static org.sonar.api.server.ws.WebService.Param.PAGE;
52 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
53 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
54 import static org.sonar.server.ws.WsUtils.writeProtobuf;
56 public class SearchBitbucketCloudReposAction implements AlmIntegrationsWsAction {
58 private static final BinaryOperator<String> resolveCollisionByNaturalOrder = (a, b) -> a.compareTo(b) < 0 ? a : b;
59 private static final String PARAM_ALM_SETTING = "almSetting";
60 private static final String PARAM_REPO_NAME = "repositoryName";
61 private static final int DEFAULT_PAGE_SIZE = 20;
62 private static final int MAX_PAGE_SIZE = 100;
64 private final DbClient dbClient;
65 private final UserSession userSession;
66 private final BitbucketCloudRestClient bitbucketCloudRestClient;
68 public SearchBitbucketCloudReposAction(DbClient dbClient, UserSession userSession,
69 BitbucketCloudRestClient bitbucketCloudRestClient) {
70 this.dbClient = dbClient;
71 this.userSession = userSession;
72 this.bitbucketCloudRestClient = bitbucketCloudRestClient;
76 public void define(WebService.NewController context) {
77 WebService.NewAction action = context.createAction("search_bitbucketcloud_repos")
78 .setDescription("Search the Bitbucket Cloud repositories<br/>" +
79 "Requires the 'Create Projects' permission")
82 .setResponseExample(getClass().getResource("example-search_bitbucketcloud_repos.json"))
85 action.createParam(PARAM_ALM_SETTING)
87 .setMaximumLength(200)
88 .setDescription("ALM setting key");
90 action.createParam(PARAM_REPO_NAME)
92 .setMaximumLength(200)
93 .setDescription("Repository name filter");
95 action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
99 public void handle(Request request, Response response) {
100 SearchBitbucketcloudReposWsResponse wsResponse = doHandle(request);
101 writeProtobuf(wsResponse, request, response);
104 private SearchBitbucketcloudReposWsResponse doHandle(Request request) {
105 userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
106 String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
107 String repoName = request.param(PARAM_REPO_NAME);
108 int page = request.mandatoryParamAsInt(PAGE);
109 int pageSize = request.mandatoryParamAsInt(PAGE_SIZE);
111 try (DbSession dbSession = dbClient.openSession(false)) {
112 AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey)
113 .orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey)));
115 String workspace = ofNullable(almSettingDto.getAppId())
116 .orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey())));
117 String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null");
118 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
120 String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
122 RepositoryList repositoryList = bitbucketCloudRestClient.searchRepos(pat, workspace, repoName, page, pageSize);
124 Map<String, String> sqProjectKeyByRepoSlug = getSqProjectKeyByRepoSlug(dbSession, almSettingDto, repositoryList.getValues());
126 List<BBCRepo> bbcRepos = repositoryList.getValues().stream()
127 .map(repository -> toBBCRepo(repository, workspace, sqProjectKeyByRepoSlug))
130 SearchBitbucketcloudReposWsResponse.Builder builder = SearchBitbucketcloudReposWsResponse.newBuilder()
131 .setIsLastPage(repositoryList.getNext() == null)
132 .setPaging(Paging.newBuilder().setPageIndex(page).setPageSize(pageSize).build())
133 .addAllRepositories(bbcRepos);
134 return builder.build();
138 private Map<String, String> getSqProjectKeyByRepoSlug(DbSession dbSession, AlmSettingDto almSettingDto, List<Repository> repositories) {
139 Set<String> repoSlugs = repositories.stream().map(Repository::getSlug).collect(toSet());
141 List<ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao().selectByAlmSettingAndRepos(dbSession, almSettingDto, repoSlugs);
143 Map<String, String> repoSlugByProjectUuid = projectAlmSettingDtos.stream()
144 .collect(toMap(ProjectAlmSettingDto::getProjectUuid, ProjectAlmSettingDto::getAlmRepo));
146 return dbClient.projectDao().selectByUuids(dbSession, repoSlugByProjectUuid.keySet())
148 .collect(toMap(p -> repoSlugByProjectUuid.get(p.getUuid()), ProjectDto::getKey, resolveCollisionByNaturalOrder));
151 private static BBCRepo toBBCRepo(Repository gsonBBCRepo, String workspace, Map<String, String> sqProjectKeyByRepoSlug) {
152 BBCRepo.Builder builder = BBCRepo.newBuilder()
153 .setSlug(gsonBBCRepo.getSlug())
154 .setUuid(gsonBBCRepo.getUuid())
155 .setName(gsonBBCRepo.getName())
156 .setWorkspace(workspace)
157 .setProjectKey(gsonBBCRepo.getProject().getKey());
159 String sqProjectKey = sqProjectKeyByRepoSlug.get(gsonBBCRepo.getSlug());
160 ofNullable(sqProjectKey).ifPresent(builder::setSqProjectKey);
162 return builder.build();