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.azure;
22 import java.util.Optional;
23 import javax.inject.Inject;
24 import org.sonar.alm.client.azure.AzureDevOpsHttpClient;
25 import org.sonar.alm.client.azure.GsonAzureRepo;
26 import org.sonar.api.server.ws.Request;
27 import org.sonar.api.server.ws.Response;
28 import org.sonar.api.server.ws.WebService;
29 import org.sonar.db.DbClient;
30 import org.sonar.db.DbSession;
31 import org.sonar.db.alm.pat.AlmPatDto;
32 import org.sonar.db.alm.setting.AlmSettingDto;
33 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
34 import org.sonar.db.component.BranchDto;
35 import org.sonar.db.project.ProjectDto;
36 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
37 import org.sonar.server.almintegration.ws.ImportHelper;
38 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
39 import org.sonar.server.component.ComponentCreationData;
40 import org.sonar.server.component.ComponentUpdater;
41 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
42 import org.sonar.server.project.DefaultBranchNameResolver;
43 import org.sonar.server.project.ProjectDefaultVisibility;
44 import org.sonar.server.user.UserSession;
45 import org.sonarqube.ws.Projects.CreateWsResponse;
47 import static java.util.Objects.requireNonNull;
48 import static org.sonar.api.resources.Qualifiers.PROJECT;
49 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
50 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
51 import static org.sonar.server.component.NewComponent.newComponentBuilder;
52 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
53 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
54 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
55 import static org.sonar.server.ws.WsUtils.writeProtobuf;
56 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
57 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
59 public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
61 private static final String PARAM_REPOSITORY_NAME = "repositoryName";
62 private static final String PARAM_PROJECT_NAME = "projectName";
64 private final DbClient dbClient;
65 private final UserSession userSession;
66 private final AzureDevOpsHttpClient azureDevOpsHttpClient;
67 private final ProjectDefaultVisibility projectDefaultVisibility;
68 private final ComponentUpdater componentUpdater;
69 private final ImportHelper importHelper;
70 private final ProjectKeyGenerator projectKeyGenerator;
71 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
72 private final DefaultBranchNameResolver defaultBranchNameResolver;
75 public ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient,
76 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
77 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
78 DefaultBranchNameResolver defaultBranchNameResolver) {
79 this.dbClient = dbClient;
80 this.userSession = userSession;
81 this.azureDevOpsHttpClient = azureDevOpsHttpClient;
82 this.projectDefaultVisibility = projectDefaultVisibility;
83 this.componentUpdater = componentUpdater;
84 this.importHelper = importHelper;
85 this.projectKeyGenerator = projectKeyGenerator;
86 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
87 this.defaultBranchNameResolver = defaultBranchNameResolver;
91 public void define(WebService.NewController context) {
92 WebService.NewAction action = context.createAction("import_azure_project")
93 .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
94 "Autoconfigure pull request decoration mechanism.<br/>" +
95 "Requires the 'Create Projects' permission")
101 action.createParam(PARAM_ALM_SETTING)
103 .setMaximumLength(200)
104 .setDescription("DevOps Platform setting key");
106 action.createParam(PARAM_PROJECT_NAME)
108 .setMaximumLength(200)
109 .setDescription("Azure project name");
111 action.createParam(PARAM_REPOSITORY_NAME)
113 .setMaximumLength(200)
114 .setDescription("Azure repository name");
116 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
117 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
120 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
121 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
126 public void handle(Request request, Response response) {
127 CreateWsResponse createResponse = doHandle(request);
128 writeProtobuf(createResponse, request, response);
131 private CreateWsResponse doHandle(Request request) {
132 importHelper.checkProvisionProjectPermission();
133 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
135 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
136 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
138 try (DbSession dbSession = dbClient.openSession(false)) {
140 String pat = getPat(dbSession, almSettingDto);
142 String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
143 String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
145 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
146 GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
148 ComponentCreationData componentCreationData = createProject(dbSession, repo);
149 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
150 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
151 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
153 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
155 if (newCodeDefinitionType != null) {
156 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
157 Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
158 newCodeDefinitionType, newCodeDefinitionValue);
161 componentUpdater.commitAndIndex(dbSession, componentCreationData);
163 return toCreateResponse(projectDto);
167 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
168 String userUuid = importHelper.getUserUuid();
169 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
170 return almPatDto.map(AlmPatDto::getPersonalAccessToken)
171 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
174 private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
175 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
176 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
177 return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
178 .setKey(uniqueProjectKey)
179 .setName(repo.getName())
180 .setPrivate(visibility)
181 .setQualifier(PROJECT)
183 userSession.isLoggedIn() ? userSession.getUuid() : null,
184 userSession.isLoggedIn() ? userSession.getLogin() : null,
185 repo.getDefaultBranchName());
188 private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
189 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
190 .setAlmSettingUuid(almSettingDto.getUuid())
191 .setAlmRepo(repo.getName())
192 .setAlmSlug(repo.getProject().getName())
193 .setProjectUuid(projectDto.getUuid())
195 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
196 projectDto.getName(), projectDto.getKey());