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.project.ProjectDto;
35 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
36 import org.sonar.server.almintegration.ws.ImportHelper;
37 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
38 import org.sonar.server.component.ComponentCreationData;
39 import org.sonar.server.component.ComponentUpdater;
40 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
41 import org.sonar.server.project.DefaultBranchNameResolver;
42 import org.sonar.server.project.ProjectDefaultVisibility;
43 import org.sonar.server.user.UserSession;
44 import org.sonarqube.ws.Projects.CreateWsResponse;
46 import static java.util.Objects.requireNonNull;
47 import static org.sonar.api.resources.Qualifiers.PROJECT;
48 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
49 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
50 import static org.sonar.server.component.NewComponent.newComponentBuilder;
51 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
52 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
53 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
54 import static org.sonar.server.ws.WsUtils.writeProtobuf;
55 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
56 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
58 public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
60 private static final String PARAM_REPOSITORY_NAME = "repositoryName";
61 private static final String PARAM_PROJECT_NAME = "projectName";
63 private final DbClient dbClient;
64 private final UserSession userSession;
65 private final AzureDevOpsHttpClient azureDevOpsHttpClient;
66 private final ProjectDefaultVisibility projectDefaultVisibility;
67 private final ComponentUpdater componentUpdater;
68 private final ImportHelper importHelper;
69 private final ProjectKeyGenerator projectKeyGenerator;
70 private final NewCodeDefinitionResolver newCodeDefinitionResolver;
71 private final DefaultBranchNameResolver defaultBranchNameResolver;
74 public ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient,
75 ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
76 ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
77 DefaultBranchNameResolver defaultBranchNameResolver) {
78 this.dbClient = dbClient;
79 this.userSession = userSession;
80 this.azureDevOpsHttpClient = azureDevOpsHttpClient;
81 this.projectDefaultVisibility = projectDefaultVisibility;
82 this.componentUpdater = componentUpdater;
83 this.importHelper = importHelper;
84 this.projectKeyGenerator = projectKeyGenerator;
85 this.newCodeDefinitionResolver = newCodeDefinitionResolver;
86 this.defaultBranchNameResolver = defaultBranchNameResolver;
90 public void define(WebService.NewController context) {
91 WebService.NewAction action = context.createAction("import_azure_project")
92 .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
93 "Autoconfigure pull request decoration mechanism.<br/>" +
94 "Requires the 'Create Projects' permission")
100 action.createParam(PARAM_ALM_SETTING)
102 .setMaximumLength(200)
103 .setDescription("DevOps Platform setting key");
105 action.createParam(PARAM_PROJECT_NAME)
107 .setMaximumLength(200)
108 .setDescription("Azure project name");
110 action.createParam(PARAM_REPOSITORY_NAME)
112 .setMaximumLength(200)
113 .setDescription("Azure repository name");
115 action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
116 .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
119 action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
120 .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
125 public void handle(Request request, Response response) {
126 CreateWsResponse createResponse = doHandle(request);
127 writeProtobuf(createResponse, request, response);
130 private CreateWsResponse doHandle(Request request) {
131 importHelper.checkProvisionProjectPermission();
132 AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
134 String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
135 String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
137 try (DbSession dbSession = dbClient.openSession(false)) {
139 String pat = getPat(dbSession, almSettingDto);
141 String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
142 String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
144 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
145 GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
147 ComponentCreationData componentCreationData = createProject(dbSession, repo);
148 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
149 populatePRSetting(dbSession, repo, projectDto, almSettingDto);
151 checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
153 if (newCodeDefinitionType != null) {
154 newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(),
155 Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
156 newCodeDefinitionType, newCodeDefinitionValue);
159 componentUpdater.commitAndIndex(dbSession, componentCreationData.mainBranchComponent());
161 return toCreateResponse(projectDto);
165 private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
166 String userUuid = importHelper.getUserUuid();
167 Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
168 return almPatDto.map(AlmPatDto::getPersonalAccessToken)
169 .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
172 private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
173 boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
174 String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
175 return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
176 .setKey(uniqueProjectKey)
177 .setName(repo.getName())
178 .setPrivate(visibility)
179 .setQualifier(PROJECT)
181 userSession.isLoggedIn() ? userSession.getUuid() : null,
182 userSession.isLoggedIn() ? userSession.getLogin() : null,
183 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());