3 * Copyright (C) 2009-2021 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;
25 import javax.annotation.CheckForNull;
26 import javax.annotation.Nullable;
27 import org.sonar.api.resources.Qualifiers;
28 import org.sonar.api.resources.ResourceTypes;
29 import org.sonar.api.server.ws.Change;
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.api.server.ws.WebService.Param;
34 import org.sonar.core.i18n.I18n;
35 import org.sonar.db.DatabaseUtils;
36 import org.sonar.db.DbClient;
37 import org.sonar.db.DbSession;
38 import org.sonar.db.component.ComponentDto;
39 import org.sonar.db.component.ComponentQuery;
40 import org.sonar.db.permission.template.PermissionTemplateDto;
41 import org.sonar.server.permission.PermissionTemplateService;
42 import org.sonar.server.permission.ws.PermissionWsSupport;
43 import org.sonar.server.permission.ws.PermissionsWsAction;
44 import org.sonar.server.permission.ws.WsParameters;
45 import org.sonar.server.project.Visibility;
46 import org.sonar.server.user.UserSession;
48 import static java.lang.String.format;
49 import static java.util.Collections.singleton;
50 import static java.util.Objects.requireNonNull;
51 import static java.util.Optional.ofNullable;
52 import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
53 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
54 import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
55 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
56 import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
57 import static org.sonar.server.ws.WsParameterBuilder.createRootQualifiersParameter;
58 import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
59 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
60 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
61 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
62 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
63 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
64 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
65 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
66 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
68 public class BulkApplyTemplateAction implements PermissionsWsAction {
70 private final DbClient dbClient;
71 private final UserSession userSession;
72 private final PermissionTemplateService permissionTemplateService;
73 private final PermissionWsSupport wsSupport;
74 private final I18n i18n;
75 private final ResourceTypes resourceTypes;
77 public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService, PermissionWsSupport wsSupport, I18n i18n,
78 ResourceTypes resourceTypes) {
79 this.dbClient = dbClient;
80 this.userSession = userSession;
81 this.permissionTemplateService = permissionTemplateService;
82 this.wsSupport = wsSupport;
84 this.resourceTypes = resourceTypes;
88 public void define(WebService.NewController context) {
89 WebService.NewAction action = context.createAction("bulk_apply_template")
90 .setDescription("Apply a permission template to several projects.<br />" +
91 "The template id or name must be provided.<br />" +
92 "Requires the following permission: 'Administer System'.")
95 .setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
98 action.createParam(Param.TEXT_QUERY)
99 .setDescription("Limit search to: <ul>" +
100 "<li>project names that contain the supplied string</li>" +
101 "<li>project keys that are exactly the same as the supplied string</li>" +
103 .setExampleValue("apac");
105 createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
106 .setDefaultValue(Qualifiers.PROJECT)
107 .setDeprecatedKey(PARAM_QUALIFIER, "6.6");
109 WsParameters.createTemplateParameters(action);
112 .createParam(PARAM_PROJECTS)
113 .setDescription("Comma-separated list of project keys")
115 // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
116 // Restricting size of HTTP parameter allows to not fail with SQL error
117 .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
118 .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
120 action.createParam(PARAM_VISIBILITY)
121 .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
122 "If no visibility is specified, the default project visibility will be used.",
123 Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
127 .setPossibleValues(Visibility.getLabels());
129 action.createParam(PARAM_ANALYZED_BEFORE)
130 .setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
131 "Either a date (server timezone) or datetime can be provided.")
133 .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
135 action.createParam(PARAM_ON_PROVISIONED_ONLY)
136 .setDescription("Filter the projects that are provisioned")
137 .setBooleanPossibleValues()
138 .setDefaultValue("false")
143 public void handle(Request request, Response response) throws Exception {
144 doHandle(toBulkApplyTemplateWsRequest(request));
145 response.noContent();
148 private void doHandle(BulkApplyTemplateRequest request) {
149 try (DbSession dbSession = dbClient.openSession(false)) {
150 PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
151 request.getTemplateId(), request.getTemplateName()));
152 checkGlobalAdmin(userSession);
154 ComponentQuery componentQuery = buildDbQuery(request);
155 List<ComponentDto> projects = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
157 permissionTemplateService.applyAndCommit(dbSession, template, projects);
161 private static BulkApplyTemplateRequest toBulkApplyTemplateWsRequest(Request request) {
162 return new BulkApplyTemplateRequest()
163 .setTemplateId(request.param(PARAM_TEMPLATE_ID))
164 .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
165 .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
166 .setQuery(request.param(Param.TEXT_QUERY))
167 .setVisibility(request.param(PARAM_VISIBILITY))
168 .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
169 .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
170 .setProjects(request.paramAsStrings(PARAM_PROJECTS));
173 private static ComponentQuery buildDbQuery(BulkApplyTemplateRequest request) {
174 Collection<String> qualifiers = request.getQualifiers();
175 ComponentQuery.Builder query = ComponentQuery.builder()
176 .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
178 ofNullable(request.getQuery()).ifPresent(q -> {
179 query.setNameOrKeyQuery(q);
180 query.setPartialMatchOnKey(true);
182 ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
183 ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
184 query.setOnProvisionedOnly(request.isOnProvisionedOnly());
185 ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
187 return query.build();
190 private static class BulkApplyTemplateRequest {
191 private String templateId;
192 private String templateName;
193 private String query;
194 private Collection<String> qualifiers = singleton(Qualifiers.PROJECT);
195 private String visibility;
196 private String analyzedBefore;
197 private boolean onProvisionedOnly = false;
198 private Collection<String> projects;
201 public String getTemplateId() {
205 public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
206 this.templateId = templateId;
211 public String getTemplateName() {
215 public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
216 this.templateName = templateName;
221 public String getQuery() {
225 public BulkApplyTemplateRequest setQuery(@Nullable String query) {
230 public Collection<String> getQualifiers() {
234 public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
235 this.qualifiers = requireNonNull(qualifiers);
240 public String getVisibility() {
244 public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
245 this.visibility = visibility;
250 public String getAnalyzedBefore() {
251 return analyzedBefore;
254 public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
255 this.analyzedBefore = analyzedBefore;
259 public boolean isOnProvisionedOnly() {
260 return onProvisionedOnly;
263 public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
264 this.onProvisionedOnly = onProvisionedOnly;
269 public Collection<String> getProjects() {
273 public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
274 this.projects = projects;