]> source.dussan.org Git - sonarqube.git/blob
d57522d24f28a6c6ac66189c89e1a0d4888ada86
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2021 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.server.permission.ws.template;
21
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;
47
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;
67
68 public class BulkApplyTemplateAction implements PermissionsWsAction {
69
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;
76
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;
83     this.i18n = i18n;
84     this.resourceTypes = resourceTypes;
85   }
86
87   @Override
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'.")
93       .setPost(true)
94       .setSince("5.5")
95       .setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
96       .setHandler(this);
97
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>" +
102         "</ul>")
103       .setExampleValue("apac");
104
105     createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
106       .setDefaultValue(Qualifiers.PROJECT)
107       .setDeprecatedKey(PARAM_QUALIFIER, "6.6");
108
109     WsParameters.createTemplateParameters(action);
110
111     action
112       .createParam(PARAM_PROJECTS)
113       .setDescription("Comma-separated list of project keys")
114       .setSince("6.6")
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));
119
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())
124       .setRequired(false)
125       .setInternal(true)
126       .setSince("6.6")
127       .setPossibleValues(Visibility.getLabels());
128
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.")
132       .setSince("6.6")
133       .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
134
135     action.createParam(PARAM_ON_PROVISIONED_ONLY)
136       .setDescription("Filter the projects that are provisioned")
137       .setBooleanPossibleValues()
138       .setDefaultValue("false")
139       .setSince("6.6");
140   }
141
142   @Override
143   public void handle(Request request, Response response) throws Exception {
144     doHandle(toBulkApplyTemplateWsRequest(request));
145     response.noContent();
146   }
147
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);
153
154       ComponentQuery componentQuery = buildDbQuery(request);
155       List<ComponentDto> projects = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
156
157       permissionTemplateService.applyAndCommit(dbSession, template, projects);
158     }
159   }
160
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));
171   }
172
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()]));
177
178     ofNullable(request.getQuery()).ifPresent(q -> {
179       query.setNameOrKeyQuery(q);
180       query.setPartialMatchOnKey(true);
181     });
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)));
186
187     return query.build();
188   }
189
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;
199
200     @CheckForNull
201     public String getTemplateId() {
202       return templateId;
203     }
204
205     public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
206       this.templateId = templateId;
207       return this;
208     }
209
210     @CheckForNull
211     public String getTemplateName() {
212       return templateName;
213     }
214
215     public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
216       this.templateName = templateName;
217       return this;
218     }
219
220     @CheckForNull
221     public String getQuery() {
222       return query;
223     }
224
225     public BulkApplyTemplateRequest setQuery(@Nullable String query) {
226       this.query = query;
227       return this;
228     }
229
230     public Collection<String> getQualifiers() {
231       return qualifiers;
232     }
233
234     public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
235       this.qualifiers = requireNonNull(qualifiers);
236       return this;
237     }
238
239     @CheckForNull
240     public String getVisibility() {
241       return visibility;
242     }
243
244     public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
245       this.visibility = visibility;
246       return this;
247     }
248
249     @CheckForNull
250     public String getAnalyzedBefore() {
251       return analyzedBefore;
252     }
253
254     public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
255       this.analyzedBefore = analyzedBefore;
256       return this;
257     }
258
259     public boolean isOnProvisionedOnly() {
260       return onProvisionedOnly;
261     }
262
263     public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
264       this.onProvisionedOnly = onProvisionedOnly;
265       return this;
266     }
267
268     @CheckForNull
269     public Collection<String> getProjects() {
270       return projects;
271     }
272
273     public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
274       this.projects = projects;
275       return this;
276     }
277   }
278 }