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.permission.ws.template;
22 import java.util.Collection;
23 import java.util.HashSet;
24 import java.util.List;
26 import java.util.stream.Collectors;
27 import javax.annotation.CheckForNull;
28 import javax.annotation.Nullable;
29 import org.sonar.api.resources.Qualifiers;
30 import org.sonar.api.resources.ResourceTypes;
31 import org.sonar.api.server.ws.Change;
32 import org.sonar.api.server.ws.Request;
33 import org.sonar.api.server.ws.Response;
34 import org.sonar.api.server.ws.WebService;
35 import org.sonar.api.server.ws.WebService.Param;
36 import org.sonar.core.i18n.I18n;
37 import org.sonar.db.DatabaseUtils;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.component.ComponentDto;
41 import org.sonar.db.component.ComponentQuery;
42 import org.sonar.db.entity.EntityDto;
43 import org.sonar.db.permission.template.PermissionTemplateDto;
44 import org.sonar.server.management.ManagedProjectService;
45 import org.sonar.server.permission.PermissionTemplateService;
46 import org.sonar.server.permission.ws.PermissionWsSupport;
47 import org.sonar.server.permission.ws.PermissionsWsAction;
48 import org.sonar.server.permission.ws.WsParameters;
49 import org.sonar.server.project.Visibility;
50 import org.sonar.server.user.UserSession;
52 import static java.lang.String.format;
53 import static java.util.Collections.singleton;
54 import static java.util.Objects.requireNonNull;
55 import static java.util.Optional.ofNullable;
56 import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
57 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
58 import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
59 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
60 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
61 import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
62 import static org.sonar.server.ws.WsParameterBuilder.createRootQualifiersParameter;
63 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
64 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
66 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
67 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
68 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
69 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
71 public class BulkApplyTemplateAction implements PermissionsWsAction {
73 private final DbClient dbClient;
74 private final UserSession userSession;
75 private final PermissionTemplateService permissionTemplateService;
76 private final PermissionWsSupport wsSupport;
77 private final I18n i18n;
78 private final ResourceTypes resourceTypes;
79 private final ManagedProjectService managedProjectService;
81 public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService, PermissionWsSupport wsSupport, I18n i18n,
82 ResourceTypes resourceTypes, ManagedProjectService managedProjectService) {
83 this.dbClient = dbClient;
84 this.userSession = userSession;
85 this.permissionTemplateService = permissionTemplateService;
86 this.wsSupport = wsSupport;
88 this.resourceTypes = resourceTypes;
89 this.managedProjectService = managedProjectService;
93 public void define(WebService.NewController context) {
94 WebService.NewAction action = context.createAction("bulk_apply_template")
95 .setDescription("Apply a permission template to several components. Managed projects will be ignored.<br />" +
96 "The template id or name must be provided.<br />" +
97 "Requires the following permission: 'Administer System'.")
100 .setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
103 action.createParam(Param.TEXT_QUERY)
104 .setDescription("Limit search to: <ul>" +
105 "<li>project names that contain the supplied string</li>" +
106 "<li>project keys that are exactly the same as the supplied string</li>" +
108 .setExampleValue("apac");
110 createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
111 .setDefaultValue(Qualifiers.PROJECT);
113 WsParameters.createTemplateParameters(action);
116 .createParam(PARAM_PROJECTS)
117 .setDescription("Comma-separated list of project keys")
119 // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
120 // Restricting size of HTTP parameter allows to not fail with SQL error
121 .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
122 .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
124 action.createParam(PARAM_VISIBILITY)
125 .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
126 "If no visibility is specified, the default project visibility will be used.",
127 Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
131 .setPossibleValues(Visibility.getLabels());
133 action.createParam(PARAM_ANALYZED_BEFORE)
134 .setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
135 "Either a date (server timezone) or datetime can be provided.")
137 .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
139 action.createParam(PARAM_ON_PROVISIONED_ONLY)
140 .setDescription("Filter the projects that are provisioned")
141 .setBooleanPossibleValues()
142 .setDefaultValue("false")
147 public void handle(Request request, Response response) throws Exception {
148 doHandle(toBulkApplyTemplateWsRequest(request));
149 response.noContent();
152 private void doHandle(BulkApplyTemplateRequest request) {
153 try (DbSession dbSession = dbClient.openSession(false)) {
154 PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
155 request.getTemplateId(), request.getTemplateName()));
156 checkGlobalAdmin(userSession);
158 ComponentQuery componentQuery = buildDbQuery(request);
159 List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
161 Set<String> entityUuids = components.stream()
162 .map(ComponentDto::getKey)
163 .collect(Collectors.toSet());
164 List<EntityDto> entities = dbClient.entityDao().selectByKeys(dbSession, entityUuids).stream()
165 .filter(entity -> !managedProjectService.isProjectManaged(dbSession, entity.getUuid()))
168 permissionTemplateService.applyAndCommit(dbSession, template, entities);
172 private static BulkApplyTemplateRequest toBulkApplyTemplateWsRequest(Request request) {
173 return new BulkApplyTemplateRequest()
174 .setTemplateId(request.param(PARAM_TEMPLATE_ID))
175 .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
176 .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
177 .setQuery(request.param(Param.TEXT_QUERY))
178 .setVisibility(request.param(PARAM_VISIBILITY))
179 .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
180 .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
181 .setProjects(request.paramAsStrings(PARAM_PROJECTS));
184 private static ComponentQuery buildDbQuery(BulkApplyTemplateRequest request) {
185 Collection<String> qualifiers = request.getQualifiers();
186 ComponentQuery.Builder query = ComponentQuery.builder()
187 .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
189 ofNullable(request.getQuery()).ifPresent(q -> {
190 query.setNameOrKeyQuery(q);
191 query.setPartialMatchOnKey(true);
193 ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
194 ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
195 query.setOnProvisionedOnly(request.isOnProvisionedOnly());
196 ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
198 return query.build();
201 private static class BulkApplyTemplateRequest {
202 private String templateId;
203 private String templateName;
204 private String query;
205 private Collection<String> qualifiers = singleton(Qualifiers.PROJECT);
206 private String visibility;
207 private String analyzedBefore;
208 private boolean onProvisionedOnly = false;
209 private Collection<String> projects;
212 public String getTemplateId() {
216 public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
217 this.templateId = templateId;
222 public String getTemplateName() {
226 public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
227 this.templateName = templateName;
232 public String getQuery() {
236 public BulkApplyTemplateRequest setQuery(@Nullable String query) {
241 public Collection<String> getQualifiers() {
245 public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
246 this.qualifiers = requireNonNull(qualifiers);
251 public String getVisibility() {
255 public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
256 this.visibility = visibility;
261 public String getAnalyzedBefore() {
262 return analyzedBefore;
265 public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
266 this.analyzedBefore = analyzedBefore;
270 public boolean isOnProvisionedOnly() {
271 return onProvisionedOnly;
274 public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
275 this.onProvisionedOnly = onProvisionedOnly;
280 public Collection<String> getProjects() {
284 public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
285 this.projects = projects;