]> source.dussan.org Git - sonarqube.git/blob
b0c5def74279a54d186c5a0b32f6e405bfa7725a
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.server.almintegration.ws.bitbucketcloud;
21
22 import java.util.List;
23 import java.util.Map;
24 import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient;
25 import java.util.Optional;
26 import java.util.Set;
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;
45
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;
55
56 public class SearchBitbucketCloudReposAction implements AlmIntegrationsWsAction {
57
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;
63
64   private final DbClient dbClient;
65   private final UserSession userSession;
66   private final BitbucketCloudRestClient bitbucketCloudRestClient;
67
68   public SearchBitbucketCloudReposAction(DbClient dbClient, UserSession userSession,
69     BitbucketCloudRestClient bitbucketCloudRestClient) {
70     this.dbClient = dbClient;
71     this.userSession = userSession;
72     this.bitbucketCloudRestClient = bitbucketCloudRestClient;
73   }
74
75   @Override
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")
80       .setPost(false)
81       .setSince("9.0")
82       .setResponseExample(getClass().getResource("example-search_bitbucketcloud_repos.json"))
83       .setHandler(this);
84
85     action.createParam(PARAM_ALM_SETTING)
86       .setRequired(true)
87       .setMaximumLength(200)
88       .setDescription("ALM setting key");
89
90     action.createParam(PARAM_REPO_NAME)
91       .setRequired(false)
92       .setMaximumLength(200)
93       .setDescription("Repository name filter");
94
95     action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
96   }
97
98   @Override
99   public void handle(Request request, Response response) {
100     SearchBitbucketcloudReposWsResponse wsResponse = doHandle(request);
101     writeProtobuf(wsResponse, request, response);
102   }
103
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);
110
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)));
114
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);
119
120       String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
121
122       RepositoryList repositoryList = bitbucketCloudRestClient.searchRepos(pat, workspace, repoName, page, pageSize);
123
124       Map<String, String> sqProjectKeyByRepoSlug = getSqProjectKeyByRepoSlug(dbSession, almSettingDto, repositoryList.getValues());
125
126       List<BBCRepo> bbcRepos = repositoryList.getValues().stream()
127         .map(repository -> toBBCRepo(repository, workspace, sqProjectKeyByRepoSlug))
128         .collect(toList());
129
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();
135     }
136   }
137
138   private Map<String, String> getSqProjectKeyByRepoSlug(DbSession dbSession, AlmSettingDto almSettingDto, List<Repository> repositories) {
139     Set<String> repoSlugs = repositories.stream().map(Repository::getSlug).collect(toSet());
140
141     List<ProjectAlmSettingDto> projectAlmSettingDtos = dbClient.projectAlmSettingDao().selectByAlmSettingAndRepos(dbSession, almSettingDto, repoSlugs);
142
143     Map<String, String> repoSlugByProjectUuid = projectAlmSettingDtos.stream()
144       .collect(toMap(ProjectAlmSettingDto::getProjectUuid, ProjectAlmSettingDto::getAlmRepo));
145
146     return dbClient.projectDao().selectByUuids(dbSession, repoSlugByProjectUuid.keySet())
147       .stream()
148       .collect(toMap(p -> repoSlugByProjectUuid.get(p.getUuid()), ProjectDto::getKey, resolveCollisionByNaturalOrder));
149   }
150
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());
158
159     String sqProjectKey = sqProjectKeyByRepoSlug.get(gsonBBCRepo.getSlug());
160     ofNullable(sqProjectKey).ifPresent(builder::setSqProjectKey);
161
162     return builder.build();
163   }
164
165 }