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.Change;
27 import org.sonar.api.server.ws.Request;
28 import org.sonar.api.server.ws.Response;
29 import org.sonar.api.server.ws.WebService;
30 import org.sonar.db.DbClient;
31 import org.sonar.db.DbSession;
32 import org.sonar.db.alm.pat.AlmPatDto;
33 import org.sonar.db.alm.setting.AlmSettingDto;
34 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
35 import org.sonar.db.component.BranchDto;
36 import org.sonar.db.project.ProjectDto;
37 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
38 import org.sonar.server.almintegration.ws.ImportHelper;
39 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
40 import org.sonar.server.component.ComponentCreationData;
41 import org.sonar.server.component.ComponentCreationParameters;
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.CreateWsResponse;
50 import static java.util.Objects.requireNonNull;
51 import static org.sonar.api.resources.Qualifiers.PROJECT;
52 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
53 import static org.sonar.db.project.CreationMethod.getCreationMethod;
54 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
55 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
56 import static org.sonar.server.component.NewComponent.newComponentBuilder;
57 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
58 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
59 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
60 import static org.sonar.server.ws.WsUtils.writeProtobuf;
61 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
62 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
64 public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
66 private static final String PARAM_REPOSITORY_NAME = "repositoryName";
67 private static final String PARAM_PROJECT_NAME = "projectName";
69 private final DbClient dbClient;
70 private final UserSession userSession;
71 private final AzureDevOpsHttpClient azureDevOpsHttpClient;
72 private final ProjectDefaultVisibility projectDefaultVisibility;
73 private final ComponentUpdater componentUpdater;
74 private final ImportHelper importHelper;
75 private final ProjectKeyGenerator projectKeyGenerator;
76 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
77 private final DefaultBranchNameResolver defaultBranchNameResolver;
80 public ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient,
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.azureDevOpsHttpClient = azureDevOpsHttpClient;
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_azure_project")
98 .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
99 "Autoconfigure pull request decoration mechanism.<br/>" +
100 "Requires the 'Create Projects' permission")
105 new Change("10.3", "Endpoint visibility change from internal to public"));
107 action.createParam(PARAM_ALM_SETTING)
109 .setMaximumLength(200)
110 .setDescription("DevOps Platform setting key");
112 action.createParam(PARAM_PROJECT_NAME)
114 .setMaximumLength(200)
115 .setDescription("Azure project name");
117 action.createParam(PARAM_REPOSITORY_NAME)
119 .setMaximumLength(200)
120 .setDescription("Azure repository name");
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 CreateWsResponse createResponse = doHandle(request);
134 writeProtobuf(createResponse, request, response);
137 private 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);
144 try (DbSession dbSession = dbClient.openSession(false)) {
146 String pat = getPat(dbSession, almSettingDto);
148 String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
149 String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
151 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
152 GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
154 ComponentCreationData componentCreationData = createProject(dbSession, repo);
155 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
156 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
157 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
159 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
161 if (newCodeDefinitionType != null) {
162 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
163 Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
164 newCodeDefinitionType, newCodeDefinitionValue);
167 componentUpdater.commitAndIndex(dbSession, componentCreationData);
169 return toCreateResponse(projectDto);
173 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
174 String userUuid = importHelper.getUserUuid();
175 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
176 return almPatDto.map(AlmPatDto::getPersonalAccessToken)
177 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
180 private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
181 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
182 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
183 NewComponent newProject = newComponentBuilder()
184 .setKey(uniqueProjectKey)
185 .setName(repo.getName())
186 .setPrivate(visibility)
187 .setQualifier(PROJECT)
189 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
190 .newComponent(newProject)
191 .userUuid(userSession.getUuid())
192 .userLogin(userSession.getLogin())
193 .mainBranchName(repo.getDefaultBranchName())
194 .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
196 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
199 private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
200 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
201 .setAlmSettingUuid(almSettingDto.getUuid())
202 .setAlmRepo(repo.getName())
203 .setAlmSlug(repo.getProject().getName())
204 .setProjectUuid(projectDto.getUuid())
206 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
207 projectDto.getName(), projectDto.getKey());