-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
UpdateAction.java
291 lines (256 loc) · 12 KB
/
UpdateAction.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.rule.ws;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.rule.RuleUpdate;
import org.sonar.server.rule.RuleUpdater;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Rules.UpdateResponse;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class UpdateAction implements RulesWsAction {
public static final String PARAM_KEY = "key";
public static final String PARAM_TAGS = "tags";
public static final String PARAM_MARKDOWN_NOTE = "markdown_note";
public static final String PARAM_REMEDIATION_FN_TYPE = "remediation_fn_type";
public static final String DEPRECATED_PARAM_REMEDIATION_FN_TYPE = "debt_remediation_fn_type";
public static final String PARAM_REMEDIATION_FN_BASE_EFFORT = "remediation_fn_base_effort";
public static final String DEPRECATED_PARAM_REMEDIATION_FN_OFFSET = "debt_remediation_fn_offset";
public static final String PARAM_REMEDIATION_FN_GAP_MULTIPLIER = "remediation_fy_gap_multiplier";
public static final String DEPRECATED_PARAM_REMEDIATION_FN_COEFF = "debt_remediation_fy_coeff";
public static final String PARAM_NAME = "name";
public static final String PARAM_DESCRIPTION = "markdown_description";
public static final String PARAM_SEVERITY = "severity";
public static final String PARAM_STATUS = "status";
public static final String PARAM_ORGANIZATION = "organization";
public static final String PARAMS = "params";
private final DbClient dbClient;
private final RuleUpdater ruleUpdater;
private final RuleMapper mapper;
private final UserSession userSession;
private final RuleWsSupport ruleWsSupport;
private final DefaultOrganizationProvider defaultOrganizationProvider;
public UpdateAction(DbClient dbClient, RuleUpdater ruleUpdater, RuleMapper mapper, UserSession userSession,
RuleWsSupport ruleWsSupport, DefaultOrganizationProvider defaultOrganizationProvider) {
this.dbClient = dbClient;
this.ruleUpdater = ruleUpdater;
this.mapper = mapper;
this.userSession = userSession;
this.ruleWsSupport = ruleWsSupport;
this.defaultOrganizationProvider = defaultOrganizationProvider;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("update")
.setPost(true)
.setDescription("Update an existing rule.<br>" +
"Requires the 'Administer Quality Profiles' permission")
.setSince("4.4")
.setHandler(this);
action.createParam(PARAM_KEY)
.setRequired(true)
.setDescription("Key of the rule to update")
.setExampleValue("javascript:NullCheck");
action.createParam(PARAM_TAGS)
.setDescription("Optional comma-separated list of tags to set. Use blank value to remove current tags. Tags " +
"are not changed if the parameter is not set.")
.setExampleValue("java8,security");
action.createParam(PARAM_MARKDOWN_NOTE)
.setDescription("Optional note in markdown format. Use empty value to remove current note. Note is not changed" +
"if the parameter is not set.")
.setExampleValue("my *note*");
action.createParam("debt_sub_characteristic")
.setDescription("Debt characteristics are no more supported. This parameter is ignored.")
.setDeprecatedSince("5.5");
action.createParam(PARAM_REMEDIATION_FN_TYPE)
.setDescription("Type of the remediation function of the rule")
.setPossibleValues(DebtRemediationFunction.Type.values())
.setSince("5.5");
action.createParam(DEPRECATED_PARAM_REMEDIATION_FN_TYPE)
.setDeprecatedSince("5.5")
.setPossibleValues(DebtRemediationFunction.Type.values());
action.createParam(PARAM_REMEDIATION_FN_BASE_EFFORT)
.setDescription("Base effort of the remediation function of the rule")
.setExampleValue("1d")
.setSince("5.5");
action.createParam(DEPRECATED_PARAM_REMEDIATION_FN_OFFSET)
.setDeprecatedSince("5.5");
action.createParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER)
.setDescription("Gap multiplier of the remediation function of the rule")
.setExampleValue("3min")
.setSince("5.5");
action.createParam(DEPRECATED_PARAM_REMEDIATION_FN_COEFF)
.setDeprecatedSince("5.5");
action
.createParam(PARAM_NAME)
.setDescription("Rule name (mandatory for custom rule)")
.setExampleValue("My custom rule");
action
.createParam(PARAM_DESCRIPTION)
.setDescription("Rule description (mandatory for custom rule and manual rule)")
.setExampleValue("Description of my custom rule");
action
.createParam(PARAM_SEVERITY)
.setDescription("Rule severity (Only when updating a custom rule)")
.setPossibleValues(Severity.ALL);
action
.createParam(PARAM_STATUS)
.setDescription("Rule status (Only when updating a custom rule)")
.setPossibleValues(RuleStatus.values());
action.createParam(PARAM_ORGANIZATION)
.setDescription("Organization key")
.setRequired(false)
.setInternal(true)
.setExampleValue("my-org")
.setSince("6.4");
action.createParam(PARAMS)
.setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only when updating a custom rule)");
}
@Override
public void handle(Request request, Response response) throws Exception {
ruleWsSupport.checkQProfileAdminPermission();
try (DbSession dbSession = dbClient.openSession(false)) {
OrganizationDto organization = getOrganization(request, dbSession);
RuleUpdate update = readRequest(dbSession, request, organization);
ruleUpdater.update(dbSession, update, organization, userSession);
UpdateResponse updateResponse = buildResponse(dbSession, update.getRuleKey(), organization);
writeProtobuf(updateResponse, request, response);
}
}
private OrganizationDto getOrganization(Request request, DbSession dbSession) {
String organizationKey = ofNullable(request.param(PARAM_ORGANIZATION))
.orElseGet(() -> defaultOrganizationProvider.get().getKey());
return dbClient.organizationDao().selectByKey(dbSession, organizationKey)
.orElseThrow(() -> new IllegalStateException(format("Cannot load organization '%s'", organizationKey)));
}
private RuleUpdate readRequest(DbSession dbSession, Request request, OrganizationDto organization) {
RuleKey key = RuleKey.parse(request.mandatoryParam(PARAM_KEY));
RuleUpdate update = createRuleUpdate(dbSession, key, organization);
readTags(request, update);
readMarkdownNote(request, update);
readDebt(request, update);
String name = request.param(PARAM_NAME);
if (name != null) {
update.setName(name);
}
String description = request.param(PARAM_DESCRIPTION);
if (description != null) {
update.setMarkdownDescription(description);
}
String severity = request.param(PARAM_SEVERITY);
if (severity != null) {
update.setSeverity(severity);
}
String status = request.param(PARAM_STATUS);
if (status != null) {
update.setStatus(RuleStatus.valueOf(status));
}
String params = request.param(PARAMS);
if (params != null) {
update.setParameters(KeyValueFormat.parse(params));
}
return update;
}
private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key, OrganizationDto organization) {
RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, organization, key)
.orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key)));
RuleUpdate ruleUpdate = ofNullable(rule.getTemplateId())
.map(x -> RuleUpdate.createForCustomRule(key))
.orElseGet(() -> RuleUpdate.createForPluginRule(key));
ruleUpdate.setOrganization(organization);
return ruleUpdate;
}
private static void readTags(Request request, RuleUpdate update) {
String value = request.param(PARAM_TAGS);
if (value != null) {
if (StringUtils.isBlank(value)) {
update.setTags(null);
} else {
update.setTags(Sets.newHashSet(Splitter.on(',').omitEmptyStrings().trimResults().split(value)));
}
}
// else do not touch this field
}
private static void readMarkdownNote(Request request, RuleUpdate update) {
String value = request.param(PARAM_MARKDOWN_NOTE);
if (value != null) {
update.setMarkdownNote(value);
}
// else do not touch this field
}
private static void readDebt(Request request, RuleUpdate update) {
String value = defaultIfEmpty(request.param(PARAM_REMEDIATION_FN_TYPE), request.param(DEPRECATED_PARAM_REMEDIATION_FN_TYPE));
if (value != null) {
if (StringUtils.isBlank(value)) {
update.setDebtRemediationFunction(null);
} else {
DebtRemediationFunction fn = new DefaultDebtRemediationFunction(
DebtRemediationFunction.Type.valueOf(value),
defaultIfEmpty(request.param(PARAM_REMEDIATION_FN_GAP_MULTIPLIER), request.param(DEPRECATED_PARAM_REMEDIATION_FN_COEFF)),
defaultIfEmpty(request.param(PARAM_REMEDIATION_FN_BASE_EFFORT), request.param(DEPRECATED_PARAM_REMEDIATION_FN_OFFSET)));
update.setDebtRemediationFunction(fn);
}
}
}
private UpdateResponse buildResponse(DbSession dbSession, RuleKey key, OrganizationDto organization) {
RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, organization, key)
.orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key)));
List<RuleDefinitionDto> templateRules = new ArrayList<>(1);
if (rule.getDefinition().isCustomRule()) {
dbClient.ruleDao().selectDefinitionById(rule.getTemplateId(), dbSession)
.ifPresent(templateRules::add);
}
List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleIds(dbSession, singletonList(rule.getId()));
UpdateResponse.Builder responseBuilder = UpdateResponse.newBuilder();
SearchAction.SearchResult searchResult = new SearchAction.SearchResult()
.setRules(singletonList(rule))
.setTemplateRules(templateRules)
.setRuleParameters(ruleParameters)
.setTotal(1L);
responseBuilder.setRule(mapper.toWsRule(rule.getDefinition(), searchResult, Collections.<String>emptySet(), rule.getMetadata()));
return responseBuilder.build();
}
}