repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/ws/SetAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.projecttag.ws;
import java.util.List;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.projecttag.TagsWsSupport;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
public class SetAction implements ProjectTagsWsAction {
private static final String PARAM_PROJECT = "project";
private static final String PARAM_TAGS = "tags";
private final DbClient dbClient;
private final TagsWsSupport tagsWsSupport;
public SetAction(DbClient dbClient, TagsWsSupport tagsWsSupport) {
this.dbClient = dbClient;
this.tagsWsSupport = tagsWsSupport;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("set")
.setDescription("Set tags on a project.<br>" +
"Requires the following permission: 'Administer' rights on the specified project")
.setSince("6.4")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_TAGS)
.setDescription("Comma-separated list of tags")
.setRequired(true)
.setExampleValue("finance, offshore");
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.mandatoryParam(PARAM_PROJECT);
List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS);
try (DbSession dbSession = dbClient.openSession(false)) {
tagsWsSupport.updateProjectTags(dbSession, projectKey, tags);
}
response.noContent();
}
}
| 2,655 | 33.493506 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/ws/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.projecttag.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 37.88 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateCaycChecker.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.measures.Metric;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import static java.util.stream.Collectors.toUnmodifiableMap;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING;
import static org.sonar.server.qualitygate.QualityGateCaycStatus.COMPLIANT;
import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT;
import static org.sonar.server.qualitygate.QualityGateCaycStatus.OVER_COMPLIANT;
public class QualityGateCaycChecker {
public static final List<Metric<? extends Serializable>> CAYC_METRICS = List.of(
NEW_MAINTAINABILITY_RATING,
NEW_RELIABILITY_RATING,
NEW_SECURITY_HOTSPOTS_REVIEWED,
NEW_SECURITY_RATING,
NEW_DUPLICATED_LINES_DENSITY,
NEW_COVERAGE
);
private static final Set<String> EXISTENCY_REQUIREMENTS = Set.of(
NEW_DUPLICATED_LINES_DENSITY_KEY,
NEW_COVERAGE_KEY
);
private static final Map<String, Double> BEST_VALUE_REQUIREMENTS = CAYC_METRICS.stream()
.filter(metric -> !EXISTENCY_REQUIREMENTS.contains(metric.getKey()))
.collect(toUnmodifiableMap(Metric::getKey, Metric::getBestValue));
private final DbClient dbClient;
public QualityGateCaycChecker(DbClient dbClient) {
this.dbClient = dbClient;
}
public QualityGateCaycStatus checkCaycCompliant(DbSession dbSession, String qualityGateUuid) {
var conditionsByMetricId = dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateUuid)
.stream()
.collect(Collectors.toMap(QualityGateConditionDto::getMetricUuid, Function.identity()));
if (conditionsByMetricId.size() < CAYC_METRICS.size()) {
return NON_COMPLIANT;
}
var metrics = dbClient.metricDao().selectByUuids(dbSession, conditionsByMetricId.keySet())
.stream()
.filter(MetricDto::isEnabled)
.toList();
long count = metrics.stream()
.filter(metric -> checkMetricCaycCompliant(conditionsByMetricId.get(metric.getUuid()), metric))
.count();
if (metrics.size() == count && count == CAYC_METRICS.size()) {
return COMPLIANT;
} else if (metrics.size() > count && count == CAYC_METRICS.size()) {
return OVER_COMPLIANT;
}
return NON_COMPLIANT;
}
public QualityGateCaycStatus checkCaycCompliantFromProject(DbSession dbSession, String projectUuid) {
return Optional.ofNullable(dbClient.qualityGateDao().selectByProjectUuid(dbSession, projectUuid))
.or(() -> Optional.ofNullable(dbClient.qualityGateDao().selectDefault(dbSession)))
.map(qualityGate -> checkCaycCompliant(dbSession, qualityGate.getUuid()))
.orElse(NON_COMPLIANT);
}
private static boolean checkMetricCaycCompliant(QualityGateConditionDto condition, MetricDto metric) {
if (EXISTENCY_REQUIREMENTS.contains(metric.getKey())) {
return true;
} else if (BEST_VALUE_REQUIREMENTS.containsKey(metric.getKey())) {
Double errorThreshold = Double.valueOf(condition.getErrorThreshold());
Double caycRequiredThreshold = BEST_VALUE_REQUIREMENTS.get(metric.getKey());
return caycRequiredThreshold.compareTo(errorThreshold) == 0;
} else {
return false;
}
}
}
| 4,857 | 39.14876 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateCaycStatus.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
public enum QualityGateCaycStatus {
NON_COMPLIANT("non-compliant"),
COMPLIANT("compliant"),
OVER_COMPLIANT("over-compliant");
final String status;
QualityGateCaycStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return status;
}
}
| 1,178 | 29.230769 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateConditionsUpdater.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.measure.Rating;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.Metric.DIRECTION_BETTER;
import static org.sonar.api.measures.Metric.DIRECTION_NONE;
import static org.sonar.api.measures.Metric.DIRECTION_WORST;
import static org.sonar.api.measures.Metric.ValueType.RATING;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.measure.Rating.E;
import static org.sonar.server.qualitygate.Condition.Operator.GREATER_THAN;
import static org.sonar.server.qualitygate.Condition.Operator.LESS_THAN;
import static org.sonar.server.qualitygate.ValidRatingMetrics.isCoreRatingMetric;
public class QualityGateConditionsUpdater {
public static final Set<String> INVALID_METRIC_KEYS = Set.of(ALERT_STATUS_KEY, SECURITY_HOTSPOTS_KEY, NEW_SECURITY_HOTSPOTS_KEY);
private static final Map<Integer, Set<Condition.Operator>> VALID_OPERATORS_BY_DIRECTION = Map.of(
DIRECTION_NONE, Set.of(GREATER_THAN, LESS_THAN),
DIRECTION_BETTER, Set.of(LESS_THAN),
DIRECTION_WORST, Set.of(GREATER_THAN));
private static final EnumSet<ValueType> VALID_METRIC_TYPES = EnumSet.of(
ValueType.INT,
ValueType.FLOAT,
ValueType.PERCENT,
ValueType.MILLISEC,
ValueType.LEVEL,
ValueType.RATING,
ValueType.WORK_DUR);
private static final List<String> RATING_VALID_INT_VALUES = stream(Rating.values()).map(r -> Integer.toString(r.getIndex())).toList();
private final DbClient dbClient;
public QualityGateConditionsUpdater(DbClient dbClient) {
this.dbClient = dbClient;
}
public QualityGateConditionDto createCondition(DbSession dbSession, QualityGateDto qualityGate, String metricKey, String operator,
String errorThreshold) {
MetricDto metric = getNonNullMetric(dbSession, metricKey);
validateCondition(metric, operator, errorThreshold);
checkConditionDoesNotExistOnSameMetric(getConditions(dbSession, qualityGate.getUuid()), metric);
QualityGateConditionDto newCondition = new QualityGateConditionDto().setQualityGateUuid(qualityGate.getUuid())
.setUuid(Uuids.create())
.setMetricUuid(metric.getUuid()).setMetricKey(metric.getKey())
.setOperator(operator)
.setErrorThreshold(errorThreshold);
dbClient.gateConditionDao().insert(newCondition, dbSession);
return newCondition;
}
public QualityGateConditionDto updateCondition(DbSession dbSession, QualityGateConditionDto condition, String metricKey, String operator,
String errorThreshold) {
MetricDto metric = getNonNullMetric(dbSession, metricKey);
validateCondition(metric, operator, errorThreshold);
condition
.setMetricUuid(metric.getUuid())
.setMetricKey(metric.getKey())
.setOperator(operator)
.setErrorThreshold(errorThreshold);
dbClient.gateConditionDao().update(condition, dbSession);
return condition;
}
private MetricDto getNonNullMetric(DbSession dbSession, String metricKey) {
MetricDto metric = dbClient.metricDao().selectByKey(dbSession, metricKey);
if (metric == null) {
throw new NotFoundException(format("There is no metric with key=%s", metricKey));
}
return metric;
}
private Collection<QualityGateConditionDto> getConditions(DbSession dbSession, String qGateUuid) {
return dbClient.gateConditionDao().selectForQualityGate(dbSession, qGateUuid);
}
private static void validateCondition(MetricDto metric, String operator, String errorThreshold) {
List<String> errors = new ArrayList<>();
validateMetric(metric, errors);
checkOperator(metric, operator, errors);
checkErrorThreshold(metric, errorThreshold, errors);
checkRatingMetric(metric, errorThreshold, errors);
checkRequest(errors.isEmpty(), errors);
}
private static void validateMetric(MetricDto metric, List<String> errors) {
check(isValid(metric), errors, "Metric '%s' cannot be used to define a condition.", metric.getKey());
}
private static boolean isValid(MetricDto metric) {
return !metric.isHidden()
&& VALID_METRIC_TYPES.contains(ValueType.valueOf(metric.getValueType()))
&& !INVALID_METRIC_KEYS.contains(metric.getKey());
}
private static void checkOperator(MetricDto metric, String operator, List<String> errors) {
check(
Condition.Operator.isValid(operator) && isAllowedOperator(operator, metric),
errors,
"Operator %s is not allowed for this metric.", operator);
}
private static void checkErrorThreshold(MetricDto metric, String errorThreshold, List<String> errors) {
requireNonNull(errorThreshold, "errorThreshold can not be null");
validateErrorThresholdValue(metric, errorThreshold, errors);
}
private static void checkConditionDoesNotExistOnSameMetric(Collection<QualityGateConditionDto> conditions, MetricDto metric) {
if (conditions.isEmpty()) {
return;
}
boolean conditionExists = conditions.stream().anyMatch(c -> c.getMetricUuid().equals(metric.getUuid()));
checkRequest(!conditionExists, format("Condition on metric '%s' already exists.", metric.getShortName()));
}
private static boolean isAllowedOperator(String operator, MetricDto metric) {
if (VALID_OPERATORS_BY_DIRECTION.containsKey(metric.getDirection())) {
return VALID_OPERATORS_BY_DIRECTION.get(metric.getDirection()).contains(Condition.Operator.fromDbValue(operator));
}
return false;
}
private static void validateErrorThresholdValue(MetricDto metric, String errorThreshold, List<String> errors) {
try {
ValueType valueType = ValueType.valueOf(metric.getValueType());
switch (valueType) {
case BOOL, INT, RATING:
parseInt(errorThreshold);
return;
case MILLISEC, WORK_DUR:
parseLong(errorThreshold);
return;
case FLOAT, PERCENT:
parseDouble(errorThreshold);
return;
case STRING, LEVEL:
return;
default:
throw new IllegalArgumentException(format("Unsupported value type %s. Cannot convert condition value", valueType));
}
} catch (Exception e) {
errors.add(format("Invalid value '%s' for metric '%s'", errorThreshold, metric.getShortName()));
}
}
private static void checkRatingMetric(MetricDto metric, String errorThreshold, List<String> errors) {
if (!metric.getValueType().equals(RATING.name())) {
return;
}
if (!isCoreRatingMetric(metric.getKey())) {
errors.add(format("The metric '%s' cannot be used", metric.getShortName()));
}
if (!isValidRating(errorThreshold)) {
addInvalidRatingError(errorThreshold, errors);
return;
}
checkRatingGreaterThanOperator(errorThreshold, errors);
}
private static void addInvalidRatingError(@Nullable String value, List<String> errors) {
errors.add(format("'%s' is not a valid rating", value));
}
private static void checkRatingGreaterThanOperator(@Nullable String value, List<String> errors) {
check(isNullOrEmpty(value) || !Objects.equals(toRating(value), E), errors, "There's no worse rating than E (%s)" , value);
}
private static Rating toRating(String value) {
return Rating.valueOf(parseInt(value));
}
private static boolean isValidRating(@Nullable String value) {
return isNullOrEmpty(value) || RATING_VALID_INT_VALUES.contains(value);
}
private static boolean check(boolean expression, List<String> errors, String message, String... args) {
if (!expression) {
errors.add(format(message, args));
}
return expression;
}
}
| 9,498 | 39.594017 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateConverter.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class QualityGateConverter {
private static final String FIELD_LEVEL = "level";
private static final String FIELD_IGNORED_CONDITIONS = "ignoredConditions";
private QualityGateConverter() {
// prevent instantiation
}
public static String toJson(EvaluatedQualityGate gate) {
JsonObject details = new JsonObject();
details.addProperty(FIELD_LEVEL, gate.getStatus().name());
JsonArray conditionResults = new JsonArray();
for (EvaluatedCondition condition : gate.getEvaluatedConditions()) {
conditionResults.add(toJson(condition));
}
details.add("conditions", conditionResults);
details.addProperty(FIELD_IGNORED_CONDITIONS, gate.hasIgnoredConditionsOnSmallChangeset());
return details.toString();
}
private static JsonObject toJson(EvaluatedCondition evaluatedCondition) {
Condition condition = evaluatedCondition.getCondition();
JsonObject result = new JsonObject();
result.addProperty("metric", condition.getMetricKey());
result.addProperty("op", condition.getOperator().getDbValue());
if (condition.isOnLeakPeriod()) {
result.addProperty("period", 1);
}
result.addProperty("error", condition.getErrorThreshold());
evaluatedCondition.getValue().ifPresent(v -> result.addProperty("actual", v));
result.addProperty(FIELD_LEVEL, evaluatedCondition.getStatus().name());
return result;
}
}
| 2,351 | 37.557377 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import org.sonar.core.platform.Module;
public class QualityGateModule extends Module {
@Override
protected void configureModule() {
add(
QualityGateUpdater.class,
QualityGateCaycChecker.class,
QualityGateConditionsUpdater.class,
QualityGateFinder.class,
QualityGateEvaluatorImpl.class);
}
}
| 1,214 | 33.714286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateUpdater.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.util.Validation.IS_ALREADY_USED_MESSAGE;
public class QualityGateUpdater {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
public QualityGateUpdater(DbClient dbClient, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
}
public QualityGateDto create(DbSession dbSession, String name) {
validateQualityGate(dbSession, name);
QualityGateDto newQualityGate = new QualityGateDto()
.setName(name)
.setBuiltIn(false)
.setUuid(uuidFactory.create());
dbClient.qualityGateDao().insert(dbSession, newQualityGate);
return newQualityGate;
}
public QualityGateDto copy(DbSession dbSession, QualityGateDto qualityGateDto, String destinationName) {
QualityGateDto destinationGate = create(dbSession, destinationName);
for (QualityGateConditionDto sourceCondition : dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getUuid())) {
dbClient.gateConditionDao().insert(new QualityGateConditionDto()
.setUuid(Uuids.create())
.setQualityGateUuid(destinationGate.getUuid())
.setMetricUuid(sourceCondition.getMetricUuid())
.setOperator(sourceCondition.getOperator())
.setErrorThreshold(sourceCondition.getErrorThreshold()),
dbSession);
}
return destinationGate;
}
private void validateQualityGate(DbSession dbSession, String name) {
checkQualityGateDoesNotAlreadyExist(dbSession, name);
}
private void checkQualityGateDoesNotAlreadyExist(DbSession dbSession, String name) {
QualityGateDto existingQGate = dbClient.qualityGateDao().selectByName(dbSession, name);
checkArgument(existingQGate == null, IS_ALREADY_USED_MESSAGE, "Name");
}
}
| 2,972 | 38.118421 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/RegisterQualityGates.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.Startable;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.qualitygate.QualityGateConditionDao;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDao;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.measure.Rating;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY;
import static org.sonar.db.qualitygate.QualityGateConditionDto.OPERATOR_GREATER_THAN;
import static org.sonar.db.qualitygate.QualityGateConditionDto.OPERATOR_LESS_THAN;
public class RegisterQualityGates implements Startable {
private static final Logger LOGGER = LoggerFactory.getLogger(RegisterQualityGates.class);
private static final String BUILTIN_QUALITY_GATE_NAME = "Sonar way";
private static final String A_RATING = Integer.toString(Rating.A.getIndex());
private static final List<QualityGateCondition> QUALITY_GATE_CONDITIONS = asList(
new QualityGateCondition().setMetricKey(NEW_SECURITY_RATING_KEY).setOperator(OPERATOR_GREATER_THAN).setErrorThreshold(A_RATING),
new QualityGateCondition().setMetricKey(NEW_RELIABILITY_RATING_KEY).setOperator(OPERATOR_GREATER_THAN).setErrorThreshold(A_RATING),
new QualityGateCondition().setMetricKey(NEW_MAINTAINABILITY_RATING_KEY).setOperator(OPERATOR_GREATER_THAN).setErrorThreshold(A_RATING),
new QualityGateCondition().setMetricKey(NEW_COVERAGE_KEY).setOperator(OPERATOR_LESS_THAN).setErrorThreshold("80"),
new QualityGateCondition().setMetricKey(NEW_DUPLICATED_LINES_DENSITY_KEY).setOperator(OPERATOR_GREATER_THAN).setErrorThreshold("3"),
new QualityGateCondition().setMetricKey(NEW_SECURITY_HOTSPOTS_REVIEWED_KEY).setOperator(OPERATOR_LESS_THAN).setErrorThreshold("100"));
private final DbClient dbClient;
private final QualityGateConditionsUpdater qualityGateConditionsUpdater;
private final QualityGateDao qualityGateDao;
private final QualityGateConditionDao qualityGateConditionDao;
private final UuidFactory uuidFactory;
private final System2 system2;
public RegisterQualityGates(DbClient dbClient, QualityGateConditionsUpdater qualityGateConditionsUpdater, UuidFactory uuidFactory, System2 system2) {
this.dbClient = dbClient;
this.qualityGateConditionsUpdater = qualityGateConditionsUpdater;
this.qualityGateDao = dbClient.qualityGateDao();
this.qualityGateConditionDao = dbClient.gateConditionDao();
this.uuidFactory = uuidFactory;
this.system2 = system2;
}
@Override
public void start() {
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto builtinQualityGate = qualityGateDao.selectByName(dbSession, BUILTIN_QUALITY_GATE_NAME);
// Create builtinQualityGate if not present
if (builtinQualityGate == null) {
LOGGER.info("Built-in quality gate [{}] has been created", BUILTIN_QUALITY_GATE_NAME);
builtinQualityGate = createQualityGate(dbSession, BUILTIN_QUALITY_GATE_NAME);
}
// Set builtinQualityGate if missing
if (!builtinQualityGate.isBuiltIn()) {
builtinQualityGate.setBuiltIn(true);
dbClient.qualityGateDao().update(builtinQualityGate, dbSession);
LOGGER.info("Quality gate [{}] has been set as built-in", BUILTIN_QUALITY_GATE_NAME);
}
updateQualityConditionsIfRequired(dbSession, builtinQualityGate);
qualityGateDao.ensureOneBuiltInQualityGate(dbSession, BUILTIN_QUALITY_GATE_NAME);
dbSession.commit();
}
}
private void updateQualityConditionsIfRequired(DbSession dbSession, QualityGateDto builtinQualityGate) {
List<QualityGateCondition> qualityGateConditions = getQualityGateConditions(dbSession, builtinQualityGate);
List<QualityGateCondition> qgConditionsDeleted = removeExtraConditions(dbSession, builtinQualityGate, qualityGateConditions);
qgConditionsDeleted.addAll(removeDuplicatedConditions(dbSession, builtinQualityGate, qualityGateConditions));
List<QualityGateCondition> qgConditionsAdded = addMissingConditions(dbSession, builtinQualityGate, qualityGateConditions);
if (!qgConditionsAdded.isEmpty() || !qgConditionsDeleted.isEmpty()) {
LOGGER.info("Built-in quality gate's conditions of [{}] has been updated", BUILTIN_QUALITY_GATE_NAME);
}
}
private ImmutableList<QualityGateCondition> getQualityGateConditions(DbSession dbSession, QualityGateDto builtinQualityGate) {
Map<String, String> uuidToKeyMetric = dbClient.metricDao().selectAll(dbSession).stream()
.collect(toMap(MetricDto::getUuid, MetricDto::getKey));
return qualityGateConditionDao.selectForQualityGate(dbSession, builtinQualityGate.getUuid())
.stream()
.map(dto -> QualityGateCondition.from(dto, uuidToKeyMetric))
.collect(toImmutableList());
}
private List<QualityGateCondition> removeExtraConditions(DbSession dbSession, QualityGateDto builtinQualityGate, List<QualityGateCondition> qualityGateConditions) {
// Find all conditions that are not present in QUALITY_GATE_CONDITIONS
// Those conditions must be deleted
List<QualityGateCondition> qgConditionsToBeDeleted = new ArrayList<>(qualityGateConditions);
qgConditionsToBeDeleted.removeAll(QUALITY_GATE_CONDITIONS);
qgConditionsToBeDeleted
.forEach(qgc -> qualityGateConditionDao.delete(qgc.toQualityGateDto(builtinQualityGate.getUuid()), dbSession));
return qgConditionsToBeDeleted;
}
private Set<QualityGateCondition> removeDuplicatedConditions(DbSession dbSession, QualityGateDto builtinQualityGate, List<QualityGateCondition> qualityGateConditions) {
Set<QualityGateCondition> qgConditionsDuplicated = qualityGateConditions
.stream()
.filter(qualityGateCondition -> Collections.frequency(qualityGateConditions, qualityGateCondition) > 1)
.collect(Collectors.toSet());
qgConditionsDuplicated
.forEach(qgc -> qualityGateConditionDao.delete(qgc.toQualityGateDto(builtinQualityGate.getUuid()), dbSession));
return qgConditionsDuplicated;
}
private List<QualityGateCondition> addMissingConditions(DbSession dbSession, QualityGateDto builtinQualityGate, List<QualityGateCondition> qualityGateConditions) {
// Find all conditions that are not present in qualityGateConditions
// Those conditions must be added to the built-in quality gate
List<QualityGateCondition> qgConditionsToBeAdded = new ArrayList<>(QUALITY_GATE_CONDITIONS);
qgConditionsToBeAdded.removeAll(qualityGateConditions);
qgConditionsToBeAdded
.forEach(qgc -> qualityGateConditionsUpdater.createCondition(dbSession, builtinQualityGate, qgc.getMetricKey(), qgc.getOperator(),
qgc.getErrorThreshold()));
return qgConditionsToBeAdded;
}
@Override
public void stop() {
// do nothing
}
private QualityGateDto createQualityGate(DbSession dbSession, String name) {
QualityGateDto qualityGate = new QualityGateDto()
.setName(name)
.setBuiltIn(true)
.setUuid(uuidFactory.create())
.setCreatedAt(new Date(system2.now()));
return dbClient.qualityGateDao().insert(dbSession, qualityGate);
}
private static class QualityGateCondition {
private String uuid;
private String metricKey;
private String operator;
private String errorThreshold;
public static QualityGateCondition from(QualityGateConditionDto qualityGateConditionDto, Map<String, String> mapping) {
return new QualityGateCondition()
.setUuid(qualityGateConditionDto.getUuid())
.setMetricKey(mapping.get(qualityGateConditionDto.getMetricUuid()))
.setOperator(qualityGateConditionDto.getOperator())
.setErrorThreshold(qualityGateConditionDto.getErrorThreshold());
}
@CheckForNull
public String getUuid() {
return uuid;
}
public QualityGateCondition setUuid(String uuid) {
this.uuid = uuid;
return this;
}
public String getMetricKey() {
return metricKey;
}
public QualityGateCondition setMetricKey(String metricKey) {
this.metricKey = metricKey;
return this;
}
public String getOperator() {
return operator;
}
public QualityGateCondition setOperator(String operator) {
this.operator = operator;
return this;
}
public String getErrorThreshold() {
return errorThreshold;
}
public QualityGateCondition setErrorThreshold(String errorThreshold) {
this.errorThreshold = errorThreshold;
return this;
}
public QualityGateConditionDto toQualityGateDto(String qualityGateUuid) {
return new QualityGateConditionDto()
.setUuid(uuid)
.setMetricKey(metricKey)
.setOperator(operator)
.setErrorThreshold(errorThreshold)
.setQualityGateUuid(qualityGateUuid);
}
// id does not belong to equals to be able to be compared with builtin
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QualityGateCondition that = (QualityGateCondition) o;
return Objects.equals(metricKey, that.metricKey) &&
Objects.equals(operator, that.operator) &&
Objects.equals(errorThreshold, that.errorThreshold);
}
// id does not belong to hashcode to be able to be compared with builtin
@Override
public int hashCode() {
return Objects.hash(metricKey, operator, errorThreshold);
}
}
}
| 11,396 | 41.685393 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ValidRatingMetrics.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.measures.CoreMetrics;
import static org.sonar.api.measures.Metric.ValueType.RATING;
public class ValidRatingMetrics {
private static final Set<String> CORE_RATING_METRICS = CoreMetrics.getMetrics().stream()
.filter(metric -> metric.getType().equals(RATING))
.map(org.sonar.api.measures.Metric::getKey)
.collect(Collectors.toSet());
private ValidRatingMetrics() {
// only static methods
}
public static boolean isCoreRatingMetric(String metricKey) {
return CORE_RATING_METRICS.contains(metricKey);
}
}
| 1,497 | 33.837209 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.qualitygate;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/AbstractGroupAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.GroupDto;
import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
public abstract class AbstractGroupAction implements QualityGatesWsAction {
protected final DbClient dbClient;
protected final QualityGatesWsSupport wsSupport;
protected AbstractGroupAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
protected void defineGateAndGroupParameters(WebService.NewAction action) {
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setExampleValue("SonarSource Way");
action.createParam(PARAM_GROUP_NAME)
.setDescription("Group name or 'anyone' (case insensitive)")
.setRequired(true)
.setExampleValue("sonar-administrators");
}
@Override
public void handle(Request request, Response response) throws Exception {
final String groupName = request.mandatoryParam(PARAM_GROUP_NAME);
final String qualityGateName = request.mandatoryParam(PARAM_GATE_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGateDto = wsSupport.getByName(dbSession, qualityGateName);
wsSupport.checkCanLimitedEdit(dbSession, qualityGateDto);
GroupDto group = getGroup(dbSession, groupName);
apply(dbSession, qualityGateDto, group);
}
response.noContent();
}
protected abstract void apply(DbSession dbSession, QualityGateDto qualityGate, GroupDto group);
private GroupDto getGroup(DbSession dbSession, String groupName) {
Optional<GroupDto> group = dbClient.groupDao().selectByName(dbSession, groupName);
checkFoundWithOptional(group, "Group with name '%s' is not found", groupName);
return group.get();
}
}
| 3,259 | 39.75 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/AbstractUserAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.UserDto;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN;
public abstract class AbstractUserAction implements QualityGatesWsAction {
protected final DbClient dbClient;
protected final QualityGatesWsSupport wsSupport;
protected AbstractUserAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
protected void defineGateAndUserParameters(WebService.NewAction action) {
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setExampleValue("SonarSource Way");
action.createParam(PARAM_LOGIN)
.setDescription("User login")
.setRequired(true)
.setExampleValue("john.doe");
}
@Override
public void handle(Request request, Response response) throws Exception {
final String login = request.mandatoryParam(PARAM_LOGIN);
final String qualityGateName = request.mandatoryParam(PARAM_GATE_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGateDto = wsSupport.getByName(dbSession, qualityGateName);
wsSupport.checkCanLimitedEdit(dbSession, qualityGateDto);
UserDto user = getUser(dbSession, login);
apply(dbSession, qualityGateDto, user);
}
response.noContent();
}
private UserDto getUser(DbSession dbSession, String login) {
UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
checkFound(user, "User with login '%s' is not found", login);
return user;
}
protected abstract void apply(DbSession dbSession, QualityGateDto qualityGate, UserDto user);
}
| 3,086 | 38.075949 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/AddGroupAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.qualitygate.QualityGateGroupPermissionsDto;
import org.sonar.db.user.GroupDto;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_ADD_GROUP;
public class AddGroupAction extends AbstractGroupAction {
private final UuidFactory uuidFactory;
public AddGroupAction(DbClient dbClient, UuidFactory uuidFactory, QualityGatesWsSupport wsSupport) {
super(dbClient, wsSupport);
this.uuidFactory = uuidFactory;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_ADD_GROUP)
.setDescription("Allow a group of users to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("9.2");
super.defineGateAndGroupParameters(action);
}
@Override
protected void apply(DbSession dbSession, QualityGateDto qualityGate, GroupDto group) {
if (dbClient.qualityGateGroupPermissionsDao().exists(dbSession, qualityGate, group)) {
return;
}
dbClient.qualityGateGroupPermissionsDao().insert(dbSession,
new QualityGateGroupPermissionsDto()
.setUuid(uuidFactory.create())
.setGroupUuid(group.getUuid())
.setQualityGateUuid(qualityGate.getUuid()),
qualityGate.getName(),
group.getName());
dbSession.commit();
}
}
| 2,629 | 35.027397 | 102 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/AddUserAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.qualitygate.QualityGateUserPermissionsDto;
import org.sonar.db.user.UserDto;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_ADD_USER;
public class AddUserAction extends AbstractUserAction {
private final UuidFactory uuidFactory;
public AddUserAction(DbClient dbClient, UuidFactory uuidFactory, QualityGatesWsSupport wsSupport) {
super(dbClient, wsSupport);
this.uuidFactory = uuidFactory;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_ADD_USER)
.setDescription("Allow a user to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("9.2");
super.defineGateAndUserParameters(action);
}
@Override
protected void apply(DbSession dbSession, QualityGateDto qualityGate, UserDto user) {
if (dbClient.qualityGateUserPermissionDao().exists(dbSession, qualityGate, user)) {
return;
}
dbClient.qualityGateUserPermissionDao().insert(dbSession,
new QualityGateUserPermissionsDto()
.setUuid(uuidFactory.create())
.setUserUuid(user.getUuid())
.setQualityGateUuid(qualityGate.getUuid()), qualityGate.getName(), user.getLogin());
dbSession.commit();
}
}
| 2,590 | 34.986111 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/CopyAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateUpdater;
import org.sonar.server.user.UserSession;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_SOURCE_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.Qualitygates.QualityGate.newBuilder;
public class CopyAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final QualityGateUpdater qualityGateUpdater;
private final QualityGatesWsSupport wsSupport;
public CopyAction(DbClient dbClient, UserSession userSession, QualityGateUpdater qualityGateUpdater,
QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.userSession = userSession;
this.qualityGateUpdater = qualityGateUpdater;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("copy")
.setDescription("Copy a Quality Gate.<br>" +
"'sourceName' must be provided. Requires the 'Administer Quality Gates' permission.")
.setPost(true)
.setChangelog(
new Change("10.0", "Field 'id' in the response is deprecated"),
new Change("10.0", "Parameter 'id' is removed. Use 'sourceName' instead."),
new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'sourceName' instead."),
new Change("8.4", "Parameter 'sourceName' added"))
.setSince("4.3")
.setHandler(this);
action.createParam(PARAM_SOURCE_NAME)
.setDescription("The name of the quality gate to copy")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setExampleValue("My Quality Gate");
action.createParam(PARAM_NAME)
.setDescription("The name of the quality gate to create")
.setRequired(true)
.setExampleValue("My New Quality Gate");
}
@Override
public void handle(Request request, Response response) {
String sourceName = request.mandatoryParam(PARAM_SOURCE_NAME);
String destinationName = request.mandatoryParam(PARAM_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(ADMINISTER_QUALITY_GATES);
QualityGateDto qualityGate = wsSupport.getByName(dbSession, sourceName);
QualityGateDto copy = qualityGateUpdater.copy(dbSession, qualityGate, destinationName);
dbSession.commit();
writeProtobuf(newBuilder()
.setId(copy.getUuid())
.setName(copy.getName())
.build(), request, response);
}
}
}
| 4,058 | 39.188119 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/CreateAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import org.sonar.api.measures.Metric;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.Condition;
import org.sonar.server.qualitygate.QualityGateConditionsUpdater;
import org.sonar.server.qualitygate.QualityGateUpdater;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualitygates.CreateResponse;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.Metric.DIRECTION_BETTER;
import static org.sonar.api.measures.Metric.DIRECTION_WORST;
import static org.sonar.server.qualitygate.Condition.Operator.GREATER_THAN;
import static org.sonar.server.qualitygate.Condition.Operator.LESS_THAN;
import static org.sonar.server.qualitygate.QualityGateCaycChecker.CAYC_METRICS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_CREATE;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class CreateAction implements QualityGatesWsAction {
static final Map<String, Integer> DEFAULT_METRIC_VALUES = Map.of(
NEW_COVERAGE_KEY, 80,
NEW_DUPLICATED_LINES_DENSITY_KEY, 3
);
private static final Map<Integer, Condition.Operator> OPERATORS_BY_DIRECTION = Map.of(
DIRECTION_BETTER, LESS_THAN,
DIRECTION_WORST, GREATER_THAN);
public static final int NAME_MAXIMUM_LENGTH = 100;
private final DbClient dbClient;
private final UserSession userSession;
private final QualityGateUpdater qualityGateUpdater;
private final QualityGateConditionsUpdater qualityGateConditionsUpdater;
public CreateAction(DbClient dbClient, UserSession userSession, QualityGateUpdater qualityGateUpdater, QualityGateConditionsUpdater qualityGateConditionsUpdater) {
this.dbClient = dbClient;
this.userSession = userSession;
this.qualityGateUpdater = qualityGateUpdater;
this.qualityGateConditionsUpdater = qualityGateConditionsUpdater;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_CREATE)
.setPost(true)
.setDescription("Create a Quality Gate.<br>" +
"Requires the 'Administer Quality Gates' permission.")
.setSince("4.3")
.setChangelog(
new Change("10.0", "Field 'id' in the response is removed."),
new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."))
.setResponseExample(getClass().getResource("create-example.json"))
.setHandler(this);
action.createParam(PARAM_NAME)
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setDescription("The name of the quality gate to create")
.setExampleValue("My Quality Gate");
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
String name = request.mandatoryParam(PARAM_NAME);
QualityGateDto newQualityGate = qualityGateUpdater.create(dbSession, name);
addCaycConditions(dbSession, newQualityGate);
CreateResponse.Builder createResponse = CreateResponse.newBuilder()
.setName(newQualityGate.getName());
dbSession.commit();
writeProtobuf(createResponse.build(), request, response);
}
}
private void addCaycConditions(DbSession dbSession, QualityGateDto newQualityGate) {
CAYC_METRICS.forEach(m ->
qualityGateConditionsUpdater.createCondition(dbSession, newQualityGate, m.getKey(), OPERATORS_BY_DIRECTION.get(m.getDirection()).getDbValue(),
String.valueOf(getDefaultCaycValue(m)))
);
}
private static int getDefaultCaycValue(Metric<? extends Serializable> metric) {
return DEFAULT_METRIC_VALUES.containsKey(metric.getKey()) ?
DEFAULT_METRIC_VALUES.get(metric.getKey()) :
Objects.requireNonNull(metric.getBestValue()).intValue();
}
}
| 5,332 | 41.325397 | 165 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/CreateConditionAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateConditionsUpdater;
import org.sonarqube.ws.Qualitygates.CreateConditionResponse;
import static org.sonar.server.qualitygate.ws.QualityGatesWs.addConditionParams;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_CREATE_CONDITION;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ERROR;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_METRIC;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPERATOR;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class CreateConditionAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGateConditionsUpdater qualityGateConditionsUpdater;
private final QualityGatesWsSupport wsSupport;
public CreateConditionAction(DbClient dbClient, QualityGateConditionsUpdater qualityGateConditionsUpdater, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.qualityGateConditionsUpdater = qualityGateConditionsUpdater;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction createCondition = controller.createAction(ACTION_CREATE_CONDITION)
.setPost(true)
.setDescription("Add a new condition to a quality gate.<br>" +
"Parameter 'gateName' must be provided. Requires the 'Administer Quality Gates' permission.")
.setSince("4.3")
.setResponseExample(getClass().getResource("create-condition-example.json"))
.setChangelog(
new Change("7.6", "Removed optional 'warning' and 'period' parameters"),
new Change("7.6", "Made 'error' parameter mandatory"),
new Change("7.6", "Reduced the possible values of 'op' parameter to LT and GT"),
new Change("8.4", "Parameter 'gateName' added"),
new Change("8.4", "Parameter 'gateId' is deprecated. Use 'gateName' instead."),
new Change("10.0", "Parameter 'gateId' is removed. Use 'gateName' instead."))
.setHandler(this);
createCondition
.createParam(PARAM_GATE_NAME)
.setRequired(true)
.setDescription("Name of the quality gate")
.setExampleValue("SonarSource way");
addConditionParams(createCondition);
}
@Override
public void handle(Request request, Response response) {
String gateName = request.mandatoryParam(PARAM_GATE_NAME);
String metric = request.mandatoryParam(PARAM_METRIC);
String operator = request.mandatoryParam(PARAM_OPERATOR);
String error = request.mandatoryParam(PARAM_ERROR);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGate = wsSupport.getByName(dbSession, gateName);
wsSupport.checkCanLimitedEdit(dbSession, qualityGate);
QualityGateConditionDto condition = qualityGateConditionsUpdater.createCondition(dbSession, qualityGate, metric, operator, error);
CreateConditionResponse.Builder createConditionResponse = CreateConditionResponse.newBuilder()
.setId(condition.getUuid())
.setMetric(condition.getMetricKey())
.setError(condition.getErrorThreshold())
.setOp(condition.getOperator());
writeProtobuf(createConditionResponse.build(), request, response);
dbSession.commit();
}
}
}
| 4,660 | 44.696078 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/DeleteConditionAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ID;
public class DeleteConditionAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
public DeleteConditionAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction createCondition = controller.createAction("delete_condition")
.setDescription("Delete a condition from a quality gate.<br>" +
"Requires the 'Administer Quality Gates' permission.")
.setPost(true)
.setSince("4.3")
.setHandler(this);
createCondition
.createParam(PARAM_ID)
.setRequired(true)
.setDescription("Condition UUID")
.setExampleValue("2");
}
@Override
public void handle(Request request, Response response) {
String conditionUuid = request.mandatoryParam(PARAM_ID);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateConditionDto condition = wsSupport.getCondition(dbSession, conditionUuid);
QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByUuid(dbSession, condition.getQualityGateUuid());
checkState(qualityGateDto != null, "Condition '%s' is linked to an unknown quality gate '%s'", conditionUuid, condition.getQualityGateUuid());
wsSupport.checkCanLimitedEdit(dbSession, qualityGateDto);
dbClient.gateConditionDao().delete(condition, dbSession);
dbSession.commit();
response.noContent();
}
}
}
| 2,890 | 37.546667 | 148 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/DeselectAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
public class DeselectAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
public DeselectAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.wsSupport = wsSupport;
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("deselect")
.setDescription("Remove the association of a project from a quality gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer Quality Gates'</li>" +
"<li>'Administer' rights on the project</li>" +
"</ul>")
.setPost(true)
.setSince("4.3")
.setHandler(this)
.setChangelog(new Change("6.6", "The parameter 'gateId' was removed"),
new Change("8.3", "The parameter 'projectId' was removed"));
action.createParam(PARAM_PROJECT_KEY)
.setRequired(true)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setSince("6.1");
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = wsSupport.getProject(dbSession, request.mandatoryParam(PARAM_PROJECT_KEY));
dissociateProject(dbSession, project);
response.noContent();
}
}
private void dissociateProject(DbSession dbSession, ProjectDto project) {
wsSupport.checkCanAdminProject(project);
dbClient.projectQgateAssociationDao().deleteByProjectUuid(dbSession, project.getUuid());
dbSession.commit();
}
}
| 2,987 | 36.35 | 102 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/DestroyAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateFinder;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
public class DestroyAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
private final QualityGateFinder finder;
public DestroyAction(DbClient dbClient, QualityGatesWsSupport wsSupport, QualityGateFinder finder) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.finder = finder;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("destroy")
.setDescription("Delete a Quality Gate.<br>" +
"Parameter 'name' must be specified. Requires the 'Administer Quality Gates' permission.")
.setSince("4.3")
.setPost(true)
.setChangelog(
new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."),
new Change("8.4", "Parameter 'name' added"),
new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."))
.setHandler(this);
action.createParam(QualityGatesWsParameters.PARAM_NAME)
.setDescription("Name of the quality gate to delete")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setExampleValue("SonarSource Way");
}
@Override
public void handle(Request request, Response response) {
String name = request.mandatoryParam(QualityGatesWsParameters.PARAM_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGate;
qualityGate = wsSupport.getByName(dbSession, name);
QualityGateDto defaultQualityGate = finder.getDefault(dbSession);
checkArgument(!defaultQualityGate.getUuid().equals(qualityGate.getUuid()), "The default quality gate cannot be removed");
wsSupport.checkCanEdit(qualityGate);
dbClient.projectQgateAssociationDao().deleteByQGateUuid(dbSession, qualityGate.getUuid());
dbClient.qualityGateGroupPermissionsDao().deleteByQualityGate(dbSession, qualityGate);
dbClient.qualityGateUserPermissionDao().deleteByQualityGate(dbSession, qualityGate);
dbClient.qualityGateDao().delete(qualityGate, dbSession);
dbSession.commit();
response.noContent();
}
}
}
| 3,604 | 38.615385 | 127 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/GetByProjectAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonar.server.qualitygate.QualityGateFinder.QualityGateData;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualitygates.GetByProjectResponse;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_GET_BY_PROJECT;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class GetByProjectAction implements QualityGatesWsAction {
private static final String PARAM_PROJECT = "project";
private final UserSession userSession;
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final QualityGateFinder qualityGateFinder;
public GetByProjectAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder, QualityGateFinder qualityGateFinder) {
this.userSession = userSession;
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.qualityGateFinder = qualityGateFinder;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_GET_BY_PROJECT)
.setInternal(false)
.setSince("6.1")
.setDescription("Get the quality gate of a project.<br />" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"<li>'Browse' on the specified project</li>" +
"</ul>")
.setResponseExample(getClass().getResource("get_by_project-example.json"))
.setHandler(this)
.setChangelog(
new Change("10.0", "Field 'id' in the response has been removed"),
new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."),
new Change("6.6", "The parameter 'projectId' has been removed"),
new Change("6.6", "The parameter 'projectKey' has been renamed to 'project'"),
new Change("6.6", "This webservice is now part of the public API"));
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, request.mandatoryParam(PARAM_PROJECT));
if (!userSession.hasEntityPermission(USER, project) &&
!userSession.hasEntityPermission(ADMIN, project)) {
throw insufficientPrivilegesException();
}
QualityGateData data = qualityGateFinder.getEffectiveQualityGate(dbSession, project);
writeProtobuf(buildResponse(data), request, response);
}
}
private static GetByProjectResponse buildResponse(QualityGateData qg) {
GetByProjectResponse.Builder response = GetByProjectResponse.newBuilder();
response.getQualityGateBuilder()
.setName(qg.getName())
.setDefault(qg.isDefault());
return response.build();
}
}
| 4,562 | 40.108108 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/ListAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import com.google.common.io.Resources;
import java.util.Collection;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateCaycChecker;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonarqube.ws.Qualitygates.ListWsResponse;
import org.sonarqube.ws.Qualitygates.ListWsResponse.QualityGate;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ListAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
private final QualityGateFinder finder;
private final QualityGateCaycChecker qualityGateCaycChecker;
public ListAction(DbClient dbClient, QualityGatesWsSupport wsSupport, QualityGateFinder finder, QualityGateCaycChecker qualityGateCaycChecker) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.finder = finder;
this.qualityGateCaycChecker = qualityGateCaycChecker;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("list")
.setDescription("Get a list of quality gates")
.setSince("4.3")
.setResponseExample(Resources.getResource(this.getClass(), "list-example.json"))
.setChangelog(
new Change("10.0", "Field 'default' in the response has been removed"),
new Change("10.0", "Field 'id' in the response has been removed"),
new Change("9.9", "'caycStatus' field is added on quality gate"),
new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."),
new Change("7.0", "'isDefault' field is added on quality gate"),
new Change("7.0", "'default' field on root level is deprecated"),
new Change("7.0", "'isBuiltIn' field is added in the response"),
new Change("7.0", "'actions' fields are added in the response"))
.setHandler(this);
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto defaultQualityGate = finder.getDefault(dbSession);
Collection<QualityGateDto> qualityGates = dbClient.qualityGateDao().selectAll(dbSession);
writeProtobuf(buildResponse(dbSession, qualityGates, defaultQualityGate), request, response);
}
}
private ListWsResponse buildResponse(DbSession dbSession, Collection<QualityGateDto> qualityGates, @Nullable QualityGateDto defaultQualityGate) {
String defaultUuid = defaultQualityGate == null ? null : defaultQualityGate.getUuid();
ListWsResponse.Builder builder = ListWsResponse.newBuilder()
.setActions(ListWsResponse.RootActions.newBuilder().setCreate(wsSupport.isQualityGateAdmin()))
.addAllQualitygates(qualityGates.stream()
.map(qualityGate -> QualityGate.newBuilder()
.setName(qualityGate.getName())
.setIsDefault(qualityGate.getUuid().equals(defaultUuid))
.setIsBuiltIn(qualityGate.isBuiltIn())
.setCaycStatus(qualityGateCaycChecker.checkCaycCompliant(dbSession, qualityGate.getUuid()).toString())
.setActions(wsSupport.getActions(dbSession, qualityGate, defaultQualityGate))
.build())
.toList());
return builder.build();
}
}
| 4,406 | 43.969388 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/ProjectStatusAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.server.ws.Change;
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.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.qualitygate.QualityGateCaycChecker;
import org.sonar.server.qualitygate.QualityGateCaycStatus;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.KeyExamples;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_PROJECT_STATUS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ANALYSIS_ID;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_BRANCH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_ID;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PULL_REQUEST;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ProjectStatusAction implements QualityGatesWsAction {
private static final String QG_STATUSES_ONE_LINE = Arrays.stream(ProjectStatusResponse.Status.values())
.map(Enum::toString)
.collect(Collectors.joining(", "));
private static final String MSG_ONE_PROJECT_PARAMETER_ONLY = String.format("Either '%s', '%s' or '%s' must be provided", PARAM_ANALYSIS_ID, PARAM_PROJECT_ID, PARAM_PROJECT_KEY);
private static final String MSG_ONE_BRANCH_PARAMETER_ONLY = String.format("Either '%s' or '%s' can be provided, not both", PARAM_BRANCH, PARAM_PULL_REQUEST);
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
private final QualityGateCaycChecker qualityGateCaycChecker;
public ProjectStatusAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, QualityGateCaycChecker qualityGateCaycChecker) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
this.qualityGateCaycChecker = qualityGateCaycChecker;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_PROJECT_STATUS)
.setDescription(String.format("Get the quality gate status of a project or a Compute Engine task.<br />" +
"%s <br />" +
"The different statuses returned are: %s. The %s status is returned when there is no quality gate associated with the analysis.<br />" +
"Returns an HTTP code 404 if the analysis associated with the task is not found or does not exist.<br />" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"<li>'Browse' on the specified project</li>" +
"<li>'Execute Analysis' on the specified project</li>" +
"</ul>", MSG_ONE_PROJECT_PARAMETER_ONLY, QG_STATUSES_ONE_LINE, ProjectStatusResponse.Status.NONE))
.setResponseExample(getClass().getResource("project_status-example.json"))
.setSince("5.3")
.setHandler(this)
.setChangelog(
new Change("10.0", "The fields 'periods' and 'periodIndex' in the response are removed"),
new Change("9.9", "'caycStatus' field is added to the response"),
new Change("9.5", "The 'Execute Analysis' permission also allows to access the endpoint"),
new Change("8.5", "The field 'periods' in the response is deprecated. Use 'period' instead"),
new Change("7.7", "The parameters 'branch' and 'pullRequest' were added"),
new Change("7.6", "The field 'warning' in the response is deprecated"),
new Change("6.4", "The field 'ignoredConditions' is added to the response"));
action.createParam(PARAM_ANALYSIS_ID)
.setDescription("Analysis id")
.setExampleValue(Uuids.UUID_EXAMPLE_04);
action.createParam(PARAM_PROJECT_ID)
.setSince("5.4")
.setDescription("Project UUID. Doesn't work with branches or pull requests")
.setExampleValue(Uuids.UUID_EXAMPLE_01);
action.createParam(PARAM_PROJECT_KEY)
.setSince("5.4")
.setDescription("Project key")
.setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setSince("7.7")
.setDescription("Branch key")
.setExampleValue(KeyExamples.KEY_BRANCH_EXAMPLE_001);
action.createParam(PARAM_PULL_REQUEST)
.setSince("7.7")
.setDescription("Pull request id")
.setExampleValue(KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001);
}
@Override
public void handle(Request request, Response response) throws Exception {
String analysisId = request.param(PARAM_ANALYSIS_ID);
String projectId = request.param(PARAM_PROJECT_ID);
String projectKey = request.param(PARAM_PROJECT_KEY);
String branchKey = request.param(PARAM_BRANCH);
String pullRequestId = request.param(PARAM_PULL_REQUEST);
checkRequest(
!isNullOrEmpty(analysisId)
^ !isNullOrEmpty(projectId)
^ !isNullOrEmpty(projectKey),
MSG_ONE_PROJECT_PARAMETER_ONLY);
checkRequest(isNullOrEmpty(branchKey) || isNullOrEmpty(pullRequestId), MSG_ONE_BRANCH_PARAMETER_ONLY);
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectStatusResponse projectStatusResponse = doHandle(dbSession, analysisId, projectId, projectKey, branchKey, pullRequestId);
writeProtobuf(projectStatusResponse, request, response);
}
}
private ProjectStatusResponse doHandle(DbSession dbSession, @Nullable String analysisId, @Nullable String projectUuid,
@Nullable String projectKey, @Nullable String branchKey, @Nullable String pullRequestId) {
ProjectAndSnapshot projectAndSnapshot = getProjectAndSnapshot(dbSession, analysisId, projectUuid, projectKey, branchKey, pullRequestId);
checkPermission(projectAndSnapshot.project);
Optional<String> measureData = loadQualityGateDetails(dbSession, projectAndSnapshot, analysisId != null);
QualityGateCaycStatus caycStatus = qualityGateCaycChecker.checkCaycCompliantFromProject(dbSession, projectAndSnapshot.project.getUuid());
return ProjectStatusResponse.newBuilder()
.setProjectStatus(new QualityGateDetailsFormatter(measureData.orElse(null), projectAndSnapshot.snapshotDto.orElse(null), caycStatus).format())
.build();
}
private ProjectAndSnapshot getProjectAndSnapshot(DbSession dbSession, @Nullable String analysisId, @Nullable String projectUuid,
@Nullable String projectKey, @Nullable String branchKey, @Nullable String pullRequestId) {
if (!isNullOrEmpty(analysisId)) {
return getSnapshotThenProject(dbSession, analysisId);
}
if (!isNullOrEmpty(projectUuid) ^ !isNullOrEmpty(projectKey)) {
return getProjectThenSnapshot(dbSession, projectUuid, projectKey, branchKey, pullRequestId);
}
throw BadRequestException.create(MSG_ONE_PROJECT_PARAMETER_ONLY);
}
private ProjectAndSnapshot getProjectThenSnapshot(DbSession dbSession, @Nullable String projectUuid, @Nullable String projectKey,
@Nullable String branchKey, @Nullable String pullRequestId) {
ProjectDto projectDto;
BranchDto branchDto;
if (projectUuid != null) {
projectDto = componentFinder.getProjectByUuid(dbSession, projectUuid);
branchDto = componentFinder.getMainBranch(dbSession, projectDto);
} else {
projectDto = componentFinder.getProjectByKey(dbSession, projectKey);
branchDto = componentFinder.getBranchOrPullRequest(dbSession, projectDto, branchKey, pullRequestId);
}
Optional<SnapshotDto> snapshot = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchDto.getUuid());
return new ProjectAndSnapshot(projectDto, branchDto, snapshot.orElse(null));
}
private ProjectAndSnapshot getSnapshotThenProject(DbSession dbSession, String analysisUuid) {
SnapshotDto snapshotDto = getSnapshot(dbSession, analysisUuid);
BranchDto branchDto = dbClient.branchDao().selectByUuid(dbSession, snapshotDto.getRootComponentUuid())
.orElseThrow(() -> new IllegalStateException(String.format("Branch '%s' not found", snapshotDto.getUuid())));
ProjectDto projectDto = dbClient.projectDao().selectByUuid(dbSession, branchDto.getProjectUuid())
.orElseThrow(() -> new IllegalStateException(String.format("Project '%s' not found", branchDto.getProjectUuid())));
return new ProjectAndSnapshot(projectDto, branchDto, snapshotDto);
}
private SnapshotDto getSnapshot(DbSession dbSession, String analysisUuid) {
Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectByUuid(dbSession, analysisUuid);
return checkFoundWithOptional(snapshotDto, "Analysis with id '%s' is not found", analysisUuid);
}
private Optional<String> loadQualityGateDetails(DbSession dbSession, ProjectAndSnapshot projectAndSnapshot, boolean onAnalysis) {
if (onAnalysis) {
if (!projectAndSnapshot.snapshotDto.isPresent()) {
return Optional.empty();
}
// get the gate status as it was computed during the specified analysis
String analysisUuid = projectAndSnapshot.snapshotDto.get().getUuid();
return dbClient.measureDao().selectMeasure(dbSession, analysisUuid, projectAndSnapshot.branch.getUuid(), CoreMetrics.QUALITY_GATE_DETAILS_KEY)
.map(MeasureDto::getData);
}
// do not restrict to a specified analysis, use the live measure
Optional<LiveMeasureDto> measure = dbClient.liveMeasureDao().selectMeasure(dbSession, projectAndSnapshot.branch.getUuid(), CoreMetrics.QUALITY_GATE_DETAILS_KEY);
return measure.map(LiveMeasureDto::getDataAsString);
}
private void checkPermission(ProjectDto project) {
if (!userSession.hasEntityPermission(UserRole.ADMIN, project) &&
!userSession.hasEntityPermission(UserRole.USER, project) &&
!userSession.hasEntityPermission(UserRole.SCAN, project) &&
!userSession.hasPermission(GlobalPermission.SCAN)) {
throw insufficientPrivilegesException();
}
}
@Immutable
private static class ProjectAndSnapshot {
private final BranchDto branch;
private final Optional<SnapshotDto> snapshotDto;
private final ProjectDto project;
private ProjectAndSnapshot(ProjectDto project, BranchDto branch, @Nullable SnapshotDto snapshotDto) {
this.project = project;
this.branch = branch;
this.snapshotDto = Optional.ofNullable(snapshotDto);
}
}
}
| 12,448 | 49.812245 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.sonar.db.component.SnapshotDto;
import org.sonar.server.qualitygate.QualityGateCaycStatus;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.NewCodePeriod;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.api.utils.DateUtils.formatDateTime;
public class QualityGateDetailsFormatter {
private final Optional<String> optionalMeasureData;
private final Optional<SnapshotDto> optionalSnapshot;
private final QualityGateCaycStatus caycStatus;
private final ProjectStatusResponse.ProjectStatus.Builder projectStatusBuilder;
public QualityGateDetailsFormatter(@Nullable String measureData, @Nullable SnapshotDto snapshot, QualityGateCaycStatus caycStatus) {
this.optionalMeasureData = Optional.ofNullable(measureData);
this.optionalSnapshot = Optional.ofNullable(snapshot);
this.caycStatus = caycStatus;
this.projectStatusBuilder = ProjectStatusResponse.ProjectStatus.newBuilder();
}
public ProjectStatusResponse.ProjectStatus format() {
if (!optionalMeasureData.isPresent()) {
return newResponseWithoutQualityGateDetails();
}
JsonObject json = JsonParser.parseString(optionalMeasureData.get()).getAsJsonObject();
ProjectStatusResponse.Status qualityGateStatus = measureLevelToQualityGateStatus(json.get("level").getAsString());
projectStatusBuilder.setStatus(qualityGateStatus);
projectStatusBuilder.setCaycStatus(caycStatus.toString());
formatIgnoredConditions(json);
formatConditions(json.getAsJsonArray("conditions"));
formatPeriods();
return projectStatusBuilder.build();
}
private void formatIgnoredConditions(JsonObject json) {
JsonElement ignoredConditions = json.get("ignoredConditions");
if (ignoredConditions != null) {
projectStatusBuilder.setIgnoredConditions(ignoredConditions.getAsBoolean());
} else {
projectStatusBuilder.setIgnoredConditions(false);
}
}
private void formatPeriods() {
if (!optionalSnapshot.isPresent()) {
return;
}
NewCodePeriod.Builder periodBuilder = NewCodePeriod.newBuilder();
SnapshotDto snapshot = this.optionalSnapshot.get();
if (isNullOrEmpty(snapshot.getPeriodMode())) {
return;
}
periodBuilder.setMode(snapshot.getPeriodMode());
Long periodDate = snapshot.getPeriodDate();
if (periodDate != null) {
String formattedDateTime = formatDateTime(periodDate);
periodBuilder.setDate(formattedDateTime);
}
String periodModeParameter = snapshot.getPeriodModeParameter();
if (!isNullOrEmpty(periodModeParameter)) {
periodBuilder.setParameter(periodModeParameter);
}
projectStatusBuilder.setPeriod(periodBuilder);
}
private void formatConditions(@Nullable JsonArray jsonConditions) {
if (jsonConditions == null) {
return;
}
StreamSupport.stream(jsonConditions.spliterator(), false)
.map(JsonElement::getAsJsonObject)
.filter(isConditionOnValidPeriod())
.forEach(this::formatCondition);
}
private void formatCondition(JsonObject jsonCondition) {
ProjectStatusResponse.Condition.Builder conditionBuilder = ProjectStatusResponse.Condition.newBuilder();
formatConditionLevel(conditionBuilder, jsonCondition);
formatConditionMetric(conditionBuilder, jsonCondition);
formatConditionOperation(conditionBuilder, jsonCondition);
formatConditionWarningThreshold(conditionBuilder, jsonCondition);
formatConditionErrorThreshold(conditionBuilder, jsonCondition);
formatConditionActual(conditionBuilder, jsonCondition);
projectStatusBuilder.addConditions(conditionBuilder);
}
private static void formatConditionActual(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement actual = jsonCondition.get("actual");
if (actual != null && !isNullOrEmpty(actual.getAsString())) {
conditionBuilder.setActualValue(actual.getAsString());
}
}
private static void formatConditionErrorThreshold(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement error = jsonCondition.get("error");
if (error != null && !isNullOrEmpty(error.getAsString())) {
conditionBuilder.setErrorThreshold(error.getAsString());
}
}
private static void formatConditionWarningThreshold(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement warning = jsonCondition.get("warning");
if (warning != null && !isNullOrEmpty(warning.getAsString())) {
conditionBuilder.setWarningThreshold(warning.getAsString());
}
}
private static void formatConditionOperation(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement op = jsonCondition.get("op");
if (op != null && !isNullOrEmpty(op.getAsString())) {
String stringOp = op.getAsString();
ProjectStatusResponse.Comparator comparator = measureOpToQualityGateComparator(stringOp);
conditionBuilder.setComparator(comparator);
}
}
private static void formatConditionMetric(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement metric = jsonCondition.get("metric");
if (metric != null && !isNullOrEmpty(metric.getAsString())) {
conditionBuilder.setMetricKey(metric.getAsString());
}
}
private static void formatConditionLevel(ProjectStatusResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {
JsonElement measureLevel = jsonCondition.get("level");
if (measureLevel != null && !isNullOrEmpty(measureLevel.getAsString())) {
conditionBuilder.setStatus(measureLevelToQualityGateStatus(measureLevel.getAsString()));
}
}
private static ProjectStatusResponse.Status measureLevelToQualityGateStatus(String measureLevel) {
for (ProjectStatusResponse.Status status : ProjectStatusResponse.Status.values()) {
if (status.name().equals(measureLevel)) {
return status;
}
}
throw new IllegalStateException(String.format("Unknown quality gate status '%s'", measureLevel));
}
private static ProjectStatusResponse.Comparator measureOpToQualityGateComparator(String measureOp) {
for (ProjectStatusResponse.Comparator comparator : ProjectStatusResponse.Comparator.values()) {
if (comparator.name().equals(measureOp)) {
return comparator;
}
}
throw new IllegalStateException(String.format("Unknown quality gate comparator '%s'", measureOp));
}
private ProjectStatusResponse.ProjectStatus newResponseWithoutQualityGateDetails() {
return ProjectStatusResponse.ProjectStatus.newBuilder().setStatus(ProjectStatusResponse.Status.NONE).setCaycStatus(caycStatus.toString()).build();
}
private static Predicate<JsonObject> isConditionOnValidPeriod() {
return jsonCondition -> {
JsonElement periodIndex = jsonCondition.get("period");
if (periodIndex == null) {
return true;
}
int period = periodIndex.getAsInt();
// Ignore period that was set on non leak period (for retro compatibility with project that hasn't been analyzed since a while)
return period == 1;
};
}
}
| 8,447 | 39.228571 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGateWsModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.core.platform.Module;
public class QualityGateWsModule extends Module {
@Override
protected void configureModule() {
add(
AddGroupAction.class,
AddUserAction.class,
CopyAction.class,
CreateAction.class,
CreateConditionAction.class,
DeleteConditionAction.class,
DeselectAction.class,
DestroyAction.class,
GetByProjectAction.class,
ListAction.class,
ProjectStatusAction.class,
QualityGatesWs.class,
QualityGatesWsSupport.class,
RemoveGroupAction.class,
RemoveUserAction.class,
RenameAction.class,
SearchAction.class,
SearchGroupsAction.class,
SearchUsersAction.class,
SelectAction.class,
SetAsDefaultAction.class,
ShowAction.class,
UpdateConditionAction.class
);
}
}
| 1,720 | 30.87037 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWs.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.qualitygate.Condition;
import static org.sonar.server.qualitygate.QualityGateConditionsUpdater.INVALID_METRIC_KEYS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.CONTROLLER_QUALITY_GATES;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ERROR;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_METRIC;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPERATOR;
public class QualityGatesWs implements WebService {
private static final int CONDITION_MAX_LENGTH = 64;
private final QualityGatesWsAction[] actions;
public QualityGatesWs(QualityGatesWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER_QUALITY_GATES)
.setSince("4.3")
.setDescription("Manage quality gates, including conditions and project association.");
for (QualityGatesWsAction action : actions) {
action.define(controller);
}
controller.done();
}
static void addConditionParams(NewAction action) {
action
.createParam(PARAM_METRIC)
.setDescription("Condition metric.<br/>" +
" Only metric of the following types are allowed:" +
"<ul>" +
"<li>INT</li>" +
"<li>MILLISEC</li>" +
"<li>RATING</li>" +
"<li>WORK_DUR</li>" +
"<li>FLOAT</li>" +
"<li>PERCENT</li>" +
"<li>LEVEL</li></ul>" +
"Following metrics are forbidden:" +
"<ul>" + getInvalidMetrics() + "</ul>")
.setRequired(true)
.setExampleValue("blocker_violations, vulnerabilities, new_code_smells");
action.createParam(PARAM_OPERATOR)
.setDescription("Condition operator:<br/>" +
"<ul>" +
"<li>LT = is lower than</li>" +
"<li>GT = is greater than</li></ul>")
.setExampleValue(Condition.Operator.GREATER_THAN.getDbValue())
.setPossibleValues(getPossibleOperators());
action.createParam(PARAM_ERROR)
.setMaximumLength(CONDITION_MAX_LENGTH)
.setDescription("Condition error threshold")
.setRequired(true)
.setExampleValue("10");
}
private static String getInvalidMetrics() {
return INVALID_METRIC_KEYS.stream().map(s -> "<li>" + s + "</li>")
.collect(Collectors.joining());
}
private static Set<String> getPossibleOperators() {
return Stream.of(Condition.Operator.values())
.map(Condition.Operator::getDbValue)
.collect(Collectors.toSet());
}
}
| 3,610 | 35.11 | 96 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.server.ws.WsAction;
public interface QualityGatesWsAction extends WsAction {
// Marker interface
}
| 1,005 | 34.928571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsParameters.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
public class QualityGatesWsParameters {
public static final String CONTROLLER_QUALITY_GATES = "api/qualitygates";
public static final String ACTION_PROJECT_STATUS = "project_status";
public static final String ACTION_GET_BY_PROJECT = "get_by_project";
public static final String ACTION_SELECT = "select";
public static final String ACTION_CREATE = "create";
public static final String ACTION_CREATE_CONDITION = "create_condition";
public static final String ACTION_UPDATE_CONDITION = "update_condition";
public static final String ACTION_ADD_GROUP = "add_group";
public static final String ACTION_ADD_USER = "add_user";
public static final String ACTION_REMOVE_GROUP = "remove_group";
public static final String ACTION_REMOVE_USER = "remove_user";
public static final String ACTION_SEARCH_GROUPS = "search_groups";
public static final String ACTION_SEARCH_USERS = "search_users";
public static final String PARAM_ANALYSIS_ID = "analysisId";
public static final String PARAM_BRANCH = "branch";
public static final String PARAM_PULL_REQUEST = "pullRequest";
public static final String PARAM_PROJECT_ID = "projectId";
public static final String PARAM_PROJECT_KEY = "projectKey";
public static final String PARAM_PAGE_SIZE = "pageSize";
public static final String PARAM_PAGE = "page";
public static final String PARAM_QUERY = "query";
public static final String PARAM_CURRENT_NAME = "currentName";
public static final String PARAM_NAME = "name";
public static final String PARAM_ERROR = "error";
public static final String PARAM_OPERATOR = "op";
public static final String PARAM_METRIC = "metric";
public static final String PARAM_GATE_NAME = "gateName";
public static final String PARAM_ID = "id";
public static final String PARAM_SOURCE_NAME = "sourceName";
private QualityGatesWsParameters() {
// prevent instantiation
}
}
| 2,777 | 45.3 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/QualityGatesWsSupport.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.Objects;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualitygates;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
public class QualityGatesWsSupport {
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
public QualityGatesWsSupport(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
}
public QualityGateDto getByUuid(DbSession dbSession, String qualityGateUuid) {
return checkFound(
dbClient.qualityGateDao().selectByUuid(dbSession, qualityGateUuid),
"No quality gate has been found for id %s", qualityGateUuid);
}
public QualityGateDto getByName(DbSession dbSession, String qualityGateName) {
return checkFound(dbClient.qualityGateDao().selectByName(dbSession, qualityGateName),
"No quality gate has been found for name %s", qualityGateName);
}
QualityGateConditionDto getCondition(DbSession dbSession, String uuid) {
return checkFound(dbClient.gateConditionDao().selectByUuid(uuid, dbSession), "No quality gate condition with uuid '%s'", uuid);
}
boolean isQualityGateAdmin() {
return userSession.hasPermission(ADMINISTER_QUALITY_GATES);
}
Qualitygates.Actions getActions(DbSession dbSession, QualityGateDto qualityGate, @Nullable QualityGateDto defaultQualityGate) {
boolean isDefault = defaultQualityGate != null && Objects.equals(defaultQualityGate.getUuid(), qualityGate.getUuid());
boolean isBuiltIn = qualityGate.isBuiltIn();
boolean isQualityGateAdmin = isQualityGateAdmin();
boolean canLimitedEdit = isQualityGateAdmin || hasLimitedPermission(dbSession, qualityGate);
return Qualitygates.Actions.newBuilder()
.setCopy(isQualityGateAdmin)
.setRename(!isBuiltIn && isQualityGateAdmin)
.setManageConditions(!isBuiltIn && canLimitedEdit)
.setDelete(!isDefault && !isBuiltIn && isQualityGateAdmin)
.setSetAsDefault(!isDefault && isQualityGateAdmin)
.setAssociateProjects(!isDefault && isQualityGateAdmin)
.setDelegate(!isBuiltIn && canLimitedEdit)
.build();
}
void checkCanEdit(QualityGateDto qualityGate) {
checkNotBuiltIn(qualityGate);
userSession.checkPermission(ADMINISTER_QUALITY_GATES);
}
void checkCanLimitedEdit(DbSession dbSession, QualityGateDto qualityGate) {
checkNotBuiltIn(qualityGate);
if (!userSession.hasPermission(ADMINISTER_QUALITY_GATES)
&& !hasLimitedPermission(dbSession, qualityGate)) {
throw insufficientPrivilegesException();
}
}
boolean hasLimitedPermission(DbSession dbSession, QualityGateDto qualityGate) {
return userHasPermission(dbSession, qualityGate) || userHasGroupPermission(dbSession, qualityGate);
}
boolean userHasGroupPermission(DbSession dbSession, QualityGateDto qualityGate) {
return userSession.isLoggedIn() && dbClient.qualityGateGroupPermissionsDao().exists(dbSession, qualityGate, userSession.getGroups());
}
boolean userHasPermission(DbSession dbSession, QualityGateDto qualityGate) {
return userSession.isLoggedIn() && dbClient.qualityGateUserPermissionDao().exists(dbSession, qualityGate.getUuid(), userSession.getUuid());
}
void checkCanAdminProject(ProjectDto project) {
if (userSession.hasPermission(ADMINISTER_QUALITY_GATES)
|| userSession.hasEntityPermission(ADMIN, project)) {
return;
}
throw insufficientPrivilegesException();
}
ProjectDto getProject(DbSession dbSession, String projectKey) {
return componentFinder.getProjectByKey(dbSession, projectKey);
}
private static void checkNotBuiltIn(QualityGateDto qualityGate) {
checkArgument(!qualityGate.isBuiltIn(), "Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName());
}
}
| 5,394 | 41.148438 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/RemoveGroupAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.GroupDto;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_REMOVE_GROUP;
public class RemoveGroupAction extends AbstractGroupAction {
public RemoveGroupAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
super(dbClient, wsSupport);
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_REMOVE_GROUP)
.setDescription("Remove the ability from a group to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("9.2");
super.defineGateAndGroupParameters(action);
}
@Override
protected void apply(DbSession dbSession, QualityGateDto qualityGate, GroupDto group) {
if (!dbClient.qualityGateGroupPermissionsDao().exists(dbSession, qualityGate, group)) {
return;
}
dbClient.qualityGateGroupPermissionsDao().deleteByQualityGateAndGroup(dbSession, qualityGate, group);
dbSession.commit();
}
}
| 2,260 | 35.467742 | 105 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/RemoveUserAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.UserDto;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_REMOVE_USER;
public class RemoveUserAction extends AbstractUserAction {
public RemoveUserAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
super(dbClient, wsSupport);
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_REMOVE_USER)
.setDescription("Remove the ability from an user to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("9.2");
super.defineGateAndUserParameters(action);
}
@Override
protected void apply(DbSession dbSession, QualityGateDto qualityGate, UserDto user) {
if (!dbClient.qualityGateUserPermissionDao().exists(dbSession, qualityGate, user)) {
return;
}
dbClient.qualityGateUserPermissionDao().deleteByQualityGateAndUser(dbSession, qualityGate, user);
dbSession.commit();
}
}
| 2,244 | 35.209677 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/RenameAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonarqube.ws.Qualitygates.QualityGate;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_CURRENT_NAME;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class RenameAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
public RenameAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("rename")
.setPost(true)
.setDescription("Rename a Quality Gate.<br>" +
"'currentName' must be specified. Requires the 'Administer Quality Gates' permission.")
.setSince("4.3")
.setChangelog(
new Change("10.0", "Field 'id' in the response is deprecated"),
new Change("10.0", "Parameter 'id' is removed. Use 'currentName' instead."),
new Change("8.4", "Parameter 'currentName' added"),
new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'currentName' instead."))
.setHandler(this);
action.createParam(PARAM_CURRENT_NAME)
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setDescription("Current name of the quality gate")
.setExampleValue("My Quality Gate");
action.createParam(PARAM_NAME)
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setDescription("New name of the quality gate")
.setExampleValue("My New Quality Gate");
}
@Override
public void handle(Request request, Response response) {
String currentName = request.mandatoryParam(PARAM_CURRENT_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGate;
qualityGate = wsSupport.getByName(dbSession, currentName);
QualityGateDto renamedQualityGate = rename(dbSession, qualityGate, request.mandatoryParam(PARAM_NAME));
writeProtobuf(QualityGate.newBuilder()
.setId(renamedQualityGate.getUuid())
.setName(renamedQualityGate.getName())
.build(), request, response);
}
}
private QualityGateDto rename(DbSession dbSession, QualityGateDto qualityGate, String name) {
wsSupport.checkCanEdit(qualityGate);
checkNotAlreadyExists(dbSession, qualityGate, name);
qualityGate.setName(name);
dbClient.qualityGateDao().update(qualityGate, dbSession);
dbSession.commit();
return qualityGate;
}
private void checkNotAlreadyExists(DbSession dbSession, QualityGateDto qualityGate, String name) {
QualityGateDto existingQgate = dbClient.qualityGateDao().selectByName(dbSession, name);
boolean isModifyingCurrentQgate = existingQgate == null || existingQgate.getUuid().equals(qualityGate.getUuid());
checkArgument(isModifyingCurrentQgate, "Name '%s' has already been taken", name);
}
}
| 4,392 | 39.302752 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SearchAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import com.google.common.io.Resources;
import java.util.Collection;
import java.util.List;
import org.sonar.api.server.ws.Change;
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.Paging;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.ProjectQgateAssociationDto;
import org.sonar.db.qualitygate.ProjectQgateAssociationQuery;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualitygates;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.utils.Paging.forPageIndex;
import static org.sonar.db.qualitygate.ProjectQgateAssociationQuery.ANY;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PAGE;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PAGE_SIZE;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_QUERY;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final QualityGatesWsSupport wsSupport;
public SearchAction(DbClient dbClient, UserSession userSession, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("search")
.setDescription("Search for projects associated (or not) to a quality gate.<br/>" +
"Only authorized projects for the current user will be returned.")
.setSince("4.3")
.setResponseExample(Resources.getResource(this.getClass(), "search-example.json"))
.setChangelog(
new Change("10.0", "deprecated 'more' response field has been removed"),
new Change("10.0", "Parameter 'gateId' is removed. Use 'gateName' instead."),
new Change("8.4", "Parameter 'gateName' added"),
new Change("8.4", "Parameter 'gateId' is deprecated. Format changes from integer to string. Use 'gateName' instead."),
new Change("7.9", "New field 'paging' in response"),
new Change("7.9", "New field 'key' returning the project key in 'results' response"),
new Change("7.9", "Field 'more' is deprecated in the response"))
.setHandler(this);
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setExampleValue("SonarSource Way");
action.createParam(PARAM_QUERY)
.setDescription("To search for projects containing this string. If this parameter is set, \"selected\" is set to \"all\".")
.setExampleValue("abc");
action.addSelectionModeParam();
action.createParam(PARAM_PAGE)
.setDescription("Page number")
.setDefaultValue("1")
.setExampleValue("2");
action.createParam(PARAM_PAGE_SIZE)
.setDescription("Page size")
.setExampleValue("10");
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
String gateName = request.mandatoryParam(PARAM_GATE_NAME);
QualityGateDto qualityGate;
qualityGate = wsSupport.getByName(dbSession, gateName);
ProjectQgateAssociationQuery projectQgateAssociationQuery = ProjectQgateAssociationQuery.builder()
.qualityGate(qualityGate)
.membership(request.param(PARAM_QUERY) == null ? request.param(SELECTED) : ANY)
.projectSearch(request.param(PARAM_QUERY))
.pageIndex(request.paramAsInt(PARAM_PAGE))
.pageSize(request.paramAsInt(PARAM_PAGE_SIZE))
.build();
List<ProjectQgateAssociationDto> projects = dbClient.projectQgateAssociationDao().selectProjects(dbSession, projectQgateAssociationQuery);
List<ProjectQgateAssociationDto> authorizedProjects = keepAuthorizedProjects(dbSession, projects);
Paging paging = forPageIndex(projectQgateAssociationQuery.pageIndex())
.withPageSize(projectQgateAssociationQuery.pageSize())
.andTotal(authorizedProjects.size());
List<ProjectQgateAssociationDto> paginatedProjects = getPaginatedProjects(authorizedProjects, paging);
Qualitygates.SearchResponse.Builder createResponse = Qualitygates.SearchResponse.newBuilder();
createResponse.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total())
.build();
for (ProjectQgateAssociationDto project : paginatedProjects) {
createResponse.addResultsBuilder()
.setName(project.getName())
.setKey(project.getKey())
.setSelected(project.getGateUuid() != null);
}
writeProtobuf(createResponse.build(), request, response);
}
}
private static List<ProjectQgateAssociationDto> getPaginatedProjects(List<ProjectQgateAssociationDto> projects, Paging paging) {
return projects.stream().skip(paging.offset()).limit(paging.pageSize()).toList();
}
private List<ProjectQgateAssociationDto> keepAuthorizedProjects(DbSession dbSession, List<ProjectQgateAssociationDto> projects) {
List<String> projectUuids = projects.stream().map(ProjectQgateAssociationDto::getUuid).toList();
Collection<String> authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, projectUuids, userSession.getUuid(), UserRole.USER);
return projects.stream().filter(project -> authorizedProjectUuids.contains(project.getUuid())).toList();
}
}
| 6,908 | 43.863636 | 165 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SearchGroupsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.SearchGroupMembershipDto;
import org.sonar.db.user.SearchPermissionQuery;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Qualitygates;
import static java.util.Optional.ofNullable;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.api.server.ws.WebService.SelectionMode.ALL;
import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED;
import static org.sonar.api.server.ws.WebService.SelectionMode.fromParam;
import static org.sonar.db.Pagination.forPage;
import static org.sonar.db.qualitygate.SearchQualityGatePermissionQuery.builder;
import static org.sonar.db.user.SearchPermissionQuery.ANY;
import static org.sonar.db.user.SearchPermissionQuery.IN;
import static org.sonar.db.user.SearchPermissionQuery.OUT;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_SEARCH_GROUPS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchGroupsAction implements QualityGatesWsAction {
private static final Map<WebService.SelectionMode, String> MEMBERSHIP = Map.of(WebService.SelectionMode.SELECTED, IN, DESELECTED, OUT, ALL, ANY);
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
public SearchGroupsAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_SEARCH_GROUPS)
.setDescription("List the groups that are allowed to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.addSelectionModeParam()
.addSearchQuery("sonar", "group names")
.addPagingParams(25)
.setResponseExample(getClass().getResource("search_groups-example.json"))
.setSince("9.2");
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setExampleValue("SonarSource Way");
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchQualityGateUsersRequest wsRequest = buildRequest(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto gate = wsSupport.getByName(dbSession, wsRequest.getQualityGate());
wsSupport.checkCanLimitedEdit(dbSession, gate);
SearchPermissionQuery query = builder()
.setQualityGate(gate)
.setQuery(wsRequest.getQuery())
.setMembership(MEMBERSHIP.get(fromParam(wsRequest.getSelected())))
.build();
int total = dbClient.qualityGateGroupPermissionsDao().countByQuery(dbSession, query);
List<SearchGroupMembershipDto> groupMemberships = dbClient.qualityGateGroupPermissionsDao().selectByQuery(dbSession, query,
forPage(wsRequest.getPage()).andSize(wsRequest.getPageSize()));
Map<String, GroupDto> groupsByUuid = dbClient.groupDao().selectByUuids(dbSession,
groupMemberships.stream().map(SearchGroupMembershipDto::getGroupUuid).toList())
.stream()
.collect(Collectors.toMap(GroupDto::getUuid, Function.identity()));
writeProtobuf(
Qualitygates.SearchGroupsResponse.newBuilder()
.addAllGroups(groupMemberships.stream()
.map(groupsMembership -> toGroup(groupsByUuid.get(groupsMembership.getGroupUuid()), groupsMembership.isSelected()))
.toList())
.setPaging(buildPaging(wsRequest, total)).build(),
request, response);
}
}
private static SearchQualityGateUsersRequest buildRequest(Request request) {
return SearchQualityGateUsersRequest.builder()
.setQualityGate(request.mandatoryParam(PARAM_GATE_NAME))
.setQuery(request.param(TEXT_QUERY))
.setSelected(request.mandatoryParam(SELECTED))
.setPage(request.mandatoryParamAsInt(PAGE))
.setPageSize(request.mandatoryParamAsInt(PAGE_SIZE))
.build();
}
private static Qualitygates.SearchGroupsResponse.Group toGroup(GroupDto group, boolean isSelected) {
Qualitygates.SearchGroupsResponse.Group.Builder builder = Qualitygates.SearchGroupsResponse.Group.newBuilder()
.setName(group.getName())
.setSelected(isSelected);
ofNullable(group.getDescription()).ifPresent(builder::setDescription);
return builder.build();
}
private static Common.Paging buildPaging(SearchQualityGateUsersRequest wsRequest, int total) {
return Common.Paging.newBuilder()
.setPageIndex(wsRequest.getPage())
.setPageSize(wsRequest.getPageSize())
.setTotal(total)
.build();
}
}
| 6,375 | 42.671233 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SearchQualityGateUsersRequest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.server.user.ws.SearchUsersRequest;
class SearchQualityGateUsersRequest extends SearchUsersRequest {
private String qualityGate;
private SearchQualityGateUsersRequest(Builder builder) {
this.qualityGate = builder.qualityGate;
this.selected = builder.getSelected();
this.query = builder.getQuery();
this.page = builder.getPage();
this.pageSize = builder.getPageSize();
}
public String getQualityGate() {
return qualityGate;
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends SearchUsersRequest.Builder<Builder> {
private String qualityGate;
public Builder setQualityGate(String qualityGate) {
this.qualityGate = qualityGate;
return this;
}
public SearchQualityGateUsersRequest build() {
return new SearchQualityGateUsersRequest(this);
}
}
}
| 1,777 | 30.75 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SearchUsersAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
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.server.ws.WebService.SelectionMode;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.user.SearchPermissionQuery;
import org.sonar.db.user.SearchUserMembershipDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolver;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Qualitygates.SearchUsersResponse;
import static com.google.common.base.Strings.emptyToNull;
import static java.util.Optional.ofNullable;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.api.server.ws.WebService.SelectionMode.ALL;
import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED;
import static org.sonar.api.server.ws.WebService.SelectionMode.fromParam;
import static org.sonar.db.Pagination.forPage;
import static org.sonar.db.qualitygate.SearchQualityGatePermissionQuery.builder;
import static org.sonar.db.user.SearchPermissionQuery.ANY;
import static org.sonar.db.user.SearchPermissionQuery.IN;
import static org.sonar.db.user.SearchPermissionQuery.OUT;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_SEARCH_USERS;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchUsersAction implements QualityGatesWsAction {
private static final Map<SelectionMode, String> MEMBERSHIP = Map.of(SelectionMode.SELECTED, IN, DESELECTED, OUT, ALL, ANY);
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
private final AvatarResolver avatarResolver;
public SearchUsersAction(DbClient dbClient, QualityGatesWsSupport wsSupport, AvatarResolver avatarResolver) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.avatarResolver = avatarResolver;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_SEARCH_USERS)
.setDescription("List the users that are allowed to edit a Quality Gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>Edit right on the specified quality gate</li>" +
"</ul>")
.setHandler(this)
.addSearchQuery("freddy", "names", "logins")
.addSelectionModeParam()
.addPagingParams(25)
.setResponseExample(getClass().getResource("search_users-example.json"))
.setSince("9.2");
action.createParam(PARAM_GATE_NAME)
.setDescription("Quality Gate name")
.setRequired(true)
.setExampleValue("Recommended quality gate");
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchQualityGateUsersRequest wsRequest = buildRequest(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto gate = wsSupport.getByName(dbSession, wsRequest.getQualityGate());
wsSupport.checkCanLimitedEdit(dbSession, gate);
SearchPermissionQuery query = builder()
.setQualityGate(gate)
.setQuery(wsRequest.getQuery())
.setMembership(MEMBERSHIP.get(fromParam(wsRequest.getSelected())))
.build();
int total = dbClient.qualityGateUserPermissionDao().countByQuery(dbSession, query);
List<SearchUserMembershipDto> usersMembership = dbClient.qualityGateUserPermissionDao().selectByQuery(dbSession, query,
forPage(wsRequest.getPage()).andSize(wsRequest.getPageSize()));
Map<String, UserDto> usersById = dbClient.userDao().selectByUuids(dbSession, usersMembership.stream().map(SearchUserMembershipDto::getUserUuid).toList())
.stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity()));
writeProtobuf(
SearchUsersResponse.newBuilder()
.addAllUsers(usersMembership.stream()
.map(userMembershipDto -> toUser(usersById.get(userMembershipDto.getUserUuid()), userMembershipDto.isSelected()))
.toList())
.setPaging(buildPaging(wsRequest, total)).build(),
request, response);
}
}
private static SearchQualityGateUsersRequest buildRequest(Request request) {
return SearchQualityGateUsersRequest.builder()
.setQualityGate(request.mandatoryParam(PARAM_GATE_NAME))
.setQuery(request.param(TEXT_QUERY))
.setSelected(request.mandatoryParam(SELECTED))
.setPage(request.mandatoryParamAsInt(PAGE))
.setPageSize(request.mandatoryParamAsInt(PAGE_SIZE))
.build();
}
private SearchUsersResponse.User toUser(UserDto user, boolean isSelected) {
SearchUsersResponse.User.Builder builder = SearchUsersResponse.User.newBuilder()
.setLogin(user.getLogin())
.setSelected(isSelected);
ofNullable(user.getName()).ifPresent(builder::setName);
ofNullable(emptyToNull(user.getEmail())).ifPresent(e -> builder.setAvatar(avatarResolver.create(user)));
return builder
.build();
}
private static Common.Paging buildPaging(SearchQualityGateUsersRequest wsRequest, int total) {
return Common.Paging.newBuilder()
.setPageIndex(wsRequest.getPage())
.setPageSize(wsRequest.getPageSize())
.setTotal(total)
.build();
}
}
| 6,656 | 42.796053 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SelectAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualitygate.QualityGateDto;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_SELECT;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
public class SelectAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGatesWsSupport wsSupport;
public SelectAction(DbClient dbClient, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction(ACTION_SELECT)
.setDescription("Associate a project to a quality gate.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Gates'</li>" +
" <li>'Administer' right on the specified project</li>" +
"</ul>")
.setPost(true)
.setSince("4.3")
.setHandler(this)
.setChangelog(
new Change("10.0", "Parameter 'gateId' is removed. Use 'gateName' instead."),
new Change("8.4", "Parameter 'gateName' added"),
new Change("8.4", "Parameter 'gateId' is deprecated. Format changes from integer to string. Use 'gateName' instead."),
new Change("8.3", "The parameter 'projectId' was removed"));
action.createParam(PARAM_GATE_NAME)
.setRequired(true)
.setDescription("Name of the quality gate")
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setExampleValue("SonarSource way");
action.createParam(PARAM_PROJECT_KEY)
.setRequired(true)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setSince("6.1");
}
@Override
public void handle(Request request, Response response) {
String gateName = request.mandatoryParam(PARAM_GATE_NAME);
String projectKey = request.mandatoryParam(PARAM_PROJECT_KEY);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGate;
qualityGate = wsSupport.getByName(dbSession, gateName);
ProjectDto project = wsSupport.getProject(dbSession, projectKey);
wsSupport.checkCanAdminProject(project);
QualityGateDto currentQualityGate = dbClient.qualityGateDao().selectByProjectUuid(dbSession, project.getUuid());
if (currentQualityGate == null) {
// project uses the default profile
dbClient.projectQgateAssociationDao()
.insertProjectQGateAssociation(dbSession, project.getUuid(), qualityGate.getUuid());
dbSession.commit();
} else if (!qualityGate.getUuid().equals(currentQualityGate.getUuid())) {
dbClient.projectQgateAssociationDao()
.updateProjectQGateAssociation(dbSession, project.getUuid(), qualityGate.getUuid());
dbSession.commit();
}
}
response.noContent();
}
}
| 4,307 | 40.028571 | 126 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/SetAsDefaultAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.user.UserSession;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES;
import static org.sonar.server.qualitygate.ws.CreateAction.NAME_MAXIMUM_LENGTH;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME;
public class SetAsDefaultAction implements QualityGatesWsAction {
private static final String DEFAULT_QUALITY_GATE_PROPERTY_NAME = "qualitygate.default";
private final DbClient dbClient;
private final UserSession userSession;
private final QualityGatesWsSupport wsSupport;
public SetAsDefaultAction(DbClient dbClient, UserSession userSession, QualityGatesWsSupport qualityGatesWsSupport) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = qualityGatesWsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("set_as_default")
.setDescription("Set a quality gate as the default quality gate.<br>" +
"Parameter 'name' must be specified. Requires the 'Administer Quality Gates' permission.")
.setSince("4.3")
.setChangelog(
new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."),
new Change("8.4", "Parameter 'name' added"),
new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."))
.setPost(true)
.setHandler(this);
action.createParam(PARAM_NAME)
.setDescription("Name of the quality gate to set as default")
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setSince("8.4")
.setExampleValue("SonarSource Way");
}
@Override
public void handle(Request request, Response response) {
String name = request.mandatoryParam(PARAM_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(ADMINISTER_QUALITY_GATES);
QualityGateDto qualityGate;
qualityGate = wsSupport.getByName(dbSession, name);
dbClient.propertiesDao().saveProperty(new PropertyDto().setKey(DEFAULT_QUALITY_GATE_PROPERTY_NAME).setValue(qualityGate.getUuid()));
dbSession.commit();
}
response.noContent();
}
}
| 3,462 | 38.352273 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/ShowAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import com.google.common.io.Resources;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateCaycChecker;
import org.sonar.server.qualitygate.QualityGateCaycStatus;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonarqube.ws.Qualitygates.ShowWsResponse;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Optional.ofNullable;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ShowAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGateFinder qualityGateFinder;
private final QualityGatesWsSupport wsSupport;
private final QualityGateCaycChecker qualityGateCaycChecker;
public ShowAction(DbClient dbClient, QualityGateFinder qualityGateFinder, QualityGatesWsSupport wsSupport, QualityGateCaycChecker qualityGateCaycChecker) {
this.dbClient = dbClient;
this.qualityGateFinder = qualityGateFinder;
this.wsSupport = wsSupport;
this.qualityGateCaycChecker = qualityGateCaycChecker;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("show")
.setDescription("Display the details of a quality gate")
.setSince("4.3")
.setResponseExample(Resources.getResource(this.getClass(), "show-example.json"))
.setChangelog(
new Change("10.0", "Field 'id' in the response has been removed"),
new Change("10.0", "Parameter 'id' is removed. Use 'name' instead."),
new Change("9.9", "'caycStatus' field is added to the response"),
new Change("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."),
new Change("8.4", "Field 'id' in the response is deprecated."),
new Change("7.6", "'period' and 'warning' fields of conditions are removed from the response"),
new Change("7.0", "'isBuiltIn' field is added to the response"),
new Change("7.0", "'actions' field is added in the response"))
.setHandler(this);
action.createParam(PARAM_NAME)
.setRequired(true)
.setDescription("Name of the quality gate. Either id or name must be set")
.setExampleValue("My Quality Gate");
}
@Override
public void handle(Request request, Response response) {
String name = request.mandatoryParam(PARAM_NAME);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGate = wsSupport.getByName(dbSession, name);
Collection<QualityGateConditionDto> conditions = getConditions(dbSession, qualityGate);
Map<String, MetricDto> metricsByUuid = getMetricsByUuid(dbSession, conditions);
QualityGateDto defaultQualityGate = qualityGateFinder.getDefault(dbSession);
QualityGateCaycStatus caycStatus = qualityGateCaycChecker.checkCaycCompliant(dbSession, qualityGate.getUuid());
writeProtobuf(buildResponse(dbSession, qualityGate, defaultQualityGate, conditions, metricsByUuid, caycStatus), request, response);
}
}
public Collection<QualityGateConditionDto> getConditions(DbSession dbSession, QualityGateDto qualityGate) {
return dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid());
}
private Map<String, MetricDto> getMetricsByUuid(DbSession dbSession, Collection<QualityGateConditionDto> conditions) {
Set<String> metricUuids = conditions.stream().map(QualityGateConditionDto::getMetricUuid).collect(Collectors.toSet());
return dbClient.metricDao().selectByUuids(dbSession, metricUuids).stream().filter(MetricDto::isEnabled).collect(Collectors.toMap(MetricDto::getUuid, Function.identity()));
}
private ShowWsResponse buildResponse(DbSession dbSession, QualityGateDto qualityGate, QualityGateDto defaultQualityGate, Collection<QualityGateConditionDto> conditions,
Map<String, MetricDto> metricsByUuid, QualityGateCaycStatus caycStatus) {
return ShowWsResponse.newBuilder()
.setName(qualityGate.getName())
.setIsBuiltIn(qualityGate.isBuiltIn())
.setCaycStatus(caycStatus.toString())
.addAllConditions(conditions.stream()
.map(toWsCondition(metricsByUuid))
.toList())
.setActions(wsSupport.getActions(dbSession, qualityGate, defaultQualityGate))
.build();
}
private static Function<QualityGateConditionDto, ShowWsResponse.Condition> toWsCondition(Map<String, MetricDto> metricsByUuid) {
return condition -> {
String metricUuid = condition.getMetricUuid();
MetricDto metric = metricsByUuid.get(metricUuid);
checkState(metric != null, "Could not find metric with id %s", metricUuid);
ShowWsResponse.Condition.Builder builder = ShowWsResponse.Condition.newBuilder()
.setId(condition.getUuid())
.setMetric(metric.getKey())
.setOp(condition.getOperator());
ofNullable(condition.getErrorThreshold()).ifPresent(builder::setError);
return builder.build();
};
}
}
| 6,446 | 46.404412 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/UpdateConditionAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualitygate.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.qualitygate.QualityGateConditionsUpdater;
import org.sonarqube.ws.Qualitygates.UpdateConditionResponse;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.qualitygate.ws.QualityGatesWs.addConditionParams;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.ACTION_UPDATE_CONDITION;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ERROR;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ID;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_METRIC;
import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPERATOR;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class UpdateConditionAction implements QualityGatesWsAction {
private final DbClient dbClient;
private final QualityGateConditionsUpdater qualityGateConditionsUpdater;
private final QualityGatesWsSupport wsSupport;
public UpdateConditionAction(DbClient dbClient, QualityGateConditionsUpdater qualityGateConditionsUpdater, QualityGatesWsSupport wsSupport) {
this.dbClient = dbClient;
this.qualityGateConditionsUpdater = qualityGateConditionsUpdater;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction createCondition = controller.createAction(ACTION_UPDATE_CONDITION)
.setDescription("Update a condition attached to a quality gate.<br>" +
"Requires the 'Administer Quality Gates' permission.")
.setPost(true)
.setSince("4.3")
.setChangelog(
new Change("8.4", "Parameter 'id' format changes from integer to string. "),
new Change("7.6", "Removed optional 'warning' and 'period' parameters"),
new Change("7.6", "Made 'error' parameter mandatory"),
new Change("7.6", "Reduced the possible values of 'op' parameter to LT and GT"))
.setHandler(this);
createCondition
.createParam(PARAM_ID)
.setDescription("Condition ID")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
addConditionParams(createCondition);
}
@Override
public void handle(Request request, Response response) {
String id = request.mandatoryParam(PARAM_ID);
String metric = request.mandatoryParam(PARAM_METRIC);
String operator = request.mandatoryParam(PARAM_OPERATOR);
String error = request.mandatoryParam(PARAM_ERROR);
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateConditionDto condition = wsSupport.getCondition(dbSession, id);
QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByUuid(dbSession, condition.getQualityGateUuid());
checkState(qualityGateDto != null, "Condition '%s' is linked to an unknown quality gate '%s'", id, condition.getQualityGateUuid());
wsSupport.checkCanLimitedEdit(dbSession, qualityGateDto);
QualityGateConditionDto updatedCondition = qualityGateConditionsUpdater.updateCondition(dbSession, condition, metric, operator, error);
UpdateConditionResponse.Builder updateConditionResponse = UpdateConditionResponse.newBuilder()
.setId(updatedCondition.getUuid())
.setMetric(updatedCondition.getMetricKey())
.setError(updatedCondition.getErrorThreshold())
.setOp(updatedCondition.getOperator());
writeProtobuf(updateConditionResponse.build(), request, response);
dbSession.commit();
}
}
}
| 4,776 | 46.29703 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/ws/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.qualitygate.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ImportedQProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.List;
import static java.util.Objects.requireNonNull;
class ImportedQProfile {
private final String profileName;
private final String profileLang;
private final List<ImportedRule> rules;
public ImportedQProfile(String profileName, String profileLang, List<ImportedRule> rules) {
requireNonNull(profileName, "Profile name should not be empty!");
requireNonNull(profileLang, "Profile language should not be empty!");
this.profileName = profileName;
this.profileLang = profileLang;
this.rules = rules;
}
public String getProfileName() {
return profileName;
}
public String getProfileLang() {
return profileLang;
}
public List<ImportedRule> getRules() {
return rules;
}
}
| 1,631 | 30.384615 | 93 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ImportedRule.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.Map;
import org.sonar.api.rule.RuleKey;
class ImportedRule {
private String key = null;
private String repository = null;
private String template = null;
private String name = null;
private String type = null;
private String severity = null;
private String description = null;
private Map<String, String> parameters = null;
public Map<String, String> getParameters() {
return parameters;
}
public RuleKey getRuleKey() {
return RuleKey.of(repository, key);
}
public RuleKey getTemplateKey() {
return RuleKey.of(repository, template);
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getSeverity() {
return severity;
}
public String getDescription() {
return description;
}
ImportedRule setType(String type) {
this.type = type;
return this;
}
ImportedRule setSeverity(String severity) {
this.severity = severity;
return this;
}
ImportedRule setDescription(String description) {
this.description = description;
return this;
}
ImportedRule setParameters(Map<String, String> parameters) {
this.parameters = parameters;
return this;
}
ImportedRule setName(String name) {
this.name = name;
return this;
}
boolean isCustomRule() {
return template != null;
}
public void setRepository(String repository) {
this.repository = repository;
}
public void setTemplate(String template) {
this.template = template;
}
public void setKey(String key) {
this.key = key;
}
}
| 2,487 | 22.471698 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.io.Reader;
import java.io.Writer;
import javax.annotation.Nullable;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
/**
* Backup and restore a Quality profile.
*/
public interface QProfileBackuper {
void backup(DbSession dbSession, QProfileDto profile, Writer backupWriter);
/**
* Restore backup on a profile. The parameter {@code overriddenProfileName}
* is the name of the profile to be used. If the parameter is null, then the name is loaded from the backup.
* The profile is created if it does not exist.
*/
QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName);
/**
* Restore backup on an existing profile.
*/
QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile);
QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to);
}
| 1,808 | 35.918367 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileBackuperImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ExportRuleDto;
import org.sonar.db.qualityprofile.ExportRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import org.sonar.server.rule.NewCustomRule;
import org.sonar.server.rule.RuleCreator;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toSet;
@ServerSide
public class QProfileBackuperImpl implements QProfileBackuper {
private final DbClient db;
private final QProfileReset profileReset;
private final QProfileFactory profileFactory;
private final RuleCreator ruleCreator;
private final QProfileParser qProfileParser;
public QProfileBackuperImpl(DbClient db, QProfileReset profileReset, QProfileFactory profileFactory,
RuleCreator ruleCreator, QProfileParser qProfileParser) {
this.db = db;
this.profileReset = profileReset;
this.profileFactory = profileFactory;
this.ruleCreator = ruleCreator;
this.qProfileParser = qProfileParser;
}
@Override
public void backup(DbSession dbSession, QProfileDto profile, Writer writer) {
List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, profile);
rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
qProfileParser.writeXml(writer, profile, rulesToExport.iterator());
}
@Override
public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, from);
rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
ImportedQProfile qProfile = toImportedQProfile(rulesToExport, to.getName(), to.getLanguage());
return restore(dbSession, qProfile, name -> to);
}
private static ImportedQProfile toImportedQProfile(List<ExportRuleDto> exportRules, String profileName, String profileLang) {
List<ImportedRule> importedRules = new ArrayList<>(exportRules.size());
for (ExportRuleDto exportRuleDto : exportRules) {
var ruleKey = exportRuleDto.getRuleKey();
ImportedRule importedRule = new ImportedRule();
importedRule.setName(exportRuleDto.getName());
importedRule.setRepository(ruleKey.repository());
importedRule.setKey(ruleKey.rule());
importedRule.setSeverity(exportRuleDto.getSeverityString());
if (exportRuleDto.isCustomRule()) {
importedRule.setTemplate(exportRuleDto.getTemplateRuleKey().rule());
importedRule.setDescription(exportRuleDto.getDescriptionOrThrow());
}
importedRule.setType(exportRuleDto.getRuleType().name());
importedRule.setParameters(exportRuleDto.getParams().stream().collect(Collectors.toMap(ExportRuleParamDto::getKey, ExportRuleParamDto::getValue)));
importedRules.add(importedRule);
}
return new ImportedQProfile(profileName, profileLang, importedRules);
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
return restore(dbSession, backup, nameInBackup -> {
QProfileName targetName = nameInBackup;
if (overriddenProfileName != null) {
targetName = new QProfileName(nameInBackup.getLanguage(), overriddenProfileName);
}
return profileFactory.getOrCreateCustom(dbSession, targetName);
});
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
return restore(dbSession, backup, nameInBackup -> {
checkArgument(profile.getLanguage().equals(nameInBackup.getLanguage()),
"Can't restore %s backup on %s profile with key [%s]. Languages are different.", nameInBackup.getLanguage(), profile.getLanguage(), profile.getKee());
return profile;
});
}
private QProfileRestoreSummary restore(DbSession dbSession, Reader backup, Function<QProfileName, QProfileDto> profileLoader) {
ImportedQProfile qProfile = qProfileParser.readXml(backup);
return restore(dbSession, qProfile, profileLoader);
}
private QProfileRestoreSummary restore(DbSession dbSession, ImportedQProfile qProfile, Function<QProfileName, QProfileDto> profileLoader) {
QProfileName targetName = new QProfileName(qProfile.getProfileLang(), qProfile.getProfileName());
QProfileDto targetProfile = profileLoader.apply(targetName);
List<ImportedRule> importedRules = qProfile.getRules();
Map<RuleKey, RuleDto> ruleKeyToDto = getImportedRulesDtos(dbSession, importedRules);
checkIfRulesFromExternalEngines(ruleKeyToDto.values());
Map<RuleKey, RuleDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleKeyToDto);
ruleKeyToDto.putAll(customRulesDefinitions);
List<RuleActivation> ruleActivations = toRuleActivations(importedRules, ruleKeyToDto);
BulkChangeResult changes = profileReset.reset(dbSession, targetProfile, ruleActivations);
return new QProfileRestoreSummary(targetProfile, changes);
}
/**
* Returns map of rule definition for an imported rule key.
* The imported rule key may refer to a deprecated rule key, in which case the the RuleDto will correspond to a different key (the new key).
*/
private Map<RuleKey, RuleDto> getImportedRulesDtos(DbSession dbSession, List<ImportedRule> rules) {
Set<RuleKey> ruleKeys = rules.stream()
.map(ImportedRule::getRuleKey)
.collect(toSet());
Map<RuleKey, RuleDto> ruleDtos = db.ruleDao().selectByKeys(dbSession, ruleKeys).stream()
.collect(Collectors.toMap(RuleDto::getKey, identity()));
Set<RuleKey> unrecognizedRuleKeys = ruleKeys.stream()
.filter(r -> !ruleDtos.containsKey(r))
.collect(toSet());
if (!unrecognizedRuleKeys.isEmpty()) {
Map<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByUuid = db.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
.filter(r -> r.getNewRepositoryKey() != null && r.getNewRuleKey() != null)
.filter(r -> unrecognizedRuleKeys.contains(RuleKey.of(r.getOldRepositoryKey(), r.getOldRuleKey())))
// ignore deprecated rule if the new rule key was already found in the list of imported rules
.filter(r -> !ruleKeys.contains(RuleKey.of(r.getNewRepositoryKey(), r.getNewRuleKey())))
.collect(Collectors.toMap(DeprecatedRuleKeyDto::getRuleUuid, identity()));
List<RuleDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
for (RuleDto rule : rulesBasedOnDeprecatedKeys) {
DeprecatedRuleKeyDto deprecatedRuleKey = deprecatedRuleKeysByUuid.get(rule.getUuid());
RuleKey oldRuleKey = RuleKey.of(deprecatedRuleKey.getOldRepositoryKey(), deprecatedRuleKey.getOldRuleKey());
ruleDtos.put(oldRuleKey, rule);
}
}
return ruleDtos;
}
private static void checkIfRulesFromExternalEngines(Collection<RuleDto> ruleDefinitions) {
List<RuleDto> externalRules = ruleDefinitions.stream()
.filter(RuleDto::isExternal)
.toList();
if (!externalRules.isEmpty()) {
throw new IllegalArgumentException("The quality profile cannot be restored as it contains rules from external rule engines: "
+ externalRules.stream().map(r -> r.getKey().toString()).collect(Collectors.joining(", ")));
}
}
private Map<RuleKey, RuleDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
List<NewCustomRule> customRulesToCreate = rules.stream()
.filter(r -> ruleDefinitionsByKey.get(r.getRuleKey()) == null && r.isCustomRule())
.map(QProfileBackuperImpl::importedRuleToNewCustomRule)
.toList();
if (!customRulesToCreate.isEmpty()) {
return db.ruleDao().selectByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate))
.stream()
.collect(Collectors.toMap(RuleDto::getKey, identity()));
}
return Collections.emptyMap();
}
private static NewCustomRule importedRuleToNewCustomRule(ImportedRule r) {
return NewCustomRule.createForCustomRule(r.getRuleKey().rule(), r.getTemplateKey())
.setName(r.getName())
.setSeverity(r.getSeverity())
.setStatus(RuleStatus.READY)
.setPreventReactivation(true)
.setType(RuleType.valueOf(r.getType()))
.setMarkdownDescription(r.getDescription())
.setParameters(r.getParameters());
}
private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
List<RuleActivation> activatedRule = new ArrayList<>();
for (ImportedRule r : rules) {
RuleDto ruleDto = ruleDefinitionsByKey.get(r.getRuleKey());
if (ruleDto == null) {
continue;
}
activatedRule.add(RuleActivation.create(ruleDto.getUuid(), r.getSeverity(), r.getParameters()));
}
return activatedRule;
}
private enum BackupActiveRuleComparator implements Comparator<ExportRuleDto> {
INSTANCE;
@Override
public int compare(ExportRuleDto o1, ExportRuleDto o2) {
RuleKey rk1 = o1.getRuleKey();
RuleKey rk2 = o2.getRuleKey();
return new CompareToBuilder()
.append(rk1.repository(), rk2.repository())
.append(rk1.rule(), rk2.rule())
.toComparison();
}
}
}
| 10,971 | 42.888 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
@ServerSide
public class QProfileComparison {
private final DbClient dbClient;
public QProfileComparison(DbClient dbClient) {
this.dbClient = dbClient;
}
public QProfileComparisonResult compare(DbSession dbSession, QProfileDto left, QProfileDto right) {
Map<RuleKey, OrgActiveRuleDto> leftActiveRulesByRuleKey = loadActiveRules(dbSession, left);
Map<RuleKey, OrgActiveRuleDto> rightActiveRulesByRuleKey = loadActiveRules(dbSession, right);
Set<RuleKey> allRules = new HashSet<>();
allRules.addAll(leftActiveRulesByRuleKey.keySet());
allRules.addAll(rightActiveRulesByRuleKey.keySet());
QProfileComparisonResult result = new QProfileComparisonResult(left, right);
for (RuleKey ruleKey : allRules) {
if (!leftActiveRulesByRuleKey.containsKey(ruleKey)) {
result.inRight.put(ruleKey, rightActiveRulesByRuleKey.get(ruleKey));
} else if (!rightActiveRulesByRuleKey.containsKey(ruleKey)) {
result.inLeft.put(ruleKey, leftActiveRulesByRuleKey.get(ruleKey));
} else {
compareActivationParams(dbSession, leftActiveRulesByRuleKey.get(ruleKey), rightActiveRulesByRuleKey.get(ruleKey), result);
}
}
return result;
}
private void compareActivationParams(DbSession session, ActiveRuleDto leftRule, ActiveRuleDto rightRule, QProfileComparisonResult result) {
RuleKey key = leftRule.getRuleKey();
Map<String, String> leftParams = paramDtoToMap(dbClient.activeRuleDao().selectParamsByActiveRuleUuid(session, leftRule.getUuid()));
Map<String, String> rightParams = paramDtoToMap(dbClient.activeRuleDao().selectParamsByActiveRuleUuid(session, rightRule.getUuid()));
if (leftParams.equals(rightParams) && leftRule.getSeverityString().equals(rightRule.getSeverityString())) {
result.same.put(key, leftRule);
} else {
ActiveRuleDiff diff = new ActiveRuleDiff();
diff.leftSeverity = leftRule.getSeverityString();
diff.rightSeverity = rightRule.getSeverityString();
diff.paramDifference = Maps.difference(leftParams, rightParams);
result.modified.put(key, diff);
}
}
private Map<RuleKey, OrgActiveRuleDto> loadActiveRules(DbSession dbSession, QProfileDto profile) {
return Maps.uniqueIndex(dbClient.activeRuleDao().selectByProfile(dbSession, profile), ActiveRuleDto::getRuleKey);
}
public static class QProfileComparisonResult {
private final QProfileDto left;
private final QProfileDto right;
private final Map<RuleKey, ActiveRuleDto> inLeft = new HashMap<>();
private final Map<RuleKey, ActiveRuleDto> inRight = new HashMap<>();
private final Map<RuleKey, ActiveRuleDiff> modified = new HashMap<>();
private final Map<RuleKey, ActiveRuleDto> same = new HashMap<>();
public QProfileComparisonResult(QProfileDto left, QProfileDto right) {
this.left = left;
this.right = right;
}
public QProfileDto left() {
return left;
}
public QProfileDto right() {
return right;
}
public Map<RuleKey, ActiveRuleDto> inLeft() {
return inLeft;
}
public Map<RuleKey, ActiveRuleDto> inRight() {
return inRight;
}
public Map<RuleKey, ActiveRuleDiff> modified() {
return modified;
}
public Map<RuleKey, ActiveRuleDto> same() {
return same;
}
public Collection<RuleKey> collectRuleKeys() {
Set<RuleKey> keys = new HashSet<>();
keys.addAll(inLeft.keySet());
keys.addAll(inRight.keySet());
keys.addAll(modified.keySet());
keys.addAll(same.keySet());
return keys;
}
}
public static class ActiveRuleDiff {
private String leftSeverity;
private String rightSeverity;
private MapDifference<String, String> paramDifference;
public String leftSeverity() {
return leftSeverity;
}
public String rightSeverity() {
return rightSeverity;
}
public MapDifference<String, String> paramDifference() {
return paramDifference;
}
}
private static Map<String, String> paramDtoToMap(List<ActiveRuleParamDto> params) {
Map<String, String> map = new HashMap<>();
for (ActiveRuleParamDto dto : params) {
map.put(dto.getKey(), dto.getValue());
}
return map;
}
}
| 5,707 | 33.593939 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.builtin.QProfileName;
@ServerSide
public class QProfileCopier {
private final DbClient db;
private final QProfileFactory factory;
private final QProfileBackuper backuper;
public QProfileCopier(DbClient db, QProfileFactory factory, QProfileBackuper backuper) {
this.db = db;
this.factory = factory;
this.backuper = backuper;
}
public QProfileDto copyToName(DbSession dbSession, QProfileDto sourceProfile, String toName) {
QProfileDto to = prepareTarget(dbSession, sourceProfile, toName);
backuper.copy(dbSession, sourceProfile, to);
return to;
}
private QProfileDto prepareTarget(DbSession dbSession, QProfileDto sourceProfile, String toName) {
verify(sourceProfile.getName(), toName);
QProfileName toProfileName = new QProfileName(sourceProfile.getLanguage(), toName);
QProfileDto toProfile = db.qualityProfileDao().selectByNameAndLanguage(dbSession, toProfileName.getName(), toProfileName.getLanguage());
if (toProfile == null) {
toProfile = factory.createCustom(dbSession, toProfileName, sourceProfile.getParentKee());
dbSession.commit();
}
return toProfile;
}
private static void verify(String fromProfileName, String toProfileName) {
if (fromProfileName.equals(toProfileName)) {
throw new IllegalArgumentException(String.format("Source and target profiles are equal: %s", toProfileName));
}
}
}
| 2,473 | 38.269841 | 140 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileExporters.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.ActiveRule;
import org.sonar.api.rules.ActiveRuleParam;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
@ServerSide
public class QProfileExporters {
private final DbClient dbClient;
private final RuleFinder ruleFinder;
private final QProfileRules qProfileRules;
private final ProfileExporter[] exporters;
private final ProfileImporter[] importers;
@Autowired(required = false)
public QProfileExporters(DbClient dbClient, RuleFinder ruleFinder, QProfileRules qProfileRules, ProfileExporter[] exporters, ProfileImporter[] importers) {
this.dbClient = dbClient;
this.ruleFinder = ruleFinder;
this.qProfileRules = qProfileRules;
this.exporters = exporters;
this.importers = importers;
}
/**
* Used by the ioc container if no {@link ProfileImporter} is found
*/
@Autowired(required = false)
public QProfileExporters(DbClient dbClient, RuleFinder ruleFinder, QProfileRules qProfileRules, ProfileExporter[] exporters) {
this(dbClient, ruleFinder, qProfileRules, exporters, new ProfileImporter[0]);
}
/**
* Used by the ioc container if no {@link ProfileExporter} is found
*/
@Autowired(required = false)
public QProfileExporters(DbClient dbClient, RuleFinder ruleFinder, QProfileRules qProfileRules, ProfileImporter[] importers) {
this(dbClient, ruleFinder, qProfileRules, new ProfileExporter[0], importers);
}
/**
* Used by the ioc container if no {@link ProfileImporter} nor {@link ProfileExporter} is found
*/
@Autowired(required = false)
public QProfileExporters(DbClient dbClient, RuleFinder ruleFinder, QProfileRules qProfileRules) {
this(dbClient, ruleFinder, qProfileRules, new ProfileExporter[0], new ProfileImporter[0]);
}
public List<ProfileExporter> exportersForLanguage(String language) {
List<ProfileExporter> result = new ArrayList<>();
for (ProfileExporter exporter : exporters) {
if (exporter.getSupportedLanguages() == null || exporter.getSupportedLanguages().length == 0 || ArrayUtils.contains(exporter.getSupportedLanguages(), language)) {
result.add(exporter);
}
}
return result;
}
public String mimeType(String exporterKey) {
ProfileExporter exporter = findExporter(exporterKey);
return exporter.getMimeType();
}
public void export(DbSession dbSession, QProfileDto profile, String exporterKey, Writer writer) {
ProfileExporter exporter = findExporter(exporterKey);
exporter.exportProfile(wrap(dbSession, profile), writer);
}
private RulesProfile wrap(DbSession dbSession, QProfileDto profile) {
RulesProfile target = new RulesProfile(profile.getName(), profile.getLanguage());
List<OrgActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfile(dbSession, profile);
List<ActiveRuleParamDto> activeRuleParamDtos = dbClient.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, Lists.transform(activeRuleDtos, ActiveRuleDto::getUuid));
ListMultimap<String, ActiveRuleParamDto> activeRuleParamsByActiveRuleUuid = FluentIterable.from(activeRuleParamDtos).index(ActiveRuleParamDto::getActiveRuleUuid);
for (ActiveRuleDto activeRule : activeRuleDtos) {
// TODO all rules should be loaded by using one query with all active rule keys as parameter
Rule rule = ruleFinder.findByKey(activeRule.getRuleKey());
org.sonar.api.rules.ActiveRule wrappedActiveRule = target.activateRule(rule, RulePriority.valueOf(activeRule.getSeverityString()));
List<ActiveRuleParamDto> paramDtos = activeRuleParamsByActiveRuleUuid.get(activeRule.getUuid());
for (ActiveRuleParamDto activeRuleParamDto : paramDtos) {
wrappedActiveRule.setParameter(activeRuleParamDto.getKey(), activeRuleParamDto.getValue());
}
}
return target;
}
private ProfileExporter findExporter(String exporterKey) {
for (ProfileExporter e : exporters) {
if (exporterKey.equals(e.getKey())) {
return e;
}
}
throw new NotFoundException("Unknown quality profile exporter: " + exporterKey);
}
public QProfileResult importXml(QProfileDto profile, String importerKey, InputStream xml, DbSession dbSession) {
return importXml(profile, importerKey, new InputStreamReader(xml, StandardCharsets.UTF_8), dbSession);
}
private QProfileResult importXml(QProfileDto profile, String importerKey, Reader xml, DbSession dbSession) {
QProfileResult result = new QProfileResult();
ValidationMessages messages = ValidationMessages.create();
ProfileImporter importer = getProfileImporter(importerKey);
RulesProfile definition = importer.importProfile(xml, messages);
List<ActiveRuleChange> changes = importProfile(profile, definition, dbSession);
result.addChanges(changes);
processValidationMessages(messages, result);
return result;
}
private List<ActiveRuleChange> importProfile(QProfileDto profile, RulesProfile definition, DbSession dbSession) {
Map<RuleKey, RuleDto> rulesByRuleKey = dbClient.ruleDao().selectAll(dbSession)
.stream()
.collect(Collectors.toMap(RuleDto::getKey, Function.identity()));
List<ActiveRule> activeRules = definition.getActiveRules();
List<RuleActivation> activations = activeRules.stream()
.map(activeRule -> toRuleActivation(activeRule, rulesByRuleKey))
.filter(Objects::nonNull)
.toList();
return qProfileRules.activateAndCommit(dbSession, profile, activations);
}
private ProfileImporter getProfileImporter(String importerKey) {
for (ProfileImporter importer : importers) {
if (StringUtils.equals(importerKey, importer.getKey())) {
return importer;
}
}
throw BadRequestException.create("No such importer : " + importerKey);
}
private static void processValidationMessages(ValidationMessages messages, QProfileResult result) {
checkRequest(messages.getErrors().isEmpty(), messages.getErrors());
result.addWarnings(messages.getWarnings());
result.addInfos(messages.getInfos());
}
@CheckForNull
private static RuleActivation toRuleActivation(ActiveRule activeRule, Map<RuleKey, RuleDto> rulesByRuleKey) {
RuleKey ruleKey = activeRule.getRule().ruleKey();
RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
if (ruleDto == null) {
return null;
}
String severity = activeRule.getSeverity().name();
Map<String, String> params = activeRule.getActiveRuleParams().stream()
.collect(Collectors.toMap(ActiveRuleParam::getKey, ActiveRuleParam::getValue));
return RuleActivation.create(ruleDto.getUuid(), severity, params);
}
}
| 8,943 | 42 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.Collection;
import javax.annotation.Nullable;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.qualityprofile.builtin.QProfileName;
/**
* Create, delete and set as default profile.
*/
public interface QProfileFactory {
QProfileDto getOrCreateCustom(DbSession dbSession, QProfileName name);
/**
* Create the quality profile in DB with the specified name.
*
* @throws BadRequestException if a quality profile with the specified name already exists
*/
QProfileDto checkAndCreateCustom(DbSession dbSession, QProfileName name);
QProfileDto createCustom(DbSession dbSession, QProfileName name, @Nullable String parentKey);
/**
* Deletes the specified profiles from database and Elasticsearch.
* All information related to custom profiles are deleted. Only association
* with built-in profiles are deleted.
* The profiles marked as "default" are deleted too. Deleting a parent profile
* does not delete descendants if the latter are not listed.
*/
void delete(DbSession dbSession, Collection<QProfileDto> profiles);
}
| 2,072 | 37.388889 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.DefaultQProfileDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public class QProfileFactoryImpl implements QProfileFactory {
private final DbClient db;
private final UuidFactory uuidFactory;
private final System2 system2;
private final ActiveRuleIndexer activeRuleIndexer;
public QProfileFactoryImpl(DbClient db, UuidFactory uuidFactory, System2 system2, ActiveRuleIndexer activeRuleIndexer) {
this.db = db;
this.uuidFactory = uuidFactory;
this.system2 = system2;
this.activeRuleIndexer = activeRuleIndexer;
}
@Override
public QProfileDto getOrCreateCustom(DbSession dbSession, QProfileName name) {
QProfileDto profile = db.qualityProfileDao().selectByNameAndLanguage(dbSession, name.getName(), name.getLanguage());
if (profile == null) {
profile = doCreate(dbSession, name, null, false, false);
} else {
checkArgument(!profile.isBuiltIn(), "Operation forbidden for built-in Quality Profile '%s' with language '%s'", profile.getName(), profile.getLanguage());
}
return profile;
}
@Override
public QProfileDto checkAndCreateCustom(DbSession dbSession, QProfileName name) {
QProfileDto dto = db.qualityProfileDao().selectByNameAndLanguage(dbSession, name.getName(), name.getLanguage());
checkRequest(dto == null, "Quality profile already exists: %s", name);
return doCreate(dbSession, name, null, false, false);
}
@Override
public QProfileDto createCustom(DbSession dbSession, QProfileName name, @Nullable String parentKey) {
return doCreate(dbSession, name, parentKey, false, false);
}
private QProfileDto doCreate(DbSession dbSession, QProfileName name, @Nullable String parentKey, boolean isDefault, boolean isBuiltIn) {
if (StringUtils.isEmpty(name.getName())) {
throw BadRequestException.create("quality_profiles.profile_name_cant_be_blank");
}
Date now = new Date(system2.now());
QProfileDto dto = new QProfileDto()
.setKee(uuidFactory.create())
.setRulesProfileUuid(uuidFactory.create())
.setName(name.getName())
.setLanguage(name.getLanguage())
.setIsBuiltIn(isBuiltIn)
.setParentKee(parentKey)
.setRulesUpdatedAtAsDate(now);
db.qualityProfileDao().insert(dbSession, dto);
if (isDefault) {
db.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(dto));
}
return dto;
}
// ------------- DELETION
@Override
public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
if (profiles.isEmpty()) {
return;
}
Set<String> uuids = new HashSet<>();
List<QProfileDto> customProfiles = new ArrayList<>();
Set<String> rulesProfileUuidsOfCustomProfiles = new HashSet<>();
profiles.forEach(p -> {
uuids.add(p.getKee());
if (!p.isBuiltIn()) {
customProfiles.add(p);
rulesProfileUuidsOfCustomProfiles.add(p.getRulesProfileUuid());
}
});
// tables org_qprofiles, default_qprofiles and project_qprofiles
// are deleted whatever custom or built-in
db.qualityProfileDao().deleteProjectAssociationsByProfileUuids(dbSession, uuids);
db.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
db.qualityProfileDao().deleteOrgQProfilesByUuids(dbSession, uuids);
// Permissions are only available on custom profiles
db.qProfileEditUsersDao().deleteByQProfiles(dbSession, customProfiles);
db.qProfileEditGroupsDao().deleteByQProfiles(dbSession, customProfiles);
// tables related to rules_profiles and active_rules are deleted
// only for custom profiles. Built-in profiles are never
// deleted from table rules_profiles.
if (!rulesProfileUuidsOfCustomProfiles.isEmpty()) {
db.activeRuleDao().deleteParametersByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.activeRuleDao().deleteByRuleProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qProfileChangeDao().deleteByRulesProfileUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
db.qualityProfileDao().deleteRulesProfilesByUuids(dbSession, rulesProfileUuidsOfCustomProfiles);
activeRuleIndexer.commitDeletionOfProfiles(dbSession, customProfiles);
} else {
dbSession.commit();
}
}
}
| 5,863 | 40.006993 | 160 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileParser.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.StringUtils;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.text.XmlWriter;
import org.sonar.db.qualityprofile.ExportRuleDto;
import org.sonar.db.qualityprofile.ExportRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
@ServerSide
public class QProfileParser {
private static final String ATTRIBUTE_PROFILE = "profile";
private static final String ATTRIBUTE_NAME = "name";
private static final String ATTRIBUTE_LANGUAGE = "language";
private static final String ATTRIBUTE_RULES = "rules";
private static final String ATTRIBUTE_RULE = "rule";
private static final String ATTRIBUTE_REPOSITORY_KEY = "repositoryKey";
private static final String ATTRIBUTE_KEY = "key";
private static final String ATTRIBUTE_PRIORITY = "priority";
private static final String ATTRIBUTE_TEMPLATE_KEY = "templateKey";
private static final String ATTRIBUTE_TYPE = "type";
private static final String ATTRIBUTE_DESCRIPTION = "description";
private static final String ATTRIBUTE_PARAMETERS = "parameters";
private static final String ATTRIBUTE_PARAMETER = "parameter";
private static final String ATTRIBUTE_PARAMETER_KEY = "key";
private static final String ATTRIBUTE_PARAMETER_VALUE = "value";
public void writeXml(Writer writer, QProfileDto profile, Iterator<ExportRuleDto> rulesToExport) {
XmlWriter xml = XmlWriter.of(writer).declaration();
xml.begin(ATTRIBUTE_PROFILE);
xml.prop(ATTRIBUTE_NAME, profile.getName());
xml.prop(ATTRIBUTE_LANGUAGE, profile.getLanguage());
xml.begin(ATTRIBUTE_RULES);
while (rulesToExport.hasNext()) {
ExportRuleDto ruleToExport = rulesToExport.next();
xml.begin(ATTRIBUTE_RULE);
xml.prop(ATTRIBUTE_REPOSITORY_KEY, ruleToExport.getRuleKey().repository());
xml.prop(ATTRIBUTE_KEY, ruleToExport.getRuleKey().rule());
xml.prop(ATTRIBUTE_TYPE, ruleToExport.getRuleType().name());
xml.prop(ATTRIBUTE_PRIORITY, ruleToExport.getSeverityString());
if (ruleToExport.isCustomRule()) {
xml.prop(ATTRIBUTE_NAME, ruleToExport.getName());
xml.prop(ATTRIBUTE_TEMPLATE_KEY, ruleToExport.getTemplateRuleKey().rule());
xml.prop(ATTRIBUTE_DESCRIPTION, ruleToExport.getDescriptionOrThrow());
}
xml.begin(ATTRIBUTE_PARAMETERS);
for (ExportRuleParamDto param : ruleToExport.getParams()) {
xml
.begin(ATTRIBUTE_PARAMETER)
.prop(ATTRIBUTE_PARAMETER_KEY, param.getKey())
.prop(ATTRIBUTE_PARAMETER_VALUE, param.getValue())
.end();
}
xml.end(ATTRIBUTE_PARAMETERS);
xml.end(ATTRIBUTE_RULE);
}
xml.end(ATTRIBUTE_RULES).end(ATTRIBUTE_PROFILE).close();
}
public ImportedQProfile readXml(Reader reader) {
List<ImportedRule> rules = new ArrayList<>();
String profileName = null;
String profileLang = null;
try {
SMInputFactory inputFactory = initStax();
SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
rootC.advance(); // <profile>
if (!ATTRIBUTE_PROFILE.equals(rootC.getLocalName())) {
throw new IllegalArgumentException("Backup XML is not valid. Root element must be <profile>.");
}
SMInputCursor cursor = rootC.childElementCursor();
while (cursor.getNext() != null) {
String nodeName = cursor.getLocalName();
if (StringUtils.equals(ATTRIBUTE_NAME, nodeName)) {
profileName = StringUtils.trim(cursor.collectDescendantText(false));
} else if (StringUtils.equals(ATTRIBUTE_LANGUAGE, nodeName)) {
profileLang = StringUtils.trim(cursor.collectDescendantText(false));
} else if (StringUtils.equals(ATTRIBUTE_RULES, nodeName)) {
SMInputCursor rulesCursor = cursor.childElementCursor("rule");
rules = parseRuleActivations(rulesCursor);
}
}
} catch (XMLStreamException e) {
throw new IllegalArgumentException("Fail to restore Quality profile backup, XML document is not well formed", e);
}
return new ImportedQProfile(profileName, profileLang, rules);
}
private static SMInputFactory initStax() {
XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
// just so it won't try to load DTD in if there's DOCTYPE
xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
return new SMInputFactory(xmlFactory);
}
private static List<ImportedRule> parseRuleActivations(SMInputCursor rulesCursor) throws XMLStreamException {
List<ImportedRule> activations = new ArrayList<>();
Set<RuleKey> activatedKeys = new HashSet<>();
List<RuleKey> duplicatedKeys = new ArrayList<>();
while (rulesCursor.getNext() != null) {
SMInputCursor ruleCursor = rulesCursor.childElementCursor();
Map<String, String> parameters = new HashMap<>();
ImportedRule rule = new ImportedRule();
readRule(ruleCursor, parameters, rule);
var ruleKey = rule.getRuleKey();
if (activatedKeys.contains(ruleKey)) {
duplicatedKeys.add(ruleKey);
}
activatedKeys.add(ruleKey);
activations.add(rule);
}
if (!duplicatedKeys.isEmpty()) {
throw new IllegalArgumentException("The quality profile cannot be restored as it contains duplicates for the following rules: " +
duplicatedKeys.stream().map(RuleKey::toString).filter(Objects::nonNull).collect(Collectors.joining(", ")));
}
return activations;
}
private static void readRule(SMInputCursor ruleCursor, Map<String, String> parameters, ImportedRule rule) throws XMLStreamException {
while (ruleCursor.getNext() != null) {
String nodeName = ruleCursor.getLocalName();
if (StringUtils.equals(ATTRIBUTE_REPOSITORY_KEY, nodeName)) {
rule.setRepository(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_KEY, nodeName)) {
rule.setKey(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_TEMPLATE_KEY, nodeName)) {
rule.setTemplate(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_NAME, nodeName)) {
rule.setName(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_TYPE, nodeName)) {
rule.setType(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_DESCRIPTION, nodeName)) {
rule.setDescription(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_PRIORITY, nodeName)) {
rule.setSeverity(StringUtils.trim(ruleCursor.collectDescendantText(false)));
} else if (StringUtils.equals(ATTRIBUTE_PARAMETERS, nodeName)) {
SMInputCursor propsCursor = ruleCursor.childElementCursor(ATTRIBUTE_PARAMETER);
readParameters(propsCursor, parameters);
rule.setParameters(parameters);
}
}
}
private static void readParameters(SMInputCursor propsCursor, Map<String, String> parameters) throws XMLStreamException {
while (propsCursor.getNext() != null) {
SMInputCursor propCursor = propsCursor.childElementCursor();
String key = null;
String value = null;
while (propCursor.getNext() != null) {
String nodeName = propCursor.getLocalName();
if (StringUtils.equals(ATTRIBUTE_PARAMETER_KEY, nodeName)) {
key = StringUtils.trim(propCursor.collectDescendantText(false));
} else if (StringUtils.equals(ATTRIBUTE_PARAMETER_VALUE, nodeName)) {
value = StringUtils.trim(propCursor.collectDescendantText(false));
}
}
if (key != null) {
parameters.put(key, value);
}
}
}
}
| 9,444 | 44.628019 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileReset.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.Collection;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
public interface QProfileReset {
/**
* Reset the rules of the specified profile.
*/
BulkChangeResult reset(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations);
}
| 1,197 | 35.30303 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileResetImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
@ServerSide
public class QProfileResetImpl implements QProfileReset {
private final DbClient db;
private final RuleActivator activator;
private final ActiveRuleIndexer activeRuleIndexer;
private final QualityProfileChangeEventService qualityProfileChangeEventService;
public QProfileResetImpl(DbClient db, RuleActivator activator, ActiveRuleIndexer activeRuleIndexer, QualityProfileChangeEventService qualityProfileChangeEventService) {
this.db = db;
this.activator = activator;
this.activeRuleIndexer = activeRuleIndexer;
this.qualityProfileChangeEventService = qualityProfileChangeEventService;
}
@Override
public BulkChangeResult reset(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations) {
requireNonNull(profile.getRulesProfileUuid(), "Quality profile must be persisted");
checkArgument(!profile.isBuiltIn(), "Operation forbidden for built-in Quality Profile '%s'", profile.getKee());
BulkChangeResult result = new BulkChangeResult();
Set<String> rulesToBeDeactivated = new HashSet<>();
// Keep reference to all the activated rules before backup restore
for (ActiveRuleDto activeRuleDto : db.activeRuleDao().selectByProfile(dbSession, profile)) {
if (activeRuleDto.getInheritance() == null) {
// inherited rules can't be deactivated
rulesToBeDeactivated.add(activeRuleDto.getRuleUuid());
}
}
Set<String> ruleUuids = new HashSet<>(rulesToBeDeactivated.size() + activations.size());
ruleUuids.addAll(rulesToBeDeactivated);
activations.forEach(a -> ruleUuids.add(a.getRuleUuid()));
RuleActivationContext context = activator.createContextForUserProfile(dbSession, profile, ruleUuids);
for (RuleActivation activation : activations) {
try {
List<ActiveRuleChange> changes = activator.activate(dbSession, activation, context);
rulesToBeDeactivated.remove(activation.getRuleUuid());
result.incrementSucceeded();
result.addChanges(changes);
} catch (BadRequestException e) {
result.incrementFailed();
result.getErrors().addAll(e.errors());
}
}
List<ActiveRuleChange> changes = new ArrayList<>(result.getChanges());
for (String ruleUuid : rulesToBeDeactivated) {
try {
changes.addAll(activator.deactivate(dbSession, context, ruleUuid, false));
} catch (BadRequestException e) {
// ignore, probably a rule inherited from parent that can't be deactivated
}
}
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), changes, profile.getLanguage());
activeRuleIndexer.commitAndIndex(dbSession, changes);
return result;
}
}
| 4,370 | 42.277228 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileRestoreSummary.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import org.sonar.db.qualityprofile.QProfileDto;
import static java.util.Objects.requireNonNull;
public record QProfileRestoreSummary(QProfileDto profile, BulkChangeResult ruleChanges) {
public QProfileRestoreSummary(QProfileDto profile, BulkChangeResult ruleChanges) {
this.profile = requireNonNull(profile);
this.ruleChanges = requireNonNull(ruleChanges);
}
}
| 1,260 | 38.40625 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileResult.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.ArrayList;
import java.util.List;
import org.sonar.db.qualityprofile.QProfileDto;
public class QProfileResult {
private List<String> warnings;
private List<String> infos;
private QProfileDto profile;
private List<ActiveRuleChange> changes;
public QProfileResult() {
warnings = new ArrayList<>();
infos = new ArrayList<>();
changes = new ArrayList<>();
}
public List<String> warnings() {
return warnings;
}
public QProfileResult addWarnings(List<String> warnings) {
this.warnings.addAll(warnings);
return this;
}
public List<String> infos() {
return infos;
}
public QProfileResult addInfos(List<String> infos) {
this.infos.addAll(infos);
return this;
}
public QProfileDto profile() {
return profile;
}
public QProfileResult setProfile(QProfileDto profile) {
this.profile = profile;
return this;
}
public List<ActiveRuleChange> getChanges() {
return changes;
}
public QProfileResult addChanges(List<ActiveRuleChange> changes) {
this.changes.addAll(changes);
return this;
}
public QProfileResult add(QProfileResult result) {
warnings.addAll(result.warnings());
infos.addAll(result.infos());
changes.addAll(result.getChanges());
return this;
}
}
| 2,183 | 24.694118 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileRulesImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleQuery;
import static com.google.common.base.Preconditions.checkArgument;
public class QProfileRulesImpl implements QProfileRules {
private final DbClient db;
private final RuleActivator ruleActivator;
private final RuleIndex ruleIndex;
private final ActiveRuleIndexer activeRuleIndexer;
private final QualityProfileChangeEventService qualityProfileChangeEventService;
public QProfileRulesImpl(DbClient db, RuleActivator ruleActivator, RuleIndex ruleIndex, ActiveRuleIndexer activeRuleIndexer,
QualityProfileChangeEventService qualityProfileChangeEventService) {
this.db = db;
this.ruleActivator = ruleActivator;
this.ruleIndex = ruleIndex;
this.activeRuleIndexer = activeRuleIndexer;
this.qualityProfileChangeEventService = qualityProfileChangeEventService;
}
@Override
public List<ActiveRuleChange> activateAndCommit(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations) {
verifyNotBuiltIn(profile);
Set<String> ruleUuids = activations.stream().map(RuleActivation::getRuleUuid).collect(Collectors.toSet());
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, ruleUuids);
List<ActiveRuleChange> changes = new ArrayList<>();
for (RuleActivation activation : activations) {
changes.addAll(ruleActivator.activate(dbSession, activation, context));
}
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), changes, profile.getLanguage());
activeRuleIndexer.commitAndIndex(dbSession, changes);
return changes;
}
@Override
public BulkChangeResult bulkActivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, @Nullable String severity) {
verifyNotBuiltIn(profile);
BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDto) -> {
RuleActivation activation = RuleActivation.create(ruleDto.getUuid(), severity, null);
return ruleActivator.activate(dbSession, activation, context);
});
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), bulkChangeResult.getChanges(), profile.getLanguage());
return bulkChangeResult;
}
@Override
public List<ActiveRuleChange> deactivateAndCommit(DbSession dbSession, QProfileDto profile, Collection<String> ruleUuids) {
verifyNotBuiltIn(profile);
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, ruleUuids);
List<ActiveRuleChange> changes = new ArrayList<>();
for (String ruleUuid : ruleUuids) {
changes.addAll(ruleActivator.deactivate(dbSession, context, ruleUuid, false));
}
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), changes, profile.getLanguage());
activeRuleIndexer.commitAndIndex(dbSession, changes);
return changes;
}
@Override
public BulkChangeResult bulkDeactivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery) {
verifyNotBuiltIn(profile);
BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDto) ->
ruleActivator.deactivate(dbSession, context, ruleDto.getUuid(), false));
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), bulkChangeResult.getChanges(), profile.getLanguage());
return bulkChangeResult;
}
@Override
public List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDto rule) {
List<ActiveRuleChange> changes = new ArrayList<>();
List<String> activeRuleUuids = new ArrayList<>();
db.activeRuleDao().selectByRuleUuid(dbSession, rule.getUuid()).forEach(ar -> {
activeRuleUuids.add(ar.getUuid());
changes.add(new ActiveRuleChange(ActiveRuleChange.Type.DEACTIVATED, ar, rule));
});
db.activeRuleDao().deleteByUuids(dbSession, activeRuleUuids);
db.activeRuleDao().deleteParamsByActiveRuleUuids(dbSession, activeRuleUuids);
return changes;
}
private static void verifyNotBuiltIn(QProfileDto profile) {
checkArgument(!profile.isBuiltIn(), "The built-in profile %s is read-only and can't be updated", profile.getName());
}
private BulkChangeResult doBulk(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, BiFunction<RuleActivationContext, RuleDto, List<ActiveRuleChange>> fn) {
BulkChangeResult result = new BulkChangeResult();
Collection<String> ruleUuids = Sets.newHashSet(ruleIndex.searchAll(ruleQuery));
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, ruleUuids);
for (String ruleUuid : ruleUuids) {
try {
context.reset(ruleUuid);
RuleDto ruleDto = context.getRule().get();
List<ActiveRuleChange> changes = fn.apply(context, ruleDto);
result.addChanges(changes);
if (!changes.isEmpty()) {
result.incrementSucceeded();
}
} catch (BadRequestException e) {
// other exceptions stop the bulk activation
result.incrementFailed();
result.getErrors().addAll(e.errors());
}
}
activeRuleIndexer.commitAndIndex(dbSession, result.getChanges());
return result;
}
}
| 6,895 | 42.64557 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileTree.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.List;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
/**
* Operations related to hierarchy of profiles
*/
@ServerSide
public interface QProfileTree {
List<ActiveRuleChange> removeParentAndCommit(DbSession dbSession, QProfileDto profile);
List<ActiveRuleChange> setParentAndCommit(DbSession dbSession, QProfileDto profile, QProfileDto parentProfile);
}
| 1,338 | 34.236842 | 113 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/QProfileTreeImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public class QProfileTreeImpl implements QProfileTree {
private final DbClient db;
private final RuleActivator ruleActivator;
private final System2 system2;
private final ActiveRuleIndexer activeRuleIndexer;
private final QualityProfileChangeEventService qualityProfileChangeEventService;
public QProfileTreeImpl(DbClient db, RuleActivator ruleActivator, System2 system2, ActiveRuleIndexer activeRuleIndexer,
QualityProfileChangeEventService qualityProfileChangeEventService) {
this.db = db;
this.ruleActivator = ruleActivator;
this.system2 = system2;
this.activeRuleIndexer = activeRuleIndexer;
this.qualityProfileChangeEventService = qualityProfileChangeEventService;
}
@Override
public List<ActiveRuleChange> removeParentAndCommit(DbSession dbSession, QProfileDto profile) {
List<ActiveRuleChange> changes = removeParent(dbSession, profile);
activeRuleIndexer.commitAndIndex(dbSession, changes);
return changes;
}
@Override
public List<ActiveRuleChange> setParentAndCommit(DbSession dbSession, QProfileDto profile, QProfileDto parentProfile) {
List<ActiveRuleChange> changes = setParent(dbSession, profile, parentProfile);
activeRuleIndexer.commitAndIndex(dbSession, changes);
return changes;
}
private List<ActiveRuleChange> setParent(DbSession dbSession, QProfileDto profile, QProfileDto parent) {
checkRequest(parent.getLanguage().equals(profile.getLanguage()), "Cannot set the profile '%s' as the parent of profile '%s' since their languages differ ('%s' != '%s')",
parent.getKee(), profile.getKee(), parent.getLanguage(), profile.getLanguage());
List<ActiveRuleChange> changes = new ArrayList<>();
if (parent.getKee().equals(profile.getParentKee())) {
return changes;
}
checkRequest(!isDescendant(dbSession, profile, parent), "Descendant profile '%s' can not be selected as parent of '%s'", parent.getKee(), profile.getKee());
// set new parent
profile.setParentKee(parent.getKee());
db.qualityProfileDao().update(dbSession, profile);
List<OrgActiveRuleDto> activeRules = db.activeRuleDao().selectByProfile(dbSession, profile);
List<OrgActiveRuleDto> parentActiveRules = db.activeRuleDao().selectByProfile(dbSession, parent);
changes = getChangesFromRulesToBeRemoved(dbSession, profile, getRulesDifference(activeRules, parentActiveRules));
Collection<String> parentRuleUuids = parentActiveRules.stream().map(ActiveRuleDto::getRuleUuid).toList();
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, parentRuleUuids);
for (ActiveRuleDto parentActiveRule : parentActiveRules) {
try {
RuleActivation activation = RuleActivation.create(parentActiveRule.getRuleUuid(), null, null);
changes.addAll(ruleActivator.activate(dbSession, activation, context));
} catch (BadRequestException e) {
// for example because rule status is REMOVED
// TODO return errors
}
}
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), changes, profile.getLanguage());
return changes;
}
private static List<OrgActiveRuleDto> getRulesDifference(Collection<OrgActiveRuleDto> rulesCollection1, Collection<OrgActiveRuleDto> rulesCollection2) {
Collection<String> rulesCollection2Uuids = rulesCollection2.stream()
.map(ActiveRuleDto::getRuleUuid)
.toList();
return rulesCollection1.stream()
.filter(rule -> !rulesCollection2Uuids.contains(rule.getRuleUuid()))
.toList();
}
private List<ActiveRuleChange> removeParent(DbSession dbSession, QProfileDto profile) {
List<ActiveRuleChange> changes = new ArrayList<>();
if (profile.getParentKee() == null) {
return changes;
}
profile.setParentKee(null);
db.qualityProfileDao().update(dbSession, profile);
List<OrgActiveRuleDto> activeRules = db.activeRuleDao().selectByProfile(dbSession, profile);
changes = getChangesFromRulesToBeRemoved(dbSession, profile, activeRules);
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), changes, profile.getLanguage());
return changes;
}
private List<ActiveRuleChange> getChangesFromRulesToBeRemoved(DbSession dbSession, QProfileDto profile, List<OrgActiveRuleDto> rules) {
List<ActiveRuleChange> changes = new ArrayList<>();
Collection<String> ruleUuids = rules.stream().map(ActiveRuleDto::getRuleUuid).toList();
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, ruleUuids);
for (OrgActiveRuleDto activeRule : rules) {
if (ActiveRuleDto.INHERITED.equals(activeRule.getInheritance())) {
changes.addAll(ruleActivator.deactivate(dbSession, context, activeRule.getRuleUuid(), true));
} else if (ActiveRuleDto.OVERRIDES.equals(activeRule.getInheritance())) {
context.reset(activeRule.getRuleUuid());
activeRule.setInheritance(null);
activeRule.setUpdatedAt(system2.now());
db.activeRuleDao().update(dbSession, activeRule);
changes.add(new ActiveRuleChange(ActiveRuleChange.Type.UPDATED, activeRule, context.getRule().get()).setInheritance(null));
}
}
return changes;
}
private boolean isDescendant(DbSession dbSession, QProfileDto childProfile, @Nullable QProfileDto parentProfile) {
QProfileDto currentParent = parentProfile;
while (currentParent != null) {
if (childProfile.getName().equals(currentParent.getName())) {
return true;
}
String parentKey = currentParent.getParentKee();
if (parentKey != null) {
currentParent = db.qualityProfileDao().selectByUuid(dbSession, parentKey);
} else {
currentParent = null;
}
}
return false;
}
}
| 7,470 | 42.690058 | 173 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.Startable;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.DefaultQProfileDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfile;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsert;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfileRepository;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdate;
import org.sonar.server.qualityprofile.builtin.BuiltInQualityProfilesUpdateListener;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import static java.lang.String.format;
import static java.util.stream.Collectors.toMap;
import static org.sonar.server.qualityprofile.ActiveRuleInheritance.NONE;
/**
* Synchronize Quality profiles during server startup
*/
@ServerSide
public class RegisterQualityProfiles implements Startable {
private static final Logger LOGGER = Loggers.get(RegisterQualityProfiles.class);
private final BuiltInQProfileRepository builtInQProfileRepository;
private final DbClient dbClient;
private final BuiltInQProfileInsert builtInQProfileInsert;
private final BuiltInQProfileUpdate builtInQProfileUpdate;
private final BuiltInQualityProfilesUpdateListener builtInQualityProfilesNotification;
private final System2 system2;
public RegisterQualityProfiles(BuiltInQProfileRepository builtInQProfileRepository,
DbClient dbClient, BuiltInQProfileInsert builtInQProfileInsert, BuiltInQProfileUpdate builtInQProfileUpdate,
BuiltInQualityProfilesUpdateListener builtInQualityProfilesNotification, System2 system2) {
this.builtInQProfileRepository = builtInQProfileRepository;
this.dbClient = dbClient;
this.builtInQProfileInsert = builtInQProfileInsert;
this.builtInQProfileUpdate = builtInQProfileUpdate;
this.builtInQualityProfilesNotification = builtInQualityProfilesNotification;
this.system2 = system2;
}
@Override
public void start() {
List<BuiltInQProfile> builtInQProfiles = builtInQProfileRepository.get();
if (builtInQProfiles.isEmpty()) {
return;
}
Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register quality profiles");
try (DbSession dbSession = dbClient.openSession(false);
DbSession batchDbSession = dbClient.openSession(true)) {
long startDate = system2.now();
Map<QProfileName, RulesProfileDto> persistedRuleProfiles = loadPersistedProfiles(dbSession);
Multimap<QProfileName, ActiveRuleChange> changedProfiles = ArrayListMultimap.create();
builtInQProfiles.forEach(builtIn -> {
RulesProfileDto ruleProfile = persistedRuleProfiles.get(builtIn.getQProfileName());
if (ruleProfile == null) {
create(dbSession, batchDbSession, builtIn);
} else {
List<ActiveRuleChange> changes = update(dbSession, builtIn, ruleProfile);
changedProfiles.putAll(builtIn.getQProfileName(), changes.stream()
.filter(change -> {
String inheritance = change.getActiveRule().getInheritance();
return inheritance == null || NONE.name().equals(inheritance);
})
.toList());
}
});
if (!changedProfiles.isEmpty()) {
long endDate = system2.now();
builtInQualityProfilesNotification.onChange(changedProfiles, startDate, endDate);
}
ensureBuiltInDefaultQPContainsRules(dbSession);
unsetBuiltInFlagAndRenameQPWhenPluginUninstalled(dbSession);
dbSession.commit();
}
profiler.stopDebug();
}
@Override
public void stop() {
// nothing to do
}
private Map<QProfileName, RulesProfileDto> loadPersistedProfiles(DbSession dbSession) {
return dbClient.qualityProfileDao().selectBuiltInRuleProfiles(dbSession).stream()
.collect(toMap(rp -> new QProfileName(rp.getLanguage(), rp.getName()), Function.identity()));
}
private void create(DbSession dbSession, DbSession batchDbSession, BuiltInQProfile builtIn) {
LOGGER.info("Register profile {}", builtIn.getQProfileName());
renameOutdatedProfiles(dbSession, builtIn);
builtInQProfileInsert.create(batchDbSession, builtIn);
}
private List<ActiveRuleChange> update(DbSession dbSession, BuiltInQProfile definition, RulesProfileDto dbProfile) {
LOGGER.info("Update profile {}", definition.getQProfileName());
return builtInQProfileUpdate.update(dbSession, definition, dbProfile);
}
/**
* The Quality profiles created by users should be renamed when they have the same name
* as the built-in profile to be persisted.
* <p>
* When upgrading from < 6.5 , all existing profiles are considered as "custom" (created
* by users) because the concept of built-in profile is not persisted. The "Sonar way" profiles
* are renamed to "Sonar way (outdated copy) in order to avoid conflicts with the new
* built-in profile "Sonar way", which has probably different configuration.
*/
private void renameOutdatedProfiles(DbSession dbSession, BuiltInQProfile profile) {
Collection<String> uuids = dbClient.qualityProfileDao().selectUuidsOfCustomRulesProfiles(dbSession, profile.getLanguage(), profile.getName());
if (uuids.isEmpty()) {
return;
}
Profiler profiler = Profiler.createIfDebug(Loggers.get(getClass())).start();
String newName = profile.getName() + " (outdated copy)";
LOGGER.info("Rename Quality profiles [{}/{}] to [{}]", profile.getLanguage(), profile.getName(), newName);
dbClient.qualityProfileDao().renameRulesProfilesAndCommit(dbSession, uuids, newName);
profiler.stopDebug(format("%d Quality profiles renamed to [%s]", uuids.size(), newName));
}
/**
* This method ensure that if a default built-in quality profile does not have any active rules but another built-in one for the same language
* does have active rules, the last one will be the default one.
*
* @see <a href="https://jira.sonarsource.com/browse/SONAR-10363">SONAR-10363</a>
*/
private void ensureBuiltInDefaultQPContainsRules(DbSession dbSession) {
Map<String, RulesProfileDto> rulesProfilesByLanguage = dbClient.qualityProfileDao().selectBuiltInRuleProfilesWithActiveRules(dbSession).stream()
.collect(toMap(RulesProfileDto::getLanguage, Function.identity(), (oldValue, newValue) -> oldValue));
dbClient.qualityProfileDao().selectDefaultBuiltInProfilesWithoutActiveRules(dbSession, rulesProfilesByLanguage.keySet())
.forEach(qp -> {
RulesProfileDto rulesProfile = rulesProfilesByLanguage.get(qp.getLanguage());
if (rulesProfile == null) {
return;
}
QProfileDto qualityProfile = dbClient.qualityProfileDao().selectByRuleProfileUuid(dbSession, rulesProfile.getUuid());
if (qualityProfile == null) {
return;
}
Set<String> uuids = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, Collections.singleton(qp.getKee()));
dbClient.defaultQProfileDao().deleteByQProfileUuids(dbSession, uuids);
dbClient.defaultQProfileDao().insertOrUpdate(dbSession, new DefaultQProfileDto()
.setQProfileUuid(qualityProfile.getKee())
.setLanguage(qp.getLanguage()));
LOGGER.info("Default built-in quality profile for language [{}] has been updated from [{}] to [{}] since previous default does not have active rules.",
qp.getLanguage(),
qp.getName(),
rulesProfile.getName());
});
}
public void unsetBuiltInFlagAndRenameQPWhenPluginUninstalled(DbSession dbSession) {
var pluginsBuiltInQProfiles = builtInQProfileRepository.get()
.stream()
.map(BuiltInQProfile::getQProfileName)
.collect(Collectors.toSet());
var languages = pluginsBuiltInQProfiles.stream().map(QProfileName::getLanguage).collect(Collectors.toSet());
dbClient.qualityProfileDao().selectBuiltInRuleProfiles(dbSession)
.forEach(qProfileDto -> {
var dbProfileName = QProfileName.createFor(qProfileDto.getLanguage(), qProfileDto.getName());
// Built-in Quality Profile can be a leftover from plugin which has been removed
// Rename Quality Profile and unset built-in flag allowing Quality Profile for existing languages to be removed
// Quality Profiles for languages not existing anymore are marked as 'REMOVED' and won't be seen in UI
if (!pluginsBuiltInQProfiles.contains(dbProfileName) && languages.contains(qProfileDto.getLanguage())) {
String oldName = qProfileDto.getName();
String newName = generateNewProfileName(qProfileDto);
qProfileDto.setName(newName);
qProfileDto.setIsBuiltIn(false);
dbClient.qualityProfileDao().update(dbSession, qProfileDto);
LOGGER.info("Quality profile [{}] for language [{}] is no longer built-in and has been renamed to [{}] "
+ "since it does not have any active rules.",
oldName,
dbProfileName.getLanguage(),
newName);
}
});
}
/**
* Abbreviate Quality Profile name if it will be too long with prefix and append suffix
*/
private String generateNewProfileName(RulesProfileDto qProfileDto) {
var shortName = StringUtils.abbreviate(qProfileDto.getName(), 40);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd yyyy 'at' hh:mm a")
.withLocale(Locale.getDefault())
.withZone(ZoneId.systemDefault());
var now = formatter.format(Instant.ofEpochMilli(system2.now()));
String suffix = " (outdated copy since " + now + ")";
return shortName + suffix;
}
}
| 11,248 | 44.176707 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.qualityprofile;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotification.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import org.sonar.api.notifications.Notification;
public class BuiltInQPChangeNotification extends Notification {
static final String TYPE = "built-in-quality-profiles";
public BuiltInQPChangeNotification() {
super(TYPE);
}
}
| 1,130 | 35.483871 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.sonar.api.notifications.Notification;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
public class BuiltInQPChangeNotificationBuilder {
private static final String NUMBER_OF_PROFILES = "numberOfProfiles";
private static final String PROFILE_NAME = ".profileName";
private static final String LANGUAGE_KEY = ".languageKey";
private static final String LANGUAGE_NAME = ".languageName";
private static final String NEW_RULES = ".newRules";
private static final String UPDATED_RULES = ".updatedRules";
private static final String REMOVED_RULES = ".removedRules";
private static final String START_DATE = ".startDate";
private static final String END_DATE = ".endDate";
private final List<Profile> profiles = new ArrayList<>();
public BuiltInQPChangeNotificationBuilder addProfile(Profile profile) {
profiles.add(profile);
return this;
}
public BuiltInQPChangeNotification build() {
BuiltInQPChangeNotification notification = new BuiltInQPChangeNotification();
notification.setFieldValue(NUMBER_OF_PROFILES, String.valueOf(profiles.size()));
AtomicInteger count = new AtomicInteger();
profiles.forEach(profile -> {
int index = count.getAndIncrement();
notification.setFieldValue(index + PROFILE_NAME, profile.getProfileName());
notification.setFieldValue(index + LANGUAGE_KEY, profile.getLanguageKey());
notification.setFieldValue(index + LANGUAGE_NAME, profile.getLanguageName());
notification.setFieldValue(index + NEW_RULES, String.valueOf(profile.getNewRules()));
notification.setFieldValue(index + UPDATED_RULES, String.valueOf(profile.getUpdatedRules()));
notification.setFieldValue(index + REMOVED_RULES, String.valueOf(profile.getRemovedRules()));
notification.setFieldValue(index + START_DATE, String.valueOf(profile.getStartDate()));
notification.setFieldValue(index + END_DATE, String.valueOf(profile.getEndDate()));
});
return notification;
}
public static BuiltInQPChangeNotificationBuilder parse(Notification notification) {
checkState(BuiltInQPChangeNotification.TYPE.equals(notification.getType()),
"Expected notification of type %s but got %s", BuiltInQPChangeNotification.TYPE, notification.getType());
BuiltInQPChangeNotificationBuilder notif = new BuiltInQPChangeNotificationBuilder();
String numberOfProfilesText = notification.getFieldValue(NUMBER_OF_PROFILES);
checkState(numberOfProfilesText != null, "Could not read the built-in quality profile notification");
Integer numberOfProfiles = Integer.valueOf(numberOfProfilesText);
IntStream.rangeClosed(0, numberOfProfiles - 1)
.mapToObj(index -> Profile.newBuilder()
.setProfileName(getNonNullFieldValue(notification, index + PROFILE_NAME))
.setLanguageKey(getNonNullFieldValue(notification, index + LANGUAGE_KEY))
.setLanguageName(getNonNullFieldValue(notification, index + LANGUAGE_NAME))
.setNewRules(parseInt(getNonNullFieldValue(notification, index + NEW_RULES)))
.setUpdatedRules(parseInt(getNonNullFieldValue(notification, index + UPDATED_RULES)))
.setRemovedRules(parseInt(getNonNullFieldValue(notification, index + REMOVED_RULES)))
.setStartDate(parseLong(getNonNullFieldValue(notification, index + START_DATE)))
.setEndDate(parseLong(getNonNullFieldValue(notification, index + END_DATE)))
.build())
.forEach(notif::addProfile);
return notif;
}
private static String getNonNullFieldValue(Notification notification, String key) {
String value = notification.getFieldValue(key);
return requireNonNull(value, format("Notification field '%s' is null", key));
}
public List<Profile> getProfiles() {
return profiles;
}
public static class Profile {
private final String profileName;
private final String languageKey;
private final String languageName;
private final int newRules;
private final int updatedRules;
private final int removedRules;
private final long startDate;
private final long endDate;
public Profile(Builder builder) {
this.profileName = builder.profileName;
this.languageKey = builder.languageKey;
this.languageName = builder.languageName;
this.newRules = builder.newRules;
this.updatedRules = builder.updatedRules;
this.removedRules = builder.removedRules;
this.startDate = builder.startDate;
this.endDate = builder.endDate;
}
public String getProfileName() {
return profileName;
}
public String getLanguageKey() {
return languageKey;
}
public String getLanguageName() {
return languageName;
}
public int getNewRules() {
return newRules;
}
public int getUpdatedRules() {
return updatedRules;
}
public int getRemovedRules() {
return removedRules;
}
public long getStartDate() {
return startDate;
}
public long getEndDate() {
return endDate;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String profileName;
private String languageKey;
private String languageName;
private int newRules;
private int updatedRules;
private int removedRules;
private long startDate;
private long endDate;
private Builder() {
}
public Builder setLanguageKey(String languageKey) {
this.languageKey = requireNonNull(languageKey, "languageKEy should not be null");
return this;
}
public Builder setLanguageName(String languageName) {
this.languageName = requireNonNull(languageName, "languageName should not be null");
return this;
}
public Builder setProfileName(String profileName) {
this.profileName = requireNonNull(profileName, "profileName should not be null");
return this;
}
public Builder setNewRules(int newRules) {
checkState(newRules >= 0, "newRules should not be negative");
this.newRules = newRules;
return this;
}
public Builder setUpdatedRules(int updatedRules) {
checkState(updatedRules >= 0, "updatedRules should not be negative");
this.updatedRules = updatedRules;
return this;
}
public Builder setRemovedRules(int removedRules) {
checkState(removedRules >= 0, "removedRules should not be negative");
this.removedRules = removedRules;
return this;
}
public Builder setStartDate(long startDate) {
this.startDate = startDate;
return this;
}
public Builder setEndDate(long endDate) {
this.endDate = endDate;
return this;
}
public Profile build() {
return new Profile(this);
}
}
}
}
| 8,081 | 35.570136 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.notification.EmailNotificationHandler;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
public class BuiltInQPChangeNotificationHandler extends EmailNotificationHandler<BuiltInQPChangeNotification> {
private final DbClient dbClient;
public BuiltInQPChangeNotificationHandler(DbClient dbClient, EmailNotificationChannel emailNotificationChannel) {
super(emailNotificationChannel);
this.dbClient = dbClient;
}
@Override
public Optional<NotificationDispatcherMetadata> getMetadata() {
return Optional.empty();
}
@Override
public Class<BuiltInQPChangeNotification> getNotificationClass() {
return BuiltInQPChangeNotification.class;
}
@Override
public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<BuiltInQPChangeNotification> notifications) {
try (DbSession session = dbClient.openSession(false)) {
return dbClient.authorizationDao()
.selectQualityProfileAdministratorLogins(session)
.stream()
.flatMap(t -> notifications.stream().map(notification -> new EmailDeliveryRequest(t.getEmail(), notification)))
.collect(Collectors.toSet());
}
}
}
| 2,415 | 37.967742 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplate.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.Date;
import javax.annotation.CheckForNull;
import org.sonar.api.notifications.Notification;
import org.sonar.api.platform.Server;
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.issue.notification.EmailTemplate;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.sonar.api.utils.DateUtils.formatDate;
import static org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
import static org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.parse;
public class BuiltInQPChangeNotificationTemplate implements EmailTemplate {
private final Server server;
public BuiltInQPChangeNotificationTemplate(Server server) {
this.server = server;
}
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) {
return null;
}
BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification);
StringBuilder message = new StringBuilder("The following built-in profiles have been updated:\n\n");
profilesNotification.getProfiles().stream()
.sorted(Comparator.comparing(Profile::getLanguageName).thenComparing(Profile::getProfileName))
.forEach(profile -> {
message.append("\"")
.append(profile.getProfileName())
.append("\" - ")
.append(profile.getLanguageName())
.append(": ")
.append(server.getPublicRootUrl()).append("/profiles/changelog?language=")
.append(profile.getLanguageKey())
.append("&name=")
.append(encode(profile.getProfileName()))
.append("&since=")
.append(formatDate(new Date(profile.getStartDate())))
.append("&to=")
.append(formatDate(new Date(profile.getEndDate())))
.append("\n");
int newRules = profile.getNewRules();
if (newRules > 0) {
message.append(" ").append(newRules).append(" new rule")
.append(plural(newRules))
.append('\n');
}
int updatedRules = profile.getUpdatedRules();
if (updatedRules > 0) {
message.append(" ").append(updatedRules).append(" rule")
.append(updatedRules > 1 ? "s have been updated" : " has been updated")
.append("\n");
}
int removedRules = profile.getRemovedRules();
if (removedRules > 0) {
message.append(" ").append(removedRules).append(" rule")
.append(plural(removedRules))
.append(" removed\n");
}
message.append("\n");
});
message.append("This is a good time to review your quality profiles and update them to benefit from the latest evolutions: ");
message.append(server.getPublicRootUrl()).append("/profiles");
// And finally return the email that will be sent
return new EmailMessage()
.setMessageId(BuiltInQPChangeNotification.TYPE)
.setSubject("Built-in quality profiles have been updated")
.setPlainTextMessage(message.toString());
}
private static String plural(int count) {
return count > 1 ? "s" : "";
}
public String encode(String text) {
try {
return URLEncoder.encode(text, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(String.format("Cannot encode %s", text), e);
}
}
}
| 4,454 | 38.078947 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import static java.util.Collections.unmodifiableList;
import static org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInActiveRule;
import static org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.OverriddenParam;
/**
* Represent a Quality Profile as computed from {@link BuiltInQualityProfilesDefinition} provided by installed plugins.
*/
@Immutable
public final class BuiltInQProfile {
private final QProfileName qProfileName;
private final boolean isDefault;
private final List<ActiveRule> activeRules;
private BuiltInQProfile(Builder builder) {
this.qProfileName = new QProfileName(builder.language, builder.name);
this.isDefault = builder.declaredDefault || builder.computedDefault;
this.activeRules = unmodifiableList(builder.activeRules);
}
public String getName() {
return qProfileName.getName();
}
public String getLanguage() {
return qProfileName.getLanguage();
}
public QProfileName getQProfileName() {
return qProfileName;
}
public boolean isDefault() {
return isDefault;
}
public List<ActiveRule> getActiveRules() {
return activeRules;
}
public static final class ActiveRule {
private final String ruleUuid;
private final RuleKey ruleKey;
private final String severity;
private final List<OverriddenParam> params;
public ActiveRule(String ruleUuid, BuiltInActiveRule builtIn) {
this(ruleUuid, RuleKey.of(builtIn.repoKey(), builtIn.ruleKey()), builtIn.overriddenSeverity(), builtIn.overriddenParams());
}
ActiveRule(String ruleUuid, RuleKey ruleKey, @Nullable String severity, List<OverriddenParam> params) {
this.ruleUuid = ruleUuid;
this.ruleKey = ruleKey;
this.severity = severity;
this.params = params;
}
public String getRuleUuid() {
return ruleUuid;
}
public RuleKey getRuleKey() {
return ruleKey;
}
@CheckForNull
public String getSeverity() {
return severity;
}
public List<OverriddenParam> getParams() {
return params;
}
}
static final class Builder {
private String language;
private String name;
private boolean declaredDefault;
private boolean computedDefault;
private final List<ActiveRule> activeRules = new ArrayList<>();
public Builder setLanguage(String language) {
this.language = language;
return this;
}
Builder setName(String name) {
this.name = name;
return this;
}
String getName() {
return name;
}
Builder setDeclaredDefault(boolean declaredDefault) {
this.declaredDefault = declaredDefault;
return this;
}
boolean isDeclaredDefault() {
return declaredDefault;
}
Builder setComputedDefault(boolean flag) {
computedDefault = flag;
return this;
}
Builder addRule(ActiveRule activeRule) {
this.activeRules.add(activeRule);
return this;
}
BuiltInQProfile build() {
return new BuiltInQProfile(this);
}
}
}
| 4,211 | 27.268456 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileInsert.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import org.sonar.db.DbSession;
public interface BuiltInQProfileInsert {
/**
* Persist a new built-in profile
* Db sessions are committed and Elasticsearch indices are updated
*/
void create(DbSession batchSession, BuiltInQProfile builtInQProfile);
}
| 1,157 | 36.354839 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileInsertImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import com.google.common.base.Splitter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.DefaultQProfileDto;
import org.sonar.db.qualityprofile.OrgQProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.ServerRuleFinder;
import org.sonar.server.util.TypeValidations;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNull;
public class BuiltInQProfileInsertImpl implements BuiltInQProfileInsert {
private final DbClient dbClient;
private final ServerRuleFinder ruleFinder;
private final System2 system2;
private final UuidFactory uuidFactory;
private final TypeValidations typeValidations;
private final ActiveRuleIndexer activeRuleIndexer;
private RuleRepository ruleRepository;
public BuiltInQProfileInsertImpl(DbClient dbClient, ServerRuleFinder ruleFinder, System2 system2, UuidFactory uuidFactory,
TypeValidations typeValidations, ActiveRuleIndexer activeRuleIndexer) {
this.dbClient = dbClient;
this.ruleFinder = ruleFinder;
this.system2 = system2;
this.uuidFactory = uuidFactory;
this.typeValidations = typeValidations;
this.activeRuleIndexer = activeRuleIndexer;
}
@Override
public void create(DbSession batchDbSession, BuiltInQProfile builtInQProfile) {
initRuleRepository(batchDbSession);
Date now = new Date(system2.now());
RulesProfileDto ruleProfile = insertRulesProfile(batchDbSession, builtInQProfile, now);
List<ActiveRuleChange> changes = builtInQProfile.getActiveRules().stream()
.map(activeRule -> insertActiveRule(batchDbSession, ruleProfile, activeRule, now.getTime()))
.toList();
changes.forEach(change -> dbClient.qProfileChangeDao().insert(batchDbSession, change.toDto(null)));
createDefaultAndOrgQProfiles(batchDbSession, builtInQProfile, ruleProfile);
activeRuleIndexer.commitAndIndex(batchDbSession, changes);
}
private void createDefaultAndOrgQProfiles(DbSession batchDbSession, BuiltInQProfile builtIn, RulesProfileDto rulesProfileDto) {
Optional<String> qProfileUuid = dbClient.defaultQProfileDao().selectDefaultQProfileUuid(batchDbSession, builtIn.getLanguage());
OrgQProfileDto dto = new OrgQProfileDto()
.setRulesProfileUuid(rulesProfileDto.getUuid())
.setUuid(uuidFactory.create());
if (builtIn.isDefault() && qProfileUuid.isEmpty()) {
DefaultQProfileDto defaultQProfileDto = new DefaultQProfileDto()
.setQProfileUuid(dto.getUuid())
.setLanguage(builtIn.getLanguage());
dbClient.defaultQProfileDao().insert(batchDbSession, defaultQProfileDto);
}
dbClient.qualityProfileDao().insert(batchDbSession, dto);
}
private void initRuleRepository(DbSession dbSession) {
if (ruleRepository == null) {
ruleRepository = new RuleRepository(dbClient, dbSession, ruleFinder);
}
}
private RulesProfileDto insertRulesProfile(DbSession dbSession, BuiltInQProfile builtIn, Date now) {
RulesProfileDto dto = new RulesProfileDto()
.setUuid(uuidFactory.create())
.setName(builtIn.getName())
.setLanguage(builtIn.getLanguage())
.setIsBuiltIn(true)
.setRulesUpdatedAtAsDate(now);
dbClient.qualityProfileDao().insert(dbSession, dto);
return dto;
}
private ActiveRuleChange insertActiveRule(DbSession batchDbSession, RulesProfileDto rulesProfileDto, BuiltInQProfile.ActiveRule activeRule, long now) {
RuleKey ruleKey = activeRule.getRuleKey();
RuleDto ruleDefinitionDto = ruleRepository.getDefinition(ruleKey)
.orElseThrow(() -> new IllegalStateException("RuleDefinition not found for key " + ruleKey));
ActiveRuleDto dto = new ActiveRuleDto();
dto.setProfileUuid(rulesProfileDto.getUuid());
dto.setRuleUuid(ruleDefinitionDto.getUuid());
dto.setKey(ActiveRuleKey.of(rulesProfileDto, ruleDefinitionDto.getKey()));
dto.setSeverity(firstNonNull(activeRule.getSeverity(), ruleDefinitionDto.getSeverityString()));
dto.setUpdatedAt(now);
dto.setCreatedAt(now);
dbClient.activeRuleDao().insert(batchDbSession, dto);
List<ActiveRuleParamDto> paramDtos = insertActiveRuleParams(batchDbSession, activeRule, dto);
ActiveRuleChange change = new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, dto, ruleDefinitionDto);
change.setSeverity(dto.getSeverityString());
paramDtos.forEach(paramDto -> change.setParameter(paramDto.getKey(), paramDto.getValue()));
return change;
}
private List<ActiveRuleParamDto> insertActiveRuleParams(DbSession session, BuiltInQProfile.ActiveRule activeRule, ActiveRuleDto activeRuleDto) {
Map<String, String> valuesByParamKey = activeRule.getParams().stream()
.collect(Collectors.toMap(BuiltInQualityProfilesDefinition.OverriddenParam::key, BuiltInQualityProfilesDefinition.OverriddenParam::overriddenValue));
List<ActiveRuleParamDto> rules = ruleRepository.getRuleParams(activeRule.getRuleKey()).stream()
.map(param -> createParamDto(param, Optional.ofNullable(valuesByParamKey.get(param.getName())).orElse(param.getDefaultValue())))
.filter(Objects::nonNull)
.toList();
rules.forEach(paramDto -> dbClient.activeRuleDao().insertParam(session, activeRuleDto, paramDto));
return rules;
}
@CheckForNull
private ActiveRuleParamDto createParamDto(RuleParamDto param, @Nullable String value) {
if (value == null) {
return null;
}
ActiveRuleParamDto paramDto = ActiveRuleParamDto.createFor(param);
paramDto.setValue(validateParam(param, value));
return paramDto;
}
private String validateParam(RuleParamDto ruleParam, String value) {
RuleParamType ruleParamType = RuleParamType.parse(ruleParam.getType());
if (ruleParamType.multiple()) {
List<String> values = newArrayList(Splitter.on(",").split(value));
typeValidations.validate(values, ruleParamType.type(), ruleParamType.values());
} else {
typeValidations.validate(value, ruleParamType.type(), ruleParamType.values());
}
return value;
}
private static class RuleRepository {
private final Map<RuleKey, Set<RuleParamDto>> params;
private final ServerRuleFinder ruleFinder;
private RuleRepository(DbClient dbClient, DbSession session, ServerRuleFinder ruleFinder) {
this.ruleFinder = ruleFinder;
this.params = new HashMap<>();
for (RuleParamDto ruleParam : dbClient.ruleDao().selectAllRuleParams(session)) {
Optional<RuleKey> ruleKey = ruleFinder.findDtoByUuid(ruleParam.getRuleUuid())
.map(r -> RuleKey.of(r.getRepositoryKey(), r.getRuleKey()));
if (ruleKey.isPresent()) {
params.computeIfAbsent(ruleKey.get(), r -> new HashSet<>()).add(ruleParam);
}
}
}
private Optional<RuleDto> getDefinition(RuleKey ruleKey) {
return ruleFinder.findDtoByKey(requireNonNull(ruleKey, "RuleKey can't be null"));
}
private Set<RuleParamDto> getRuleParams(RuleKey ruleKey) {
return params.getOrDefault(requireNonNull(ruleKey, "RuleKey can't be null"), emptySet());
}
}
}
| 9,000 | 41.258216 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import org.sonar.api.Startable;
/**
* Startable added to {@link org.sonar.server.platform.platformlevel.PlatformLevelStartup} responsible for initializing
* {@link BuiltInQProfileRepository}.
*/
public class BuiltInQProfileLoader implements Startable {
private final BuiltInQProfileRepository builtInQProfileRepository;
public BuiltInQProfileLoader(BuiltInQProfileRepository builtInQProfileRepository) {
this.builtInQProfileRepository = builtInQProfileRepository;
}
@Override
public void start() {
builtInQProfileRepository.initialize();
}
@Override
public void stop() {
// nothing to do
}
}
| 1,522 | 32.844444 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.List;
public interface BuiltInQProfileRepository {
/**
* Initializes the Repository.
*
* This method is intended to be called from a startup task
* (see {@link org.sonar.server.platform.platformlevel.PlatformLevelStartup}).
*
* @throws IllegalStateException if called more then once
*/
void initialize();
/**
* @return an immutable list
*
* @throws IllegalStateException if {@link #initialize()} has not been called
*/
List<BuiltInQProfile> get();
}
| 1,403 | 32.428571 | 80 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInQualityProfile;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.rule.ServerRuleFinder;
import org.springframework.beans.factory.annotation.Autowired;
import static com.google.common.base.Preconditions.checkState;
public class BuiltInQProfileRepositoryImpl implements BuiltInQProfileRepository {
private static final Logger LOGGER = Loggers.get(BuiltInQProfileRepositoryImpl.class);
private static final String DEFAULT_PROFILE_NAME = "Sonar way";
private final DbClient dbClient;
private final ServerRuleFinder ruleFinder;
private final Languages languages;
private final List<BuiltInQualityProfilesDefinition> definitions;
private List<BuiltInQProfile> qProfiles;
/**
* Used by the ioc container when no {@link BuiltInQualityProfilesDefinition} is defined at all
*/
@Autowired(required = false)
public BuiltInQProfileRepositoryImpl(DbClient dbClient, ServerRuleFinder ruleFinder, Languages languages) {
this(dbClient, ruleFinder, languages, new BuiltInQualityProfilesDefinition[0]);
}
@Autowired(required = false)
public BuiltInQProfileRepositoryImpl(DbClient dbClient, ServerRuleFinder ruleFinder, Languages languages, BuiltInQualityProfilesDefinition... definitions) {
this.dbClient = dbClient;
this.ruleFinder = ruleFinder;
this.languages = languages;
this.definitions = ImmutableList.copyOf(definitions);
}
@Override
public void initialize() {
checkState(qProfiles == null, "initialize must be called only once");
Profiler profiler = Profiler.create(LOGGER).startInfo("Load quality profiles");
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
for (BuiltInQualityProfilesDefinition definition : definitions) {
definition.define(context);
}
Map<String, Map<String, BuiltInQualityProfile>> rulesProfilesByLanguage = validateAndClean(context);
this.qProfiles = toFlatList(rulesProfilesByLanguage);
ensureAllLanguagesHaveAtLeastOneBuiltInQP();
profiler.stopDebug();
}
@Override
public List<BuiltInQProfile> get() {
checkState(qProfiles != null, "initialize must be called first");
return qProfiles;
}
private void ensureAllLanguagesHaveAtLeastOneBuiltInQP() {
Set<String> languagesWithBuiltInQProfiles = qProfiles.stream().map(BuiltInQProfile::getLanguage).collect(Collectors.toSet());
Set<String> languagesWithoutBuiltInQProfiles = Arrays.stream(languages.all())
.map(Language::getKey)
.filter(key -> !languagesWithBuiltInQProfiles.contains(key))
.collect(Collectors.toSet());
checkState(languagesWithoutBuiltInQProfiles.isEmpty(), "The following languages have no built-in quality profiles: %s",
String.join("", languagesWithoutBuiltInQProfiles));
}
private Map<String, Map<String, BuiltInQualityProfile>> validateAndClean(BuiltInQualityProfilesDefinition.Context context) {
Map<String, Map<String, BuiltInQualityProfile>> profilesByLanguageAndName = context.profilesByLanguageAndName();
profilesByLanguageAndName.entrySet()
.removeIf(entry -> {
String language = entry.getKey();
if (languages.get(language) == null) {
LOGGER.info("Language {} is not installed, related quality profiles are ignored", language);
return true;
}
return false;
});
return profilesByLanguageAndName;
}
private List<BuiltInQProfile> toFlatList(Map<String, Map<String, BuiltInQualityProfile>> rulesProfilesByLanguage) {
if (rulesProfilesByLanguage.isEmpty()) {
return Collections.emptyList();
}
Map<RuleKey, RuleDto> rulesByRuleKey = loadRuleDefinitionsByRuleKey();
Map<String, List<BuiltInQProfile.Builder>> buildersByLanguage = rulesProfilesByLanguage
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, rulesProfilesByLanguageAndName -> toQualityProfileBuilders(rulesProfilesByLanguageAndName, rulesByRuleKey)));
return buildersByLanguage
.entrySet()
.stream()
.filter(BuiltInQProfileRepositoryImpl::ensureAtMostOneDeclaredDefault)
.map(entry -> toQualityProfiles(entry.getValue()))
.flatMap(Collection::stream)
.toList();
}
private Map<RuleKey, RuleDto> loadRuleDefinitionsByRuleKey() {
try (DbSession dbSession = dbClient.openSession(false)) {
Collection<RuleDto> ruleDefinitions = ruleFinder.findAll();
Multimap<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByRuleId = dbClient.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
.collect(MoreCollectors.index(DeprecatedRuleKeyDto::getRuleUuid));
Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
for (RuleDto ruleDto : ruleDefinitions) {
rulesByRuleKey.put(ruleDto.getKey(), ruleDto);
deprecatedRuleKeysByRuleId.get(ruleDto.getUuid()).forEach(t -> rulesByRuleKey.put(RuleKey.of(t.getOldRepositoryKey(), t.getOldRuleKey()), ruleDto));
}
return rulesByRuleKey;
}
}
/**
* Creates {@link BuiltInQProfile.Builder} for each unique quality profile name for a given language.
* Builders will have the following properties populated:
* <ul>
* <li>{@link BuiltInQProfile.Builder#language language}: key of the method's parameter</li>
* <li>{@link BuiltInQProfile.Builder#name name}: {@link RulesProfile#getName()}</li>
* <li>{@link BuiltInQProfile.Builder#declaredDefault declaredDefault}: {@code true} if at least one RulesProfile
* with a given name has {@link RulesProfile#getDefaultProfile()} is {@code true}</li>
* <li>{@link BuiltInQProfile.Builder#activeRules activeRules}: the concatenate of the active rules of all
* RulesProfile with a given name</li>
* </ul>
*/
private static List<BuiltInQProfile.Builder> toQualityProfileBuilders(Map.Entry<String, Map<String, BuiltInQualityProfile>> rulesProfilesByLanguageAndName,
Map<RuleKey, RuleDto> rulesByRuleKey) {
String language = rulesProfilesByLanguageAndName.getKey();
// use a LinkedHashMap to keep order of insertion of RulesProfiles
Map<String, BuiltInQProfile.Builder> qualityProfileBuildersByName = new LinkedHashMap<>();
for (BuiltInQualityProfile builtInProfile : rulesProfilesByLanguageAndName.getValue().values()) {
qualityProfileBuildersByName.compute(
builtInProfile.name(),
(name, existingBuilder) -> updateOrCreateBuilder(language, existingBuilder, builtInProfile, rulesByRuleKey));
}
return ImmutableList.copyOf(qualityProfileBuildersByName.values());
}
/**
* Fails if more than one {@link BuiltInQProfile.Builder#declaredDefault} is {@code true}, otherwise returns {@code true}.
*/
private static boolean ensureAtMostOneDeclaredDefault(Map.Entry<String, List<BuiltInQProfile.Builder>> entry) {
Set<String> declaredDefaultProfileNames = entry.getValue().stream()
.filter(BuiltInQProfile.Builder::isDeclaredDefault)
.map(BuiltInQProfile.Builder::getName)
.collect(Collectors.toSet());
checkState(declaredDefaultProfileNames.size() <= 1, "Several Quality profiles are flagged as default for the language %s: %s", entry.getKey(), declaredDefaultProfileNames);
return true;
}
private static BuiltInQProfile.Builder updateOrCreateBuilder(String language, @Nullable BuiltInQProfile.Builder existingBuilder, BuiltInQualityProfile builtInProfile,
Map<RuleKey, RuleDto> rulesByRuleKey) {
BuiltInQProfile.Builder builder = createOrReuseBuilder(existingBuilder, language, builtInProfile);
builder.setDeclaredDefault(builtInProfile.isDefault());
builtInProfile.rules().forEach(builtInActiveRule -> {
RuleKey ruleKey = RuleKey.of(builtInActiveRule.repoKey(), builtInActiveRule.ruleKey());
RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
checkState(ruleDto != null, "Rule with key '%s' not found", ruleKey);
builder.addRule(new BuiltInQProfile.ActiveRule(ruleDto.getUuid(), ruleDto.getKey(),
builtInActiveRule.overriddenSeverity(), builtInActiveRule.overriddenParams()));
});
return builder;
}
private static BuiltInQProfile.Builder createOrReuseBuilder(@Nullable BuiltInQProfile.Builder existingBuilder, String language, BuiltInQualityProfile builtInProfile) {
if (existingBuilder == null) {
return new BuiltInQProfile.Builder()
.setLanguage(language)
.setName(builtInProfile.name());
}
return existingBuilder;
}
private static List<BuiltInQProfile> toQualityProfiles(List<BuiltInQProfile.Builder> builders) {
if (builders.stream().noneMatch(BuiltInQProfile.Builder::isDeclaredDefault)) {
Optional<BuiltInQProfile.Builder> sonarWayProfile = builders.stream().filter(builder -> builder.getName().equals(DEFAULT_PROFILE_NAME)).findFirst();
if (sonarWayProfile.isPresent()) {
sonarWayProfile.get().setComputedDefault(true);
} else {
builders.iterator().next().setComputedDefault(true);
}
}
return builders.stream()
.map(BuiltInQProfile.Builder::build)
.toList();
}
}
| 10,942 | 45.764957 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileUpdate.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.List;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
public interface BuiltInQProfileUpdate {
/**
* Persist an existing built-in profile.
* Db session is committed and Elasticsearch indices are updated.
*/
List<ActiveRuleChange> update(DbSession dbSession, BuiltInQProfile builtInQProfile, RulesProfileDto ruleProfile);
}
| 1,339 | 38.411765 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileUpdateImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
public class BuiltInQProfileUpdateImpl implements BuiltInQProfileUpdate {
private final DbClient dbClient;
private final RuleActivator ruleActivator;
private final ActiveRuleIndexer activeRuleIndexer;
private final QualityProfileChangeEventService qualityProfileChangeEventService;
public BuiltInQProfileUpdateImpl(DbClient dbClient, RuleActivator ruleActivator, ActiveRuleIndexer activeRuleIndexer,
QualityProfileChangeEventService qualityProfileChangeEventService) {
this.dbClient = dbClient;
this.ruleActivator = ruleActivator;
this.activeRuleIndexer = activeRuleIndexer;
this.qualityProfileChangeEventService = qualityProfileChangeEventService;
}
public List<ActiveRuleChange> update(DbSession dbSession, BuiltInQProfile builtInDefinition, RulesProfileDto initialRuleProfile) {
// Keep reference to all the activated rules before update
Set<String> deactivatedRuleUuids = dbClient.activeRuleDao().selectByRuleProfile(dbSession, initialRuleProfile)
.stream()
.map(ActiveRuleDto::getRuleUuid)
.collect(Collectors.toSet());
// all rules, including those which are removed from built-in profile
Set<String> ruleUuids = Stream.concat(
deactivatedRuleUuids.stream(),
builtInDefinition.getActiveRules().stream().map(BuiltInQProfile.ActiveRule::getRuleUuid))
.collect(Collectors.toSet());
Collection<RuleActivation> activations = new ArrayList<>();
for (BuiltInQProfile.ActiveRule ar : builtInDefinition.getActiveRules()) {
RuleActivation activation = convert(ar);
activations.add(activation);
deactivatedRuleUuids.remove(activation.getRuleUuid());
}
RuleActivationContext context = ruleActivator.createContextForBuiltInProfile(dbSession, initialRuleProfile, ruleUuids);
List<ActiveRuleChange> changes = new ArrayList<>();
changes.addAll(ruleActivator.activate(dbSession, activations, context));
// these rules are no longer part of the built-in profile
deactivatedRuleUuids.forEach(ruleUuid -> changes.addAll(ruleActivator.deactivate(dbSession, context, ruleUuid, false)));
if (!changes.isEmpty()) {
qualityProfileChangeEventService.distributeRuleChangeEvent(context.getProfiles(), changes, initialRuleProfile.getLanguage());
}
activeRuleIndexer.commitAndIndex(dbSession, changes);
return changes;
}
private static RuleActivation convert(BuiltInQProfile.ActiveRule ar) {
Map<String, String> params = ar.getParams().stream()
.collect(Collectors.toMap(BuiltInQualityProfilesDefinition.OverriddenParam::key, BuiltInQualityProfilesDefinition.OverriddenParam::overriddenValue));
return RuleActivation.create(ar.getRuleUuid(), ar.getSeverity(), params);
}
}
| 4,319 | 43.536082 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListener.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import com.google.common.collect.Multimap;
import java.util.Collection;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
import static org.sonar.core.config.CorePropertyDefinitions.DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.DEACTIVATED;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.UPDATED;
public class BuiltInQualityProfilesUpdateListener {
private final NotificationManager notificationManager;
private final Languages languages;
private final Configuration config;
public BuiltInQualityProfilesUpdateListener(NotificationManager notificationManager, Languages languages, Configuration config) {
this.notificationManager = notificationManager;
this.languages = languages;
this.config = config;
}
public void onChange(Multimap<QProfileName, ActiveRuleChange> changedProfiles, long startDate, long endDate) {
if (config.getBoolean(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES).orElse(false)) {
return;
}
BuiltInQPChangeNotificationBuilder builder = new BuiltInQPChangeNotificationBuilder();
changedProfiles.keySet().stream()
.map(changedProfile -> {
String profileName = changedProfile.getName();
Language language = languages.get(changedProfile.getLanguage());
Collection<ActiveRuleChange> activeRuleChanges = changedProfiles.get(changedProfile);
int newRules = (int) activeRuleChanges.stream().map(ActiveRuleChange::getType).filter(ACTIVATED::equals).count();
int updatedRules = (int) activeRuleChanges.stream().map(ActiveRuleChange::getType).filter(UPDATED::equals).count();
int removedRules = (int) activeRuleChanges.stream().map(ActiveRuleChange::getType).filter(DEACTIVATED::equals).count();
return Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(language.getKey())
.setLanguageName(language.getName())
.setNewRules(newRules)
.setUpdatedRules(updatedRules)
.setRemovedRules(removedRules)
.setStartDate(startDate)
.setEndDate(endDate)
.build();
})
.forEach(builder::addProfile);
notificationManager.scheduleForSending(builder.build());
}
}
| 3,532 | 44.294872 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/DescendantProfilesSupplier.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import java.util.Collection;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
@FunctionalInterface
public interface DescendantProfilesSupplier {
Result get(Collection<QProfileDto> profiles, Collection<String> ruleUuids);
record Result(Collection<QProfileDto> profiles, Collection<ActiveRuleDto> activeRules, Collection<ActiveRuleParamDto> activeRuleParams) {
}
}
| 1,369 | 38.142857 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/QProfileName.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import javax.annotation.Nullable;
public class QProfileName {
private final String lang;
private final String name;
public QProfileName(String lang, String name) {
this.lang = lang;
this.name = name;
}
public String getLanguage() {
return lang;
}
public String getName() {
return name;
}
public static QProfileName createFor(String lang, String name){
return new QProfileName(lang, name);
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QProfileName that = (QProfileName) o;
if (!lang.equals(that.lang)) {
return false;
}
return name.equals(that.name);
}
@Override
public int hashCode() {
int result = lang.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return String.format("%s/%s", lang, name);
}
}
| 1,888 | 25.236111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/RuleActivationContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.rule.RuleKey;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.RuleActivation;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonar.core.util.stream.MoreCollectors.index;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
/**
* Cache of the data required to activate/deactivate
* multiple rules on a Quality profile, including
* the rule definitions, the rule parameters, the tree
* of profiles hierarchy and its related active rules.
*/
public class RuleActivationContext {
private final long date;
// The profile that is initially targeted by the operation
private final RulesProfileDto baseRulesProfile;
private final Map<String, QProfileDto> profilesByUuid = new HashMap<>();
private final ListMultimap<String, QProfileDto> profilesByParentUuid = ArrayListMultimap.create();
// The rules/active rules involved in the group of activations/de-activations
private final Map<String, RuleWrapper> rulesByUuid = new HashMap<>();
private final Map<ActiveRuleKey, ActiveRuleWrapper> activeRulesByKey = new HashMap<>();
// Cursors used to move in the rules and in the tree of profiles.
private RulesProfileDto currentRulesProfile;
// Cardinality is zero-to-many when cursor is on a built-in rules profile,
// otherwise it's always one, and only one (cursor on descendants or on non-built-in base profile).
private Collection<QProfileDto> currentProfiles;
private RuleWrapper currentRule;
private ActiveRuleWrapper currentActiveRule;
private ActiveRuleWrapper currentParentActiveRule;
private boolean descendantsLoaded = false;
private final DescendantProfilesSupplier descendantProfilesSupplier;
private RuleActivationContext(Builder builder) {
this.date = builder.date;
this.descendantProfilesSupplier = builder.descendantProfilesSupplier;
ListMultimap<String, RuleParamDto> paramsByRuleId = builder.ruleParams.stream().collect(index(RuleParamDto::getRuleUuid));
for (RuleDto rule : builder.rules) {
RuleWrapper wrapper = new RuleWrapper(rule, paramsByRuleId.get(rule.getUuid()));
rulesByUuid.put(rule.getUuid(), wrapper);
}
this.baseRulesProfile = builder.baseRulesProfile;
register(builder.profiles);
register(builder.activeRules, builder.activeRuleParams);
}
private void register(Collection<QProfileDto> profiles) {
for (QProfileDto profile : profiles) {
profilesByUuid.put(profile.getKee(), profile);
if (profile.getParentKee() != null) {
profilesByParentUuid.put(profile.getParentKee(), profile);
}
}
}
private void register(Collection<ActiveRuleDto> activeRules, Collection<ActiveRuleParamDto> activeRuleParams) {
ListMultimap<String, ActiveRuleParamDto> paramsByActiveRuleUuid = activeRuleParams.stream().collect(index(ActiveRuleParamDto::getActiveRuleUuid));
for (ActiveRuleDto activeRule : activeRules) {
ActiveRuleWrapper wrapper = new ActiveRuleWrapper(activeRule, paramsByActiveRuleUuid.get(activeRule.getUuid()));
this.activeRulesByKey.put(activeRule.getKey(), wrapper);
}
}
long getDate() {
return date;
}
/**
* The rule currently selected.
*/
public RuleWrapper getRule() {
checkState(currentRule != null, "Rule has not been set yet");
return currentRule;
}
@CheckForNull
String getRequestedParamValue(RuleActivation request, String key) {
if (currentRule.rule.isCustomRule()) {
return null;
}
return request.getParameter(key);
}
boolean hasRequestedParamValue(RuleActivation request, String key) {
return request.hasParameter(key);
}
/**
* The rules profile being selected.
*/
RulesProfileDto getRulesProfile() {
checkState(currentRulesProfile != null, "Rule profile has not been set yet");
return currentRulesProfile;
}
/**
* The active rule related to the selected profile and rule.
* @return null if the selected rule is not activated on the selected profile.
* @see #getRulesProfile()
* @see #getRule()
*/
@CheckForNull
ActiveRuleWrapper getActiveRule() {
return currentActiveRule;
}
/**
* The active rule related to the rule and the parent of the selected profile.
* @return null if the selected rule is not activated on the parent profile.
* @see #getRule()
*/
@CheckForNull
ActiveRuleWrapper getParentActiveRule() {
return currentParentActiveRule;
}
/**
* Whether the profile cursor is on the base profile or not.
*/
boolean isCascading() {
return currentRulesProfile != null && !currentRulesProfile.getUuid().equals(baseRulesProfile.getUuid());
}
/**
* The profiles being selected. Can be zero or many if {@link #getRulesProfile()} is built-in.
* Else the collection always contains a single profile.
*/
Collection<QProfileDto> getProfiles() {
checkState(currentProfiles != null, "Profiles have not been set yet");
return currentProfiles;
}
/**
* The children of {@link #getProfiles()}
*/
Collection<QProfileDto> getChildProfiles() {
loadDescendants();
return getProfiles().stream()
.flatMap(p -> profilesByParentUuid.get(p.getKee()).stream())
.toList();
}
private void loadDescendants() {
if (descendantsLoaded) {
return;
}
Collection<QProfileDto> baseProfiles = profilesByUuid.values().stream()
.filter(p -> p.getRulesProfileUuid().equals(baseRulesProfile.getUuid()))
.toList();
DescendantProfilesSupplier.Result result = descendantProfilesSupplier.get(baseProfiles, rulesByUuid.keySet());
register(result.profiles());
register(result.activeRules(), result.activeRuleParams());
descendantsLoaded = true;
}
/**
* Move the cursor to the given rule and back to the base profile.
*/
public void reset(String ruleUuid) {
doSwitch(this.baseRulesProfile, ruleUuid);
}
/**
* Moves cursor to a child profile
*/
void selectChild(QProfileDto to) {
checkState(!to.isBuiltIn());
QProfileDto qp = requireNonNull(this.profilesByUuid.get(to.getKee()), () -> "No profile with uuid " + to.getKee());
RulesProfileDto ruleProfile = RulesProfileDto.from(qp);
doSwitch(ruleProfile, getRule().get().getUuid());
}
private void doSwitch(RulesProfileDto ruleProfile, String ruleUuid) {
this.currentRule = rulesByUuid.get(ruleUuid);
checkRequest(this.currentRule != null, "Rule with UUID %s not found", ruleUuid);
RuleKey ruleKey = currentRule.get().getKey();
this.currentRulesProfile = ruleProfile;
this.currentProfiles = profilesByUuid.values().stream()
.filter(p -> p.getRulesProfileUuid().equals(ruleProfile.getUuid()))
.toList();
this.currentActiveRule = this.activeRulesByKey.get(ActiveRuleKey.of(ruleProfile, ruleKey));
this.currentParentActiveRule = this.currentProfiles.stream()
.map(QProfileDto::getParentKee)
.filter(Objects::nonNull)
.map(profilesByUuid::get)
.filter(Objects::nonNull)
.findFirst()
.map(profile -> activeRulesByKey.get(ActiveRuleKey.of(profile, ruleKey)))
.orElse(null);
}
static final class Builder {
private long date = System.currentTimeMillis();
private RulesProfileDto baseRulesProfile;
private Collection<RuleDto> rules;
private Collection<RuleParamDto> ruleParams;
private Collection<QProfileDto> profiles;
private Collection<ActiveRuleDto> activeRules;
private Collection<ActiveRuleParamDto> activeRuleParams;
private DescendantProfilesSupplier descendantProfilesSupplier;
Builder setDate(long l) {
this.date = l;
return this;
}
Builder setBaseProfile(RulesProfileDto p) {
this.baseRulesProfile = p;
return this;
}
Builder setRules(Collection<RuleDto> rules) {
this.rules = rules;
return this;
}
Builder setRuleParams(Collection<RuleParamDto> ruleParams) {
this.ruleParams = ruleParams;
return this;
}
/**
* All the profiles involved in the activation workflow, including the
* parent profile, even if it's not updated.
*/
Builder setProfiles(Collection<QProfileDto> profiles) {
this.profiles = profiles;
return this;
}
Builder setActiveRules(Collection<ActiveRuleDto> activeRules) {
this.activeRules = activeRules;
return this;
}
Builder setActiveRuleParams(Collection<ActiveRuleParamDto> activeRuleParams) {
this.activeRuleParams = activeRuleParams;
return this;
}
Builder setDescendantProfilesSupplier(DescendantProfilesSupplier d) {
this.descendantProfilesSupplier = d;
return this;
}
RuleActivationContext build() {
checkArgument(date > 0, "date is not set");
requireNonNull(baseRulesProfile, "baseRulesProfile is null");
requireNonNull(rules, "rules is null");
requireNonNull(ruleParams, "ruleParams is null");
requireNonNull(profiles, "profiles is null");
requireNonNull(activeRules, "activeRules is null");
requireNonNull(activeRuleParams, "activeRuleParams is null");
requireNonNull(descendantProfilesSupplier, "descendantProfilesSupplier is null");
return new RuleActivationContext(this);
}
}
public static final class RuleWrapper {
private final RuleDto rule;
private final Map<String, RuleParamDto> paramsByKey;
private RuleWrapper(RuleDto rule, Collection<RuleParamDto> params) {
this.rule = rule;
this.paramsByKey = params.stream().collect(Collectors.toMap(RuleParamDto::getName, Function.identity()));
}
public RuleDto get() {
return rule;
}
Collection<RuleParamDto> getParams() {
return paramsByKey.values();
}
@CheckForNull
RuleParamDto getParam(String key) {
return paramsByKey.get(key);
}
@CheckForNull
String getParamDefaultValue(String key) {
RuleParamDto param = getParam(key);
return param != null ? param.getDefaultValue() : null;
}
}
static final class ActiveRuleWrapper {
private final ActiveRuleDto activeRule;
private final Map<String, ActiveRuleParamDto> paramsByKey;
private ActiveRuleWrapper(ActiveRuleDto activeRule, Collection<ActiveRuleParamDto> params) {
this.activeRule = activeRule;
this.paramsByKey = params.stream().collect(Collectors.toMap(ActiveRuleParamDto::getKey, Function.identity()));
}
ActiveRuleDto get() {
return activeRule;
}
Collection<ActiveRuleParamDto> getParams() {
return paramsByKey.values();
}
@CheckForNull
ActiveRuleParamDto getParam(String key) {
return paramsByKey.get(key);
}
@CheckForNull
String getParamValue(String key) {
ActiveRuleParamDto param = paramsByKey.get(key);
return param != null ? param.getValue() : null;
}
}
}
| 12,511 | 33.092643 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/RuleActivator.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.builtin;
import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDao;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgQProfileDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext.ActiveRuleWrapper;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext.RuleWrapper;
import org.sonar.server.user.UserSession;
import org.sonar.server.util.TypeValidations;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
/**
* Activation and deactivation of rules in Quality profiles
*/
@ServerSide
public class RuleActivator {
private final System2 system2;
private final DbClient db;
private final TypeValidations typeValidations;
private final UserSession userSession;
public RuleActivator(System2 system2, DbClient db, TypeValidations typeValidations, UserSession userSession) {
this.system2 = system2;
this.db = db;
this.typeValidations = typeValidations;
this.userSession = userSession;
}
public List<ActiveRuleChange> activate(DbSession dbSession, Collection<RuleActivation> activations, RuleActivationContext context) {
return activations.stream().map(a -> activate(dbSession, a, context))
.flatMap(List::stream)
.toList();
}
public List<ActiveRuleChange> activate(DbSession dbSession, RuleActivation activation, RuleActivationContext context) {
context.reset(activation.getRuleUuid());
return doActivate(dbSession, activation, context);
}
private List<ActiveRuleChange> doActivate(DbSession dbSession, RuleActivation activation, RuleActivationContext context) {
RuleDto rule = context.getRule().get();
checkRequest(RuleStatus.REMOVED != rule.getStatus(), "Rule was removed: %s", rule.getKey());
checkRequest(!rule.isTemplate(), "Rule template can't be activated on a Quality profile: %s", rule.getKey());
checkRequest(context.getRulesProfile().getLanguage().equals(rule.getLanguage()),
"%s rule %s cannot be activated on %s profile %s", rule.getLanguage(), rule.getKey(), context.getRulesProfile().getLanguage(), context.getRulesProfile().getName());
List<ActiveRuleChange> changes = new ArrayList<>();
ActiveRuleChange change;
boolean stopCascading = false;
ActiveRuleWrapper activeRule = context.getActiveRule();
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(context.getRulesProfile(), rule.getKey());
if (activeRule == null) {
if (activation.isReset()) {
// ignore reset when rule is not activated
return changes;
}
change = handleNewRuleActivation(activation, context, rule, activeRuleKey);
} else {
// already activated
if (context.isCascading() && activeRule.get().doesOverride()) {
// propagating to descendants, but child profile already overrides rule -> stop propagation
return changes;
}
change = new ActiveRuleChange(ActiveRuleChange.Type.UPDATED, activeRuleKey, rule);
stopCascading = handleUpdatedRuleActivation(activation, context, change, stopCascading, activeRule);
if (isSame(change, activeRule)) {
change = null;
stopCascading = true;
}
}
if (change != null) {
changes.add(change);
persist(change, context, dbSession);
}
if (!changes.isEmpty()) {
updateProfileDates(dbSession, context);
}
if (!stopCascading) {
changes.addAll(propagateActivationToDescendants(dbSession, activation, context));
}
return changes;
}
private boolean handleUpdatedRuleActivation(RuleActivation activation, RuleActivationContext context, ActiveRuleChange change,
boolean stopCascading, ActiveRuleWrapper activeRule) {
if (context.isCascading() && activeRule.get().getInheritance() == null) {
// activate on child, then on parent -> mark child as overriding parent
change.setInheritance(ActiveRuleInheritance.OVERRIDES);
change.setSeverity(activeRule.get().getSeverityString());
for (ActiveRuleParamDto activeParam : activeRule.getParams()) {
change.setParameter(activeParam.getKey(), activeParam.getValue());
}
stopCascading = true;
} else {
applySeverityAndParamToChange(activation, context, change);
if (!context.isCascading() && context.getParentActiveRule() != null) {
// override rule which is already declared on parents
change.setInheritance(isSameAsParent(change, context) ? ActiveRuleInheritance.INHERITED : ActiveRuleInheritance.OVERRIDES);
}
}
return stopCascading;
}
private ActiveRuleChange handleNewRuleActivation(RuleActivation activation, RuleActivationContext context, RuleDto rule, ActiveRuleKey activeRuleKey) {
ActiveRuleChange change = new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, activeRuleKey, rule);
applySeverityAndParamToChange(activation, context, change);
if (context.isCascading() || isSameAsParent(change, context)) {
change.setInheritance(ActiveRuleInheritance.INHERITED);
}
return change;
}
private void updateProfileDates(DbSession dbSession, RuleActivationContext context) {
RulesProfileDto ruleProfile = context.getRulesProfile();
ruleProfile.setRulesUpdatedAtAsDate(new Date(context.getDate()));
db.qualityProfileDao().update(dbSession, ruleProfile);
if (userSession.isLoggedIn()) {
context.getProfiles().forEach(p -> db.qualityProfileDao().update(dbSession, OrgQProfileDto.from(p).setUserUpdatedAt(context.getDate())));
}
}
/**
* Update severity and params
*/
private void applySeverityAndParamToChange(RuleActivation request, RuleActivationContext context, ActiveRuleChange change) {
RuleWrapper rule = context.getRule();
ActiveRuleWrapper activeRule = context.getActiveRule();
ActiveRuleWrapper parentActiveRule = context.getParentActiveRule();
if (request.isReset()) {
applySeverityAndParamsWhenResetRequested(change, rule, parentActiveRule);
} else if (context.getRulesProfile().isBuiltIn()) {
applySeverityAndParamsWhenBuiltInProfile(request, context, change, rule);
} else {
applySeverityAndParamsWhenNonBuiltInProfile(request, context, change, rule, activeRule, parentActiveRule);
}
}
private void applySeverityAndParamsWhenResetRequested(ActiveRuleChange change, RuleWrapper rule, @Nullable ActiveRuleWrapper parentActiveRule) {
String severity = firstNonNull(
parentActiveRule != null ? parentActiveRule.get().getSeverityString() : null,
rule.get().getSeverityString());
change.setSeverity(severity);
for (RuleParamDto ruleParamDto : rule.getParams()) {
String paramKey = ruleParamDto.getName();
// load params from parent profile, else from default values
String paramValue = firstNonNull(
parentActiveRule != null ? parentActiveRule.getParamValue(paramKey) : null,
rule.getParamDefaultValue(paramKey));
change.setParameter(paramKey, validateParam(ruleParamDto, paramValue));
}
}
private void applySeverityAndParamsWhenBuiltInProfile(RuleActivation request, RuleActivationContext context, ActiveRuleChange change,
RuleWrapper rule) {
// for builtin quality profiles, the severity from profile, when null use the default severity of the rule
String severity = firstNonNull(request.getSeverity(), rule.get().getSeverityString());
change.setSeverity(severity);
for (RuleParamDto ruleParamDto : rule.getParams()) {
String paramKey = ruleParamDto.getName();
// use the value defined in the profile definition, else the rule default value
String paramValue = firstNonNull(
context.getRequestedParamValue(request, paramKey),
rule.getParamDefaultValue(paramKey));
change.setParameter(paramKey, validateParam(ruleParamDto, paramValue));
}
}
/**
* 1. apply requested severity and param
* 2. if rule activated and overridden - apply user value
* 3. apply parent value
* 4. apply defaults
*/
private void applySeverityAndParamsWhenNonBuiltInProfile(RuleActivation request, RuleActivationContext context, ActiveRuleChange change,
RuleWrapper rule, @Nullable ActiveRuleWrapper activeRule, @Nullable ActiveRuleWrapper parentActiveRule) {
String severity = getSeverityForNonBuiltInProfile(request, rule, activeRule, parentActiveRule);
change.setSeverity(severity);
for (RuleParamDto ruleParamDto : rule.getParams()) {
String paramKey = ruleParamDto.getName();
String parentValue = parentActiveRule != null ? parentActiveRule.getParamValue(paramKey) : null;
String paramValue;
if (context.hasRequestedParamValue(request, paramKey)) {
// If the request contains the parameter then we're using either value from request, or parent value, or default value
paramValue = firstNonNull(
context.getRequestedParamValue(request, paramKey),
parentValue,
rule.getParamDefaultValue(paramKey));
} else if (activeRule != null) {
// If the request doesn't contain the parameter, then we're using either user value from db, or parent value if rule inherited, or default
// value
paramValue = firstNonNull(
activeRule.get().doesOverride() ? activeRule.getParamValue(paramKey) : null,
parentValue == null ? activeRule.getParamValue(paramKey) : parentValue,
rule.getParamDefaultValue(paramKey));
} else {
paramValue = firstNonNull(
parentValue,
rule.getParamDefaultValue(paramKey));
}
change.setParameter(paramKey, validateParam(ruleParamDto, paramValue));
}
}
private static String getSeverityForNonBuiltInProfile(RuleActivation request, RuleWrapper rule, @Nullable ActiveRuleWrapper activeRule,
@Nullable ActiveRuleWrapper parentActiveRule) {
String severity;
if (activeRule != null) {
ActiveRuleDto activeRuleDto = activeRule.get();
// load severity from request, else keep existing one (if overridden), else from parent if rule inherited, else from default
severity = firstNonNull(
request.getSeverity(),
activeRuleDto.doesOverride() ? activeRuleDto.getSeverityString() : null,
parentActiveRule != null ? parentActiveRule.get().getSeverityString() : activeRuleDto.getSeverityString(),
rule.get().getSeverityString());
} else {
// load severity from request, else from parent, else from default
severity = firstNonNull(
request.getSeverity(),
parentActiveRule != null ? parentActiveRule.get().getSeverityString() : null,
rule.get().getSeverityString());
}
return severity;
}
private List<ActiveRuleChange> propagateActivationToDescendants(DbSession dbSession, RuleActivation activation, RuleActivationContext context) {
List<ActiveRuleChange> changes = new ArrayList<>();
// get all inherited profiles
context.getChildProfiles().forEach(child -> {
context.selectChild(child);
changes.addAll(doActivate(dbSession, activation, context));
});
return changes;
}
private void persist(ActiveRuleChange change, RuleActivationContext context, DbSession dbSession) {
ActiveRuleDto activeRule = null;
if (change.getType() == ActiveRuleChange.Type.ACTIVATED) {
activeRule = doInsert(change, context, dbSession);
} else if (change.getType() == ActiveRuleChange.Type.DEACTIVATED) {
ActiveRuleDao dao = db.activeRuleDao();
activeRule = dao.delete(dbSession, change.getKey()).orElse(null);
} else if (change.getType() == ActiveRuleChange.Type.UPDATED) {
activeRule = doUpdate(change, context, dbSession);
}
change.setActiveRule(activeRule);
db.qProfileChangeDao().insert(dbSession, change.toDto(userSession.getUuid()));
}
private ActiveRuleDto doInsert(ActiveRuleChange change, RuleActivationContext context, DbSession dbSession) {
ActiveRuleDao dao = db.activeRuleDao();
RuleWrapper rule = context.getRule();
ActiveRuleDto activeRule = new ActiveRuleDto();
activeRule.setProfileUuid(context.getRulesProfile().getUuid());
activeRule.setRuleUuid(rule.get().getUuid());
activeRule.setKey(ActiveRuleKey.of(context.getRulesProfile(), rule.get().getKey()));
String severity = change.getSeverity();
if (severity != null) {
activeRule.setSeverity(severity);
}
ActiveRuleInheritance inheritance = change.getInheritance();
if (inheritance != null) {
activeRule.setInheritance(inheritance.name());
}
activeRule.setUpdatedAt(system2.now());
activeRule.setCreatedAt(system2.now());
dao.insert(dbSession, activeRule);
for (Map.Entry<String, String> param : change.getParameters().entrySet()) {
if (param.getValue() != null) {
ActiveRuleParamDto paramDto = ActiveRuleParamDto.createFor(rule.getParam(param.getKey()));
paramDto.setValue(param.getValue());
dao.insertParam(dbSession, activeRule, paramDto);
}
}
return activeRule;
}
private ActiveRuleDto doUpdate(ActiveRuleChange change, RuleActivationContext context, DbSession dbSession) {
ActiveRuleWrapper activeRule = context.getActiveRule();
if (activeRule == null) {
return null;
}
ActiveRuleDao dao = db.activeRuleDao();
String severity = change.getSeverity();
if (severity != null) {
activeRule.get().setSeverity(severity);
}
ActiveRuleInheritance inheritance = change.getInheritance();
if (inheritance != null) {
activeRule.get().setInheritance(inheritance.name());
}
activeRule.get().setUpdatedAt(system2.now());
dao.update(dbSession, activeRule.get());
for (Map.Entry<String, String> param : change.getParameters().entrySet()) {
ActiveRuleParamDto activeRuleParamDto = activeRule.getParam(param.getKey());
if (activeRuleParamDto == null) {
// did not exist
if (param.getValue() != null) {
activeRuleParamDto = ActiveRuleParamDto.createFor(context.getRule().getParam(param.getKey()));
activeRuleParamDto.setValue(param.getValue());
dao.insertParam(dbSession, activeRule.get(), activeRuleParamDto);
}
} else {
if (param.getValue() != null) {
activeRuleParamDto.setValue(param.getValue());
dao.updateParam(dbSession, activeRuleParamDto);
} else {
dao.deleteParam(dbSession, activeRuleParamDto);
}
}
}
return activeRule.get();
}
public List<ActiveRuleChange> deactivate(DbSession dbSession, RuleActivationContext context, String ruleUuid, boolean force) {
context.reset(ruleUuid);
return doDeactivate(dbSession, context, force);
}
private List<ActiveRuleChange> doDeactivate(DbSession dbSession, RuleActivationContext context, boolean force) {
List<ActiveRuleChange> changes = new ArrayList<>();
ActiveRuleWrapper activeRule = context.getActiveRule();
if (activeRule == null) {
return changes;
}
ActiveRuleChange change;
checkRequest(force || context.isCascading() || activeRule.get().getInheritance() == null, "Cannot deactivate inherited rule '%s'", context.getRule().get().getKey());
change = new ActiveRuleChange(ActiveRuleChange.Type.DEACTIVATED, activeRule.get(), context.getRule().get());
changes.add(change);
persist(change, context, dbSession);
// get all inherited profiles (they are not built-in by design)
context.getChildProfiles().forEach(child -> {
context.selectChild(child);
changes.addAll(doDeactivate(dbSession, context, force));
});
if (!changes.isEmpty()) {
updateProfileDates(dbSession, context);
}
return changes;
}
@CheckForNull
private String validateParam(RuleParamDto ruleParam, @Nullable String value) {
if (value != null) {
RuleParamType ruleParamType = RuleParamType.parse(ruleParam.getType());
if (ruleParamType.multiple()) {
List<String> values = Splitter.on(",").splitToList(value);
typeValidations.validate(values, ruleParamType.type(), ruleParamType.values());
} else {
typeValidations.validate(value, ruleParamType.type(), ruleParamType.values());
}
}
return value;
}
public RuleActivationContext createContextForBuiltInProfile(DbSession dbSession, RulesProfileDto builtInProfile, Collection<String> ruleUuids) {
checkArgument(builtInProfile.isBuiltIn(), "Rules profile with UUID %s is not built-in", builtInProfile.getUuid());
RuleActivationContext.Builder builder = new RuleActivationContext.Builder();
builder.setDescendantProfilesSupplier(createDescendantProfilesSupplier(dbSession));
// load rules
completeWithRules(dbSession, builder, ruleUuids);
// load org profiles. Their parents are null by nature.
List<QProfileDto> profiles = db.qualityProfileDao().selectQProfilesByRuleProfile(dbSession, builtInProfile);
builder.setProfiles(profiles);
builder.setBaseProfile(builtInProfile);
// load active rules
Collection<String> ruleProfileUuids = Stream
.concat(Stream.of(builtInProfile.getUuid()), profiles.stream().map(QProfileDto::getRulesProfileUuid))
.collect(Collectors.toSet());
completeWithActiveRules(dbSession, builder, ruleUuids, ruleProfileUuids);
return builder.build();
}
public RuleActivationContext createContextForUserProfile(DbSession dbSession, QProfileDto profile, Collection<String> ruleUuids) {
checkArgument(!profile.isBuiltIn(), "Profile with UUID %s is built-in", profile.getKee());
RuleActivationContext.Builder builder = new RuleActivationContext.Builder();
builder.setDescendantProfilesSupplier(createDescendantProfilesSupplier(dbSession));
// load rules
completeWithRules(dbSession, builder, ruleUuids);
// load profiles
List<QProfileDto> profiles = new ArrayList<>();
profiles.add(profile);
if (profile.getParentKee() != null) {
profiles.add(db.qualityProfileDao().selectByUuid(dbSession, profile.getParentKee()));
}
builder.setProfiles(profiles);
builder.setBaseProfile(RulesProfileDto.from(profile));
// load active rules
Collection<String> ruleProfileUuids = profiles.stream()
.map(QProfileDto::getRulesProfileUuid)
.collect(Collectors.toSet());
completeWithActiveRules(dbSession, builder, ruleUuids, ruleProfileUuids);
return builder.build();
}
DescendantProfilesSupplier createDescendantProfilesSupplier(DbSession dbSession) {
return (parents, ruleUuids) -> {
Collection<QProfileDto> profiles = db.qualityProfileDao().selectDescendants(dbSession, parents);
Set<String> ruleProfileUuids = profiles.stream()
.map(QProfileDto::getRulesProfileUuid)
.collect(Collectors.toSet());
Collection<ActiveRuleDto> activeRules = db.activeRuleDao().selectByRulesAndRuleProfileUuids(dbSession, ruleUuids, ruleProfileUuids);
List<String> activeRuleUuids = activeRules.stream().map(ActiveRuleDto::getUuid).toList();
List<ActiveRuleParamDto> activeRuleParams = db.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, activeRuleUuids);
return new DescendantProfilesSupplier.Result(profiles, activeRules, activeRuleParams);
};
}
private void completeWithRules(DbSession dbSession, RuleActivationContext.Builder builder, Collection<String> ruleUuids) {
List<RuleDto> rules = db.ruleDao().selectByUuids(dbSession, ruleUuids);
builder.setRules(rules);
builder.setRuleParams(db.ruleDao().selectRuleParamsByRuleUuids(dbSession, ruleUuids));
}
private void completeWithActiveRules(DbSession dbSession, RuleActivationContext.Builder builder, Collection<String> ruleUuids, Collection<String> ruleProfileUuids) {
Collection<ActiveRuleDto> activeRules = db.activeRuleDao().selectByRulesAndRuleProfileUuids(dbSession, ruleUuids, ruleProfileUuids);
builder.setActiveRules(activeRules);
List<String> activeRuleUuids = activeRules.stream().map(ActiveRuleDto::getUuid).toList();
builder.setActiveRuleParams(db.activeRuleDao().selectParamsByActiveRuleUuids(dbSession, activeRuleUuids));
}
private static boolean isSame(ActiveRuleChange change, ActiveRuleWrapper activeRule) {
ActiveRuleInheritance inheritance = change.getInheritance();
if (inheritance != null && !inheritance.name().equals(activeRule.get().getInheritance())) {
return false;
}
String severity = change.getSeverity();
if (severity != null && !severity.equals(activeRule.get().getSeverityString())) {
return false;
}
for (Map.Entry<String, String> changeParam : change.getParameters().entrySet()) {
String activeParamValue = activeRule.getParamValue(changeParam.getKey());
if (changeParam.getValue() == null && activeParamValue != null) {
return false;
}
if (changeParam.getValue() != null && (activeParamValue == null || !StringUtils.equals(changeParam.getValue(), activeParamValue))) {
return false;
}
}
return true;
}
/**
* True if trying to override an inherited rule but with exactly the same values
*/
private static boolean isSameAsParent(ActiveRuleChange change, RuleActivationContext context) {
ActiveRuleWrapper parentActiveRule = context.getParentActiveRule();
if (parentActiveRule == null) {
return false;
}
if (!StringUtils.equals(change.getSeverity(), parentActiveRule.get().getSeverityString())) {
return false;
}
for (Map.Entry<String, String> entry : change.getParameters().entrySet()) {
if (entry.getValue() != null && !entry.getValue().equals(parentActiveRule.getParamValue(entry.getKey()))) {
return false;
}
}
return true;
}
@CheckForNull
private static String firstNonNull(String... strings) {
for (String s : strings) {
if (s != null) {
return s;
}
}
return null;
}
}
| 23,913 | 42.638686 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/builtin/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.qualityprofile.builtin;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 38.24 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRuleAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Map;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
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.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ACTIVATE_RULE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PARAMS;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RESET;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RULE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_SEVERITY;
public class ActivateRuleAction implements QProfileWsAction {
private final DbClient dbClient;
private final QProfileRules ruleActivator;
private final UserSession userSession;
private final QProfileWsSupport wsSupport;
public ActivateRuleAction(DbClient dbClient, QProfileRules ruleActivator, UserSession userSession, QProfileWsSupport wsSupport) {
this.dbClient = dbClient;
this.ruleActivator = ruleActivator;
this.userSession = userSession;
this.wsSupport = wsSupport;
}
public void define(WebService.NewController controller) {
WebService.NewAction activate = controller
.createAction(ACTION_ACTIVATE_RULE)
.setDescription("Activate a rule on a Quality Profile.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("4.4");
activate.createParam(PARAM_KEY)
.setDescription("Quality Profile key. Can be obtained through <code>api/qualityprofiles/search</code>")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
activate.createParam(PARAM_RULE)
.setDescription("Rule key")
.setRequired(true)
.setExampleValue("java:AvoidCycles");
activate.createParam(PARAM_SEVERITY)
.setDescription(format("Severity. Ignored if parameter %s is true.", PARAM_RESET))
.setPossibleValues(Severity.ALL);
activate.createParam(PARAM_PARAMS)
.setDescription(format("Parameters as semi-colon list of <code>key=value</code>. Ignored if parameter %s is true.", PARAM_RESET))
.setExampleValue("params=key1=v1;key2=v2");
activate.createParam(PARAM_RESET)
.setDescription("Reset severity and parameters of activated rule. Set the values defined on parent profile or from rule default values.")
.setBooleanPossibleValues();
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
String profileKey = request.mandatoryParam(PARAM_KEY);
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(profileKey));
wsSupport.checkCanEdit(dbSession, profile);
RuleActivation activation = readActivation(dbSession, request);
ruleActivator.activateAndCommit(dbSession, profile, singletonList(activation));
}
response.noContent();
}
private RuleActivation readActivation(DbSession dbSession, Request request) {
RuleKey ruleKey = RuleKey.parse(request.mandatoryParam(PARAM_RULE));
RuleDto ruleDto = wsSupport.getRule(dbSession, ruleKey);
boolean reset = Boolean.TRUE.equals(request.paramAsBoolean(PARAM_RESET));
if (reset) {
return RuleActivation.createReset(ruleDto.getUuid());
}
String severity = request.param(PARAM_SEVERITY);
Map<String, String> params = null;
String paramsAsString = request.param(PARAM_PARAMS);
if (paramsAsString != null) {
params = KeyValueFormat.parse(paramsAsString);
}
return RuleActivation.create(ruleDto.getUuid(), severity, params);
}
}
| 5,417 | 41.328125 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRulesAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.user.UserSession;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_03;
import static org.sonar.server.qualityprofile.ws.BulkChangeWsResponse.writeResponse;
import static org.sonar.server.qualityprofile.ws.QProfileReference.fromKey;
import static org.sonar.server.rule.ws.RuleWsSupport.defineGenericRuleSearchParameters;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ACTIVATE_RULES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_SEVERITY;
public class ActivateRulesAction implements QProfileWsAction {
private final RuleQueryFactory ruleQueryFactory;
private final UserSession userSession;
private final QProfileRules qProfileRules;
private final DbClient dbClient;
private final QProfileWsSupport wsSupport;
public ActivateRulesAction(RuleQueryFactory ruleQueryFactory, UserSession userSession, QProfileRules qProfileRules, QProfileWsSupport wsSupport, DbClient dbClient) {
this.ruleQueryFactory = ruleQueryFactory;
this.userSession = userSession;
this.qProfileRules = qProfileRules;
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
public void define(WebService.NewController controller) {
WebService.NewAction activate = controller
.createAction(ACTION_ACTIVATE_RULES)
.setDescription("Bulk-activate rules on one quality profile.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setPost(true)
.setSince("4.4")
.setChangelog(new Change("10.0", "Parameter 'sansTop25' is deprecated"))
.setHandler(this);
defineGenericRuleSearchParameters(activate);
activate.createParam(PARAM_TARGET_KEY)
.setDescription("Quality Profile key on which the rule activation is done. To retrieve a quality profile key please see <code>api/qualityprofiles/search</code>")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_03);
activate.createParam(PARAM_TARGET_SEVERITY)
.setDescription("Severity to set on the activated rules")
.setPossibleValues(Severity.ALL);
}
@Override
public void handle(Request request, Response response) throws Exception {
String qualityProfileKey = request.mandatoryParam(PARAM_TARGET_KEY);
userSession.checkLoggedIn();
BulkChangeResult result;
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, fromKey(qualityProfileKey));
wsSupport.checkCanEdit(dbSession, profile);
wsSupport.checkNotBuiltIn(profile);
RuleQuery ruleQuery = ruleQueryFactory.createRuleQuery(dbSession, request);
ruleQuery.setIncludeExternal(false);
result = qProfileRules.bulkActivateAndCommit(dbSession, profile, ruleQuery, request.param(PARAM_TARGET_SEVERITY));
}
writeResponse(result, response);
}
}
| 4,526 | 42.951456 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/AddGroupAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QProfileEditGroupsDto;
import org.sonar.db.user.GroupDto;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ADD_GROUP;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class AddGroupAction implements QProfileWsAction {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
private final QProfileWsSupport wsSupport;
private final Languages languages;
public AddGroupAction(DbClient dbClient, UuidFactory uuidFactory, QProfileWsSupport wsSupport, Languages languages) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
this.wsSupport = wsSupport;
this.languages = languages;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_ADD_GROUP)
.setDescription("Allow a group to edit a Quality Profile.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setInternal(true)
.setSince("6.6");
action.createParam(PARAM_QUALITY_PROFILE)
.setDescription("Quality Profile name")
.setRequired(true)
.setExampleValue("Recommended quality profile");
action
.createParam(PARAM_LANGUAGE)
.setDescription("Quality profile language")
.setRequired(true)
.setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet()));
action.createParam(PARAM_GROUP)
.setDescription("Group name")
.setRequired(true)
.setExampleValue("sonar-administrators");
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, request.mandatoryParam(PARAM_QUALITY_PROFILE), request.mandatoryParam(PARAM_LANGUAGE));
wsSupport.checkCanEdit(dbSession, profile);
GroupDto user = wsSupport.getGroup(dbSession, request.mandatoryParam(PARAM_GROUP));
addGroup(dbSession, profile, user);
}
response.noContent();
}
private void addGroup(DbSession dbSession, QProfileDto profile, GroupDto group) {
if (dbClient.qProfileEditGroupsDao().exists(dbSession, profile, group)) {
return;
}
dbClient.qProfileEditGroupsDao().insert(dbSession,
new QProfileEditGroupsDto()
.setUuid(uuidFactory.create())
.setGroupUuid(group.getUuid())
.setQProfileUuid(profile.getKee()),
profile.getName(),
group.getName());
dbSession.commit();
}
}
| 4,329 | 37.660714 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/AddProjectAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.resources.Languages;
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.server.ws.WebService.NewAction;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.user.UserSession;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ADD_PROJECT;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PROJECT;
public class AddProjectAction implements QProfileWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final Languages languages;
private final ComponentFinder componentFinder;
private final QProfileWsSupport wsSupport;
private final QualityProfileChangeEventService qualityProfileChangeEventService;
public AddProjectAction(DbClient dbClient, UserSession userSession, Languages languages, ComponentFinder componentFinder,
QProfileWsSupport wsSupport, QualityProfileChangeEventService qualityProfileChangeEventService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.languages = languages;
this.componentFinder = componentFinder;
this.wsSupport = wsSupport;
this.qualityProfileChangeEventService = qualityProfileChangeEventService;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction(ACTION_ADD_PROJECT)
.setSince("5.2")
.setDescription("Associate a project with a quality profile.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Administer right on the specified project</li>" +
"</ul>")
.setPost(true)
.setHandler(this);
QProfileReference.defineParams(action, languages);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = loadProject(dbSession, request);
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromName(request));
checkPermissions(profile, project);
QProfileDto currentProfile = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(dbSession, project, profile.getLanguage());
QProfileDto deactivatedProfile = null;
if (currentProfile == null) {
QProfileDto defaultProfile = dbClient.qualityProfileDao().selectDefaultProfile(dbSession, profile.getLanguage());
if (defaultProfile != null) {
deactivatedProfile = defaultProfile;
}
// project uses the default profile
dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, profile);
dbSession.commit();
} else if (!profile.getKee().equals(currentProfile.getKee())) {
deactivatedProfile = currentProfile;
dbClient.qualityProfileDao().updateProjectProfileAssociation(dbSession, project, profile.getKee(), currentProfile.getKee());
dbSession.commit();
}
qualityProfileChangeEventService.publishRuleActivationToSonarLintClients(project, profile, deactivatedProfile);
}
response.noContent();
}
private ProjectDto loadProject(DbSession dbSession, Request request) {
String projectKey = request.mandatoryParam(PARAM_PROJECT);
return componentFinder.getProjectByKey(dbSession, projectKey);
}
private void checkPermissions(QProfileDto profile, ProjectDto project) {
if (wsSupport.canAdministrate(profile) || userSession.hasEntityPermission(UserRole.ADMIN, project)) {
return;
}
throw insufficientPrivilegesException();
}
}
| 5,261 | 40.433071 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/AddUserAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QProfileEditUsersDto;
import org.sonar.db.user.UserDto;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ADD_USER;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class AddUserAction implements QProfileWsAction {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
private final QProfileWsSupport wsSupport;
private final Languages languages;
public AddUserAction(DbClient dbClient, UuidFactory uuidFactory, QProfileWsSupport wsSupport, Languages languages) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
this.wsSupport = wsSupport;
this.languages = languages;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION_ADD_USER)
.setDescription("Allow a user to edit a Quality Profile.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setInternal(true)
.setSince("6.6");
action.createParam(PARAM_QUALITY_PROFILE)
.setDescription("Quality Profile name")
.setRequired(true)
.setExampleValue("Recommended quality profile");
action
.createParam(PARAM_LANGUAGE)
.setDescription("Quality profile language")
.setRequired(true)
.setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet()));
action.createParam(PARAM_LOGIN)
.setDescription("User login")
.setRequired(true)
.setExampleValue("john.doe");
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, request.mandatoryParam(PARAM_QUALITY_PROFILE), request.mandatoryParam(PARAM_LANGUAGE));
wsSupport.checkCanEdit(dbSession, profile);
UserDto user = wsSupport.getUser(dbSession, request.mandatoryParam(PARAM_LOGIN));
addUser(dbSession, profile, user);
}
response.noContent();
}
private void addUser(DbSession dbSession, QProfileDto profile, UserDto user) {
if (dbClient.qProfileEditUsersDao().exists(dbSession, profile, user)) {
return;
}
dbClient.qProfileEditUsersDao().insert(dbSession,
new QProfileEditUsersDto()
.setUuid(uuidFactory.create())
.setUserUuid(user.getUuid())
.setQProfileUuid(profile.getKee()),
profile.getName(), user.getLogin());
dbSession.commit();
}
}
| 4,294 | 37.00885 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/BackupAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.io.OutputStreamWriter;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.Response.Stream;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonarqube.ws.MediaTypes;
import static java.nio.charset.StandardCharsets.UTF_8;
public class BackupAction implements QProfileWsAction {
private final DbClient dbClient;
private final QProfileBackuper backuper;
private final QProfileWsSupport wsSupport;
private final Languages languages;
public BackupAction(DbClient dbClient, QProfileBackuper backuper, QProfileWsSupport wsSupport, Languages languages) {
this.dbClient = dbClient;
this.backuper = backuper;
this.wsSupport = wsSupport;
this.languages = languages;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction("backup")
.setSince("5.2")
.setDescription("Backup a quality profile in XML form. The exported profile can be restored through api/qualityprofiles/restore.")
.setResponseExample(getClass().getResource("backup-example.xml"))
.setHandler(this);
QProfileReference.defineParams(action, languages);
}
@Override
public void handle(Request request, Response response) throws Exception {
// Allowed to users without admin permission: http://jira.sonarsource.com/browse/SONAR-2039
Stream stream = response.stream();
stream.setMediaType(MediaTypes.XML);
QProfileDto profile = loadQProfile(request);
try (OutputStreamWriter writer = new OutputStreamWriter(stream.output(), UTF_8);
DbSession dbSession = dbClient.openSession(false)) {
response.setHeader("Content-Disposition", String.format("attachment; filename=%s.xml", profile.getKee()));
backuper.backup(dbSession, profile, writer);
}
}
private QProfileDto loadQProfile(Request request) {
try (DbSession dbSession = dbClient.openSession(false)) {
return wsSupport.getProfile(dbSession, QProfileReference.fromName(request));
}
}
}
| 3,206 | 38.592593 | 136 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/BulkChangeWsResponse.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.server.ws.Response;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.ws.WebServiceEngine;
class BulkChangeWsResponse {
private BulkChangeWsResponse() {
// use static methods
}
static void writeResponse(BulkChangeResult result, Response response) {
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
json.prop("succeeded", result.countSucceeded());
json.prop("failed", result.countFailed());
WebServiceEngine.writeErrors(json, result.getErrors());
json.endObject();
}
}
}
| 1,529 | 34.581395 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ChangeParentAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QProfileTree;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
public class ChangeParentAction implements QProfileWsAction {
private final DbClient dbClient;
private final QProfileTree ruleActivator;
private final Languages languages;
private final QProfileWsSupport wsSupport;
private final UserSession userSession;
public ChangeParentAction(DbClient dbClient, QProfileTree ruleActivator,
Languages languages, QProfileWsSupport wsSupport, UserSession userSession) {
this.dbClient = dbClient;
this.ruleActivator = ruleActivator;
this.languages = languages;
this.wsSupport = wsSupport;
this.userSession = userSession;
}
@Override
public void define(NewController context) {
NewAction inheritance = context.createAction("change_parent")
.setSince("5.2")
.setPost(true)
.setDescription("Change a quality profile's parent.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setHandler(this);
QProfileReference.defineParams(inheritance, languages);
inheritance.createParam(QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE)
.setDescription("New parent profile name. <br> " +
"If no profile is provided, the inheritance link with current parent profile (if any) is broken, which deactivates all rules " +
"which come from the parent and are not overridden.")
.setExampleValue("Sonar way");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
QProfileReference reference = QProfileReference.fromName(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, reference);
wsSupport.checkCanEdit(dbSession, profile);
String parentName = request.param(QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE);
if (isEmpty(parentName)) {
ruleActivator.removeParentAndCommit(dbSession, profile);
} else {
String parentLanguage = request.mandatoryParam(PARAM_LANGUAGE);
QProfileReference parentRef = QProfileReference.fromName(parentLanguage, parentName);
QProfileDto parent = wsSupport.getProfile(dbSession, parentRef);
ruleActivator.setParentAndCommit(dbSession, profile, parent);
}
response.noContent();
}
}
}
| 4,012 | 39.535354 | 136 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ChangelogAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileChangeQuery;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_SINCE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TO;
public class ChangelogAction implements QProfileWsAction {
private final QProfileWsSupport wsSupport;
private final Languages languages;
private DbClient dbClient;
public ChangelogAction(QProfileWsSupport wsSupport, Languages languages, DbClient dbClient) {
this.wsSupport = wsSupport;
this.languages = languages;
this.dbClient = dbClient;
}
@Override
public void define(NewController context) {
NewAction wsAction = context.createAction("changelog")
.setSince("5.2")
.setDescription("Get the history of changes on a quality profile: rule activation/deactivation, change in parameters/severity. " +
"Events are ordered by date in descending order (most recent first).")
.setChangelog(
new org.sonar.api.server.ws.Change("9.8", "response fields 'total', 's', 'ps' have been deprecated, please use 'paging' object instead"),
new org.sonar.api.server.ws.Change("9.8", "The field 'paging' has been added to the response"))
.setHandler(this)
.setResponseExample(getClass().getResource("changelog-example.json"));
QProfileReference.defineParams(wsAction, languages);
wsAction.addPagingParams(50, MAX_PAGE_SIZE);
wsAction.createParam(PARAM_SINCE)
.setDescription("Start date for the changelog (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided.")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
wsAction.createParam(PARAM_TO)
.setDescription("End date for the changelog (exclusive, strictly before). <br>" +
"Either a date (server timezone) or datetime can be provided.")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
}
@Override
public void handle(Request request, Response response) throws Exception {
QProfileReference reference = QProfileReference.fromName(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, reference);
QProfileChangeQuery query = new QProfileChangeQuery(profile.getKee());
Date since = parseStartingDateOrDateTime(request.param(PARAM_SINCE));
if (since != null) {
query.setFromIncluded(since.getTime());
}
Date to = parseEndingDateOrDateTime(request.param(PARAM_TO));
if (to != null) {
query.setToExcluded(to.getTime());
}
int page = request.mandatoryParamAsInt(Param.PAGE);
int pageSize = request.mandatoryParamAsInt(Param.PAGE_SIZE);
query.setPage(page, pageSize);
int total = dbClient.qProfileChangeDao().countByQuery(dbSession, query);
List<Change> changelogs = load(dbSession, query);
Map<String, UserDto> usersByUuid = getUsersByUserUuid(dbSession, changelogs);
Map<String, RuleDto> rulesByRuleIds = getRulesByRuleUuids(dbSession, changelogs);
writeResponse(response.newJsonWriter(), total, page, pageSize, changelogs, usersByUuid, rulesByRuleIds);
}
}
private Map<String, UserDto> getUsersByUserUuid(DbSession dbSession, List<Change> changes) {
Set<String> userUuids = changes.stream()
.map(Change::getUserUuid)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
return dbClient.userDao()
.selectByUuids(dbSession, userUuids)
.stream()
.collect(Collectors.toMap(UserDto::getUuid, Function.identity()));
}
private Map<String, RuleDto> getRulesByRuleUuids(DbSession dbSession, List<Change> changes) {
Set<String> ruleUuids = changes.stream()
.map(c -> c.ruleUuid)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
return dbClient.ruleDao()
.selectByUuids(dbSession, Lists.newArrayList(ruleUuids))
.stream()
.collect(Collectors.toMap(RuleDto::getUuid, Function.identity()));
}
private static void writeResponse(JsonWriter json, int total, int page, int pageSize, List<Change> changelogs,
Map<String, UserDto> usersByUuid, Map<String, RuleDto> rulesByRuleUuids) {
json.beginObject();
writePaging(json, total, page, pageSize);
json.name("paging").beginObject()
.prop("pageIndex", page)
.prop("pageSize", pageSize)
.prop("total", total)
.endObject();
json.name("events").beginArray();
changelogs.forEach(change -> {
JsonWriter changeWriter = json.beginObject();
changeWriter
.prop("date", DateUtils.formatDateTime(change.getCreatedAt()))
.prop("action", change.getType());
UserDto user = usersByUuid.get(change.getUserUuid());
if (user != null) {
changeWriter
.prop("authorLogin", user.getLogin())
.prop("authorName", user.getName());
}
RuleDto rule = rulesByRuleUuids.get(change.getRuleUuid());
if (rule != null) {
changeWriter
.prop("ruleKey", rule.getKey().toString())
.prop("ruleName", rule.getName());
}
writeParameters(json, change);
json.endObject();
});
json.endArray();
json.endObject().close();
}
private static void writeParameters(JsonWriter json, Change change) {
json.name("params").beginObject()
.prop("severity", change.getSeverity());
for (Map.Entry<String, String> param : change.getParams().entrySet()) {
json.prop(param.getKey(), param.getValue());
}
json.endObject();
}
/**
* @deprecated since 9.8 - replaced by 'paging' object structure.
*/
@Deprecated(since = "9.8")
private static void writePaging(JsonWriter json, int total, int page, int pageSize) {
json.prop("total", total);
json.prop(Param.PAGE, page);
json.prop(Param.PAGE_SIZE, pageSize);
}
/**
* @return non-null list of changes, by descending order of date
*/
public List<Change> load(DbSession dbSession, QProfileChangeQuery query) {
List<QProfileChangeDto> changeDtos = dbClient.qProfileChangeDao().selectByQuery(dbSession, query);
return changeDtos.stream()
.map(Change::from)
.toList();
}
static class Change {
private String key;
private String type;
private long at;
private String severity;
private String userUuid;
private String inheritance;
private String ruleUuid;
private final Map<String, String> params = new HashMap<>();
private Change() {
}
public String getKey() {
return key;
}
@CheckForNull
public String getSeverity() {
return severity;
}
@CheckForNull
public String getUserUuid() {
return userUuid;
}
public String getType() {
return type;
}
@CheckForNull
public String getInheritance() {
return inheritance;
}
@CheckForNull
public String getRuleUuid() {
return ruleUuid;
}
public long getCreatedAt() {
return at;
}
public Map<String, String> getParams() {
return params;
}
private static Change from(QProfileChangeDto dto) {
Map<String, String> data = dto.getDataAsMap();
Change change = new Change();
change.key = dto.getUuid();
change.userUuid = dto.getUserUuid();
change.type = dto.getChangeType();
change.at = dto.getCreatedAt();
// see content of data in class org.sonar.server.qualityprofile.ActiveRuleChange
change.severity = data.get("severity");
String ruleUuid = data.get("ruleUuid");
if (ruleUuid != null) {
change.ruleUuid = ruleUuid;
}
change.inheritance = data.get("inheritance");
data.entrySet().stream()
.filter(entry -> entry.getKey().startsWith("param_"))
.forEach(entry -> change.params.put(entry.getKey().replace("param_", ""), entry.getValue()));
return change;
}
}
}
| 9,942 | 35.025362 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/CompareAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleRepositoryDto;
import org.sonar.server.qualityprofile.QProfileComparison;
import org.sonar.server.qualityprofile.QProfileComparison.ActiveRuleDiff;
import org.sonar.server.qualityprofile.QProfileComparison.QProfileComparisonResult;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
public class CompareAction implements QProfileWsAction {
private static final String ATTRIBUTE_LEFT = "left";
private static final String ATTRIBUTE_RIGHT = "right";
private static final String ATTRIBUTE_IN_LEFT = "inLeft";
private static final String ATTRIBUTE_IN_RIGHT = "inRight";
private static final String ATTRIBUTE_MODIFIED = "modified";
private static final String ATTRIBUTE_SAME = "same";
private static final String ATTRIBUTE_KEY = "key";
private static final String ATTRIBUTE_NAME = "name";
private static final String ATTRIBUTE_SEVERITY = "severity";
private static final String ATTRIBUTE_PLUGIN_KEY = "pluginKey";
private static final String ATTRIBUTE_PLUGIN_NAME = "pluginName";
private static final String ATTRIBUTE_LANGUAGE_KEY = "languageKey";
private static final String ATTRIBUTE_LANGUAGE_NAME = "languageName";
private static final String ATTRIBUTE_PARAMS = "params";
private static final String PARAM_LEFT_KEY = "leftKey";
private static final String PARAM_RIGHT_KEY = "rightKey";
private final DbClient dbClient;
private final QProfileComparison comparator;
private final Languages languages;
public CompareAction(DbClient dbClient, QProfileComparison comparator, Languages languages) {
this.dbClient = dbClient;
this.comparator = comparator;
this.languages = languages;
}
@Override
public void define(NewController context) {
NewAction compare = context.createAction("compare")
.setDescription("Compare two quality profiles.")
.setHandler(this)
.setInternal(true)
.setResponseExample(getClass().getResource("compare-example.json"))
.setSince("5.2");
compare.createParam(PARAM_LEFT_KEY)
.setDescription("Profile key.")
.setExampleValue(UUID_EXAMPLE_01)
.setRequired(true);
compare.createParam(PARAM_RIGHT_KEY)
.setDescription("Another profile key.")
.setExampleValue(UUID_EXAMPLE_02)
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
String leftKey = request.mandatoryParam(PARAM_LEFT_KEY);
String rightKey = request.mandatoryParam(PARAM_RIGHT_KEY);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto left = dbClient.qualityProfileDao().selectByUuid(dbSession, leftKey);
checkArgument(left != null, "Could not find left profile '%s'", leftKey);
QProfileDto right = dbClient.qualityProfileDao().selectByUuid(dbSession, rightKey);
checkArgument(right != null, "Could not find right profile '%s'", rightKey);
QProfileComparisonResult result = comparator.compare(dbSession, left, right);
List<RuleDto> referencedRules = dbClient.ruleDao().selectByKeys(dbSession, new ArrayList<>(result.collectRuleKeys()));
Map<RuleKey, RuleDto> rulesByKey = Maps.uniqueIndex(referencedRules, RuleDto::getKey);
Map<String, RuleRepositoryDto> repositoriesByKey = Maps.uniqueIndex(dbClient.ruleRepositoryDao().selectAll(dbSession), RuleRepositoryDto::getKey);
writeResult(response.newJsonWriter(), result, rulesByKey, repositoriesByKey);
}
}
private void writeResult(JsonWriter json, QProfileComparisonResult result, Map<RuleKey, RuleDto> rulesByKey, Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginObject();
json.name(ATTRIBUTE_LEFT).beginObject();
writeProfile(json, result.left());
json.endObject();
json.name(ATTRIBUTE_RIGHT).beginObject();
writeProfile(json, result.right());
json.endObject();
json.name(ATTRIBUTE_IN_LEFT);
writeRules(json, result.inLeft(), rulesByKey, repositoriesByKey);
json.name(ATTRIBUTE_IN_RIGHT);
writeRules(json, result.inRight(), rulesByKey, repositoriesByKey);
json.name(ATTRIBUTE_MODIFIED);
writeDifferences(json, result.modified(), rulesByKey, repositoriesByKey);
json.name(ATTRIBUTE_SAME);
writeRules(json, result.same(), rulesByKey, repositoriesByKey);
json.endObject().close();
}
private static void writeProfile(JsonWriter json, QProfileDto profile) {
json.prop(ATTRIBUTE_KEY, profile.getKee())
.prop(ATTRIBUTE_NAME, profile.getName());
}
private void writeRules(JsonWriter json, Map<RuleKey, ActiveRuleDto> activeRules, Map<RuleKey, RuleDto> rulesByKey,
Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginArray();
for (Entry<RuleKey, ActiveRuleDto> activeRule : activeRules.entrySet()) {
RuleKey key = activeRule.getKey();
ActiveRuleDto value = activeRule.getValue();
json.beginObject();
RuleDto rule = rulesByKey.get(key);
writeRule(json, rule, repositoriesByKey.get(rule.getRepositoryKey()));
json.prop(ATTRIBUTE_SEVERITY, value.getSeverityString());
json.endObject();
}
json.endArray();
}
private void writeRule(JsonWriter json, RuleDto rule, @Nullable RuleRepositoryDto repository) {
String repositoryKey = rule.getRepositoryKey();
json.prop(ATTRIBUTE_KEY, rule.getKey().toString())
.prop(ATTRIBUTE_NAME, rule.getName())
.prop(ATTRIBUTE_PLUGIN_KEY, repositoryKey);
if (repository != null) {
String languageKey = repository.getLanguage();
Language language = languages.get(languageKey);
json.prop(ATTRIBUTE_PLUGIN_NAME, repository.getName());
json.prop(ATTRIBUTE_LANGUAGE_KEY, languageKey);
json.prop(ATTRIBUTE_LANGUAGE_NAME, language == null ? null : language.getName());
}
}
private void writeDifferences(JsonWriter json, Map<RuleKey, ActiveRuleDiff> modified, Map<RuleKey, RuleDto> rulesByKey,
Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginArray();
for (Entry<RuleKey, ActiveRuleDiff> diffEntry : modified.entrySet()) {
RuleKey key = diffEntry.getKey();
ActiveRuleDiff value = diffEntry.getValue();
json.beginObject();
RuleDto rule = rulesByKey.get(key);
writeRule(json, rule, repositoriesByKey.get(rule.getRepositoryKey()));
json.name(ATTRIBUTE_LEFT).beginObject();
json.prop(ATTRIBUTE_SEVERITY, value.leftSeverity());
json.name(ATTRIBUTE_PARAMS).beginObject();
for (Entry<String, ValueDifference<String>> valueDiff : value.paramDifference().entriesDiffering().entrySet()) {
json.prop(valueDiff.getKey(), valueDiff.getValue().leftValue());
}
for (Entry<String, String> valueDiff : value.paramDifference().entriesOnlyOnLeft().entrySet()) {
json.prop(valueDiff.getKey(), valueDiff.getValue());
}
// params
json.endObject();
// left
json.endObject();
json.name(ATTRIBUTE_RIGHT).beginObject();
json.prop(ATTRIBUTE_SEVERITY, value.rightSeverity());
json.name(ATTRIBUTE_PARAMS).beginObject();
for (Entry<String, ValueDifference<String>> valueDiff : value.paramDifference().entriesDiffering().entrySet()) {
json.prop(valueDiff.getKey(), valueDiff.getValue().rightValue());
}
for (Entry<String, String> valueDiff : value.paramDifference().entriesOnlyOnRight().entrySet()) {
json.prop(valueDiff.getKey(), valueDiff.getValue());
}
// params
json.endObject();
// right
json.endObject();
// rule
json.endObject();
}
json.endArray();
}
}
| 9,384 | 39.982533 | 162 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/CopyAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
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.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QProfileCopier;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualityprofiles.CopyWsResponse;
import static java.util.Optional.ofNullable;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_COPY;
public class CopyAction implements QProfileWsAction {
private static final String PARAM_TO_NAME = "toName";
private static final String PARAM_FROM_KEY = "fromKey";
private final DbClient dbClient;
private final QProfileCopier profileCopier;
private final Languages languages;
private final UserSession userSession;
private final QProfileWsSupport wsSupport;
public CopyAction(DbClient dbClient, QProfileCopier profileCopier, Languages languages, UserSession userSession, QProfileWsSupport wsSupport) {
this.dbClient = dbClient;
this.profileCopier = profileCopier;
this.languages = languages;
this.userSession = userSession;
this.wsSupport = wsSupport;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction(ACTION_COPY)
.setSince("5.2")
.setDescription("Copy a quality profile.<br> " +
"Requires to be logged in and the 'Administer Quality Profiles' permission.")
.setResponseExample(getClass().getResource("copy-example.json"))
.setPost(true)
.setHandler(this);
action.createParam(PARAM_TO_NAME)
.setDescription("Name for the new quality profile.")
.setExampleValue("My Sonar way")
.setRequired(true);
action.createParam(PARAM_FROM_KEY)
.setDescription("Quality profile key")
.setExampleValue(UUID_EXAMPLE_01)
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
String newName = request.mandatoryParam(PARAM_TO_NAME);
String profileKey = request.mandatoryParam(PARAM_FROM_KEY);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto sourceProfile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(profileKey));
userSession.checkPermission(ADMINISTER_QUALITY_PROFILES);
QProfileDto copiedProfile = profileCopier.copyToName(dbSession, sourceProfile, newName);
boolean isDefault = dbClient.defaultQProfileDao().isDefault(dbSession, copiedProfile.getKee());
CopyWsResponse wsResponse = buildResponse(copiedProfile, isDefault);
writeProtobuf(wsResponse, request, response);
}
}
private CopyWsResponse buildResponse(QProfileDto copiedProfile, boolean isDefault) {
String languageKey = copiedProfile.getLanguage();
Language language = languages.get(copiedProfile.getLanguage());
String parentKey = copiedProfile.getParentKee();
CopyWsResponse.Builder wsResponse = CopyWsResponse.newBuilder();
wsResponse.setKey(copiedProfile.getKee());
wsResponse.setName(copiedProfile.getName());
wsResponse.setLanguage(languageKey);
ofNullable(language).ifPresent(l -> wsResponse.setLanguageName(l.getName()));
wsResponse.setIsDefault(isDefault);
wsResponse.setIsInherited(parentKey != null);
ofNullable(parentKey).ifPresent(wsResponse::setParentKey);
return wsResponse.build();
}
}
| 4,735 | 39.135593 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/CreateAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Change;
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.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QProfileExporters;
import org.sonar.server.qualityprofile.QProfileFactory;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import org.sonar.server.qualityprofile.QProfileResult;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.server.language.LanguageParamUtils.getOrderedLanguageKeys;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_CREATE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_NAME;
import org.springframework.beans.factory.annotation.Autowired;
public class CreateAction implements QProfileWsAction {
private static final String PARAM_BACKUP_FORMAT = "backup_%s";
static final int NAME_MAXIMUM_LENGTH = 100;
private final DbClient dbClient;
private final QProfileFactory profileFactory;
private final QProfileExporters exporters;
private final Languages languages;
private final ProfileImporter[] importers;
private final UserSession userSession;
private final ActiveRuleIndexer activeRuleIndexer;
@Autowired(required = false)
public CreateAction(DbClient dbClient, QProfileFactory profileFactory, QProfileExporters exporters, Languages languages,
UserSession userSession, ActiveRuleIndexer activeRuleIndexer, ProfileImporter... importers) {
this.dbClient = dbClient;
this.profileFactory = profileFactory;
this.exporters = exporters;
this.languages = languages;
this.userSession = userSession;
this.activeRuleIndexer = activeRuleIndexer;
this.importers = importers;
}
@Autowired(required = false)
public CreateAction(DbClient dbClient, QProfileFactory profileFactory, QProfileExporters exporters, Languages languages,
UserSession userSession, ActiveRuleIndexer activeRuleIndexer) {
this(dbClient, profileFactory, exporters, languages, userSession, activeRuleIndexer, new ProfileImporter[0]);
}
@Override
public void define(WebService.NewController controller) {
NewAction create = controller.createAction(ACTION_CREATE)
.setPost(true)
.setDescription("Create a quality profile.<br>" +
"Requires to be logged in and the 'Administer Quality Profiles' permission.")
.setResponseExample(getClass().getResource("create-example.json"))
.setSince("5.2")
.setHandler(this);
List<Change> changelog = new ArrayList<>();
create.createParam(PARAM_NAME)
.setRequired(true)
.setMaximumLength(NAME_MAXIMUM_LENGTH)
.setDescription("Quality profile name")
.setExampleValue("My Sonar way");
create.createParam(PARAM_LANGUAGE)
.setRequired(true)
.setDescription("Quality profile language")
.setExampleValue("js")
.setPossibleValues(getOrderedLanguageKeys(languages));
for (ProfileImporter importer : importers) {
String backupParamName = getBackupParamName(importer.getKey());
create.createParam(backupParamName)
.setDescription(String.format("A configuration file for %s.", importer.getName()))
.setDeprecatedSince("9.8");
changelog.add(new Change("9.8", String.format("'%s' parameter is deprecated", backupParamName)));
}
create.setChangelog(changelog.toArray(new Change[0]));
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(ADMINISTER_QUALITY_PROFILES);
CreateRequest createRequest = toRequest(request);
writeProtobuf(doHandle(dbSession, createRequest, request), request, response);
}
}
private CreateWsResponse doHandle(DbSession dbSession, CreateRequest createRequest, Request request) {
QProfileResult result = new QProfileResult();
QProfileDto profile = profileFactory.checkAndCreateCustom(dbSession, QProfileName.createFor(createRequest.getLanguage(), createRequest.getName()));
result.setProfile(profile);
for (ProfileImporter importer : importers) {
String importerKey = importer.getKey();
InputStream contentToImport = request.paramAsInputStream(getBackupParamName(importerKey));
if (contentToImport != null) {
result.add(exporters.importXml(profile, importerKey, contentToImport, dbSession));
}
}
activeRuleIndexer.commitAndIndex(dbSession, result.getChanges());
return buildResponse(result);
}
private static CreateRequest toRequest(Request request) {
Builder builder = CreateRequest.builder()
.setLanguage(request.mandatoryParam(PARAM_LANGUAGE))
.setName(request.mandatoryParam(PARAM_NAME));
return builder.build();
}
private CreateWsResponse buildResponse(QProfileResult result) {
String language = result.profile().getLanguage();
CreateWsResponse.QualityProfile.Builder builder = CreateWsResponse.QualityProfile.newBuilder()
.setKey(result.profile().getKee())
.setName(result.profile().getName())
.setLanguage(language)
.setLanguageName(languages.get(result.profile().getLanguage()).getName())
.setIsDefault(false)
.setIsInherited(false);
if (!result.infos().isEmpty()) {
builder.getInfosBuilder().addAllInfos(result.infos());
}
if (!result.warnings().isEmpty()) {
builder.getWarningsBuilder().addAllWarnings(result.warnings());
}
return CreateWsResponse.newBuilder().setProfile(builder.build()).build();
}
private static String getBackupParamName(String importerKey) {
return String.format(PARAM_BACKUP_FORMAT, importerKey);
}
private static class CreateRequest {
private final String name;
private final String language;
private CreateRequest(Builder builder) {
this.name = builder.name;
this.language = builder.language;
}
public String getLanguage() {
return language;
}
public String getName() {
return name;
}
public static Builder builder() {
return new Builder();
}
}
private static class Builder {
private String language;
private String name;
private Builder() {
// enforce factory method use
}
public Builder setLanguage(@Nullable String language) {
this.language = language;
return this;
}
public Builder setName(@Nullable String profileName) {
this.name = profileName;
return this;
}
public CreateRequest build() {
checkArgument(language != null && !language.isEmpty(), "Language is mandatory and must not be empty.");
checkArgument(name != null && !name.isEmpty(), "Profile name is mandatory and must not be empty.");
return new CreateRequest(this);
}
}
}
| 8,548 | 38.03653 | 151 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/DeactivateRuleAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singletonList;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_DEACTIVATE_RULE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RULE;
public class DeactivateRuleAction implements QProfileWsAction {
private final DbClient dbClient;
private final QProfileRules ruleActivator;
private final UserSession userSession;
private final QProfileWsSupport wsSupport;
public DeactivateRuleAction(DbClient dbClient, QProfileRules ruleActivator, UserSession userSession, QProfileWsSupport wsSupport) {
this.dbClient = dbClient;
this.ruleActivator = ruleActivator;
this.userSession = userSession;
this.wsSupport = wsSupport;
}
public void define(WebService.NewController controller) {
WebService.NewAction deactivate = controller
.createAction(ACTION_DEACTIVATE_RULE)
.setDescription("Deactivate a rule on a quality profile.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setHandler(this)
.setPost(true)
.setSince("4.4");
deactivate.createParam(PARAM_KEY)
.setDescription("Quality Profile key. Can be obtained through <code>api/qualityprofiles/search</code>")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
deactivate.createParam(PARAM_RULE)
.setDescription("Rule key")
.setRequired(true)
.setExampleValue("java:S1144");
}
@Override
public void handle(Request request, Response response) throws Exception {
RuleKey ruleKey = RuleKey.parse(request.mandatoryParam(PARAM_RULE));
String qualityProfileKey = request.mandatoryParam(PARAM_KEY);
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
RuleDto rule = wsSupport.getRule(dbSession, ruleKey);
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(qualityProfileKey));
wsSupport.checkCanEdit(dbSession, profile);
ruleActivator.deactivateAndCommit(dbSession, profile, singletonList(rule.getUuid()));
}
response.noContent();
}
}
| 3,720 | 39.89011 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/DeactivateRulesAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.user.UserSession;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_04;
import static org.sonar.server.qualityprofile.ws.BulkChangeWsResponse.writeResponse;
import static org.sonar.server.rule.ws.RuleWsSupport.defineGenericRuleSearchParameters;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_DEACTIVATE_RULES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
public class DeactivateRulesAction implements QProfileWsAction {
private final RuleQueryFactory ruleQueryFactory;
private final UserSession userSession;
private final QProfileRules ruleActivator;
private final QProfileWsSupport wsSupport;
private final DbClient dbClient;
public DeactivateRulesAction(RuleQueryFactory ruleQueryFactory, UserSession userSession, QProfileRules ruleActivator, QProfileWsSupport wsSupport, DbClient dbClient) {
this.ruleQueryFactory = ruleQueryFactory;
this.userSession = userSession;
this.ruleActivator = ruleActivator;
this.wsSupport = wsSupport;
this.dbClient = dbClient;
}
public void define(WebService.NewController controller) {
WebService.NewAction deactivate = controller
.createAction(ACTION_DEACTIVATE_RULES)
.setDescription("Bulk deactivate rules on Quality profiles.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setPost(true)
.setSince("4.4")
.setChangelog(new Change("10.0", "Parameter 'sansTop25' is deprecated"))
.setHandler(this);
defineGenericRuleSearchParameters(deactivate);
deactivate.createParam(PARAM_TARGET_KEY)
.setDescription("Quality Profile key on which the rule deactivation is done. To retrieve a profile key please see <code>api/qualityprofiles/search</code>")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_04);
}
@Override
public void handle(Request request, Response response) throws Exception {
String qualityProfileKey = request.mandatoryParam(PARAM_TARGET_KEY);
userSession.checkLoggedIn();
BulkChangeResult result;
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(qualityProfileKey));
wsSupport.checkCanEdit(dbSession, profile);
RuleQuery ruleQuery = ruleQueryFactory.createRuleQuery(dbSession, request);
ruleQuery.setIncludeExternal(false);
result = ruleActivator.bulkDeactivateAndCommit(dbSession, profile, ruleQuery);
}
writeResponse(result, response);
}
}
| 4,103 | 42.659574 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/DeleteAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QProfileFactory;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.singleton;
public class DeleteAction implements QProfileWsAction {
private final Languages languages;
private final QProfileFactory profileFactory;
private final DbClient dbClient;
private final UserSession userSession;
private final QProfileWsSupport wsSupport;
public DeleteAction(Languages languages, QProfileFactory profileFactory, DbClient dbClient, UserSession userSession, QProfileWsSupport wsSupport) {
this.languages = languages;
this.profileFactory = profileFactory;
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
}
@Override
public void define(NewController controller) {
NewAction action = controller.createAction("delete")
.setDescription("Delete a quality profile and all its descendants. The default quality profile cannot be deleted.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setSince("5.2")
.setPost(true)
.setHandler(this);
QProfileReference.defineParams(action, languages);
}
@Override
public void handle(Request request, Response response) {
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromName(request));
wsSupport.checkCanAdministrate(profile);
Collection<QProfileDto> descendants = selectDescendants(dbSession, profile);
ensureNoneIsMarkedAsDefault(dbSession, profile, descendants);
profileFactory.delete(dbSession, merge(profile, descendants));
dbSession.commit();
}
response.noContent();
}
private Collection<QProfileDto> selectDescendants(DbSession dbSession, QProfileDto profile) {
return dbClient.qualityProfileDao().selectDescendants(dbSession, singleton(profile));
}
private void ensureNoneIsMarkedAsDefault(DbSession dbSession, QProfileDto profile, Collection<QProfileDto> descendants) {
Set<String> allUuids = new HashSet<>();
allUuids.add(profile.getKee());
descendants.forEach(p -> allUuids.add(p.getKee()));
Set<String> uuidsOfDefaultProfiles = dbClient.defaultQProfileDao().selectExistingQProfileUuids(dbSession, allUuids);
checkArgument(!uuidsOfDefaultProfiles.contains(profile.getKee()), "Profile '%s' cannot be deleted because it is marked as default", profile.getName());
descendants.stream()
.filter(p -> uuidsOfDefaultProfiles.contains(p.getKee()))
.findFirst()
.ifPresent(p -> {
throw new IllegalArgumentException(String.format("Profile '%s' cannot be deleted because its descendant named '%s' is marked as default", profile.getName(), p.getName()));
});
}
private static List<QProfileDto> merge(QProfileDto profile, Collection<QProfileDto> descendants) {
return Stream.concat(Stream.of(profile), descendants.stream())
.toList();
}
}
| 4,596 | 38.973913 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ExportAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.Response.Stream;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.language.LanguageParamUtils;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileExporters;
import org.sonarqube.ws.MediaTypes;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class ExportAction implements QProfileWsAction {
private static final String PARAM_EXPORTER_KEY = "exporterKey";
private final DbClient dbClient;
private final QProfileBackuper backuper;
private final QProfileExporters exporters;
private final Languages languages;
public ExportAction(DbClient dbClient, QProfileBackuper backuper, QProfileExporters exporters, Languages languages) {
this.dbClient = dbClient;
this.backuper = backuper;
this.exporters = exporters;
this.languages = languages;
}
@Override
public void define(WebService.NewController controller) {
NewAction action = controller.createAction("export")
.setSince("5.2")
.setDescription("Export a quality profile.")
.setResponseExample(getClass().getResource("export-example.xml"))
.setHandler(this);
action.createParam(PARAM_QUALITY_PROFILE)
.setDescription("Quality profile name to export. If left empty, the default profile for the language is exported.")
.setExampleValue("My Sonar way");
action.createParam(PARAM_LANGUAGE)
.setDescription("Quality profile language")
.setRequired(true)
.setExampleValue(LanguageParamUtils.getExampleValue(languages))
.setPossibleValues(LanguageParamUtils.getOrderedLanguageKeys(languages));
Set<String> exporterKeys = Arrays.stream(languages.all())
.map(language -> exporters.exportersForLanguage(language.getKey()))
.flatMap(Collection::stream)
.map(ProfileExporter::getKey)
.collect(Collectors.toSet());
if (!exporterKeys.isEmpty()) {
action.createParam(PARAM_EXPORTER_KEY)
.setDescription("Output format. If left empty, the same format as api/qualityprofiles/backup is used. " +
"Possible values are described by api/qualityprofiles/exporters.")
.setPossibleValues(exporterKeys);
}
}
@Override
public void handle(Request request, Response response) throws Exception {
String name = request.param(PARAM_QUALITY_PROFILE);
String language = request.mandatoryParam(PARAM_LANGUAGE);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = loadProfile(dbSession, language, name);
String exporterKey = exporters.exportersForLanguage(profile.getLanguage()).isEmpty() ? null : request.param(PARAM_EXPORTER_KEY);
writeResponse(dbSession, profile, exporterKey, response);
}
}
private void writeResponse(DbSession dbSession, QProfileDto profile, @Nullable String exporterKey, Response response) throws IOException {
Stream stream = response.stream();
ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
try (Writer writer = new OutputStreamWriter(bufferStream, UTF_8)) {
if (exporterKey == null) {
stream.setMediaType(MediaTypes.XML);
backuper.backup(dbSession, profile, writer);
} else {
stream.setMediaType(exporters.mimeType(exporterKey));
exporters.export(dbSession, profile, exporterKey, writer);
}
}
OutputStream output = response.stream().output();
IOUtils.write(bufferStream.toByteArray(), output);
}
private QProfileDto loadProfile(DbSession dbSession, String language, @Nullable String name) {
QProfileDto profile;
if (name == null) {
// return the default profile
profile = dbClient.qualityProfileDao().selectDefaultProfile(dbSession, language);
} else {
profile = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, name, language);
}
return checkFound(profile, "Could not find profile with name '%s' for language '%s'", name, language);
}
}
| 5,829 | 40.347518 | 140 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ExportersAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.utils.text.JsonWriter;
import org.springframework.beans.factory.annotation.Autowired;
public class ExportersAction implements QProfileWsAction {
private final ProfileExporter[] exporters;
@Autowired(required = false)
public ExportersAction(ProfileExporter[] exporters) {
this.exporters = exporters;
}
/**
* Used by the container if no {@link ProfileExporter} is found
*/
@Autowired(required = false)
public ExportersAction() {
this(new ProfileExporter[0]);
}
@Override
public void define(NewController context) {
context.createAction("exporters")
.setDescription("Lists available profile export formats.")
.setHandler(this)
.setResponseExample(getClass().getResource("exporters-example.json"))
.setSince("5.2");
}
@Override
public void handle(Request request, Response response) throws Exception {
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject().name("exporters").beginArray();
for (ProfileExporter exporter : exporters) {
json.beginObject()
.prop("key", exporter.getKey())
.prop("name", exporter.getName());
json.name("languages").beginArray();
for (String language : exporter.getSupportedLanguages()) {
json.value(language);
}
json.endArray().endObject();
}
json.endArray().endObject();
}
}
}
| 2,490 | 32.662162 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ImportersAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import org.sonar.api.profiles.ProfileImporter;
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.text.JsonWriter;
import org.springframework.beans.factory.annotation.Autowired;
public class ImportersAction implements QProfileWsAction {
private final ProfileImporter[] importers;
@Autowired(required = false)
public ImportersAction(ProfileImporter[] importers) {
this.importers = importers;
}
@Autowired(required = false)
public ImportersAction() {
this(new ProfileImporter[0]);
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("importers")
.setSince("5.2")
.setDescription("List supported importers.")
.setResponseExample(getClass().getResource("importers-example.json"))
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject().name("importers").beginArray();
for (ProfileImporter importer : importers) {
json.beginObject()
.prop("key", importer.getKey())
.prop("name", importer.getName())
.name("languages").beginArray();
for (String languageKey : importer.getSupportedLanguages()) {
json.value(languageKey);
}
json.endArray().endObject();
}
json.endArray().endObject();
}
}
}
| 2,403 | 33.342857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/InheritanceAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleCountQuery;
import org.sonar.db.qualityprofile.ActiveRuleDao;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonarqube.ws.Qualityprofiles.InheritanceWsResponse;
import org.sonarqube.ws.Qualityprofiles.InheritanceWsResponse.QualityProfile;
import static java.util.Collections.singleton;
import static java.util.Optional.ofNullable;
import static org.sonar.db.qualityprofile.ActiveRuleDto.OVERRIDES;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class InheritanceAction implements QProfileWsAction {
private final DbClient dbClient;
private final QProfileWsSupport wsSupport;
private final Languages languages;
public InheritanceAction(DbClient dbClient, QProfileWsSupport wsSupport, Languages languages) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.languages = languages;
}
@Override
public void define(NewController context) {
NewAction inheritance = context.createAction("inheritance")
.setSince("5.2")
.setDescription("Show a quality profile's ancestors and children.")
.setHandler(this)
.setResponseExample(getClass().getResource("inheritance-example.json"));
QProfileReference.defineParams(inheritance, languages);
}
@Override
public void handle(Request request, Response response) throws Exception {
QProfileReference reference = QProfileReference.fromName(request);
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, reference);
List<QProfileDto> ancestors = ancestors(profile, dbSession);
List<QProfileDto> children = dbClient.qualityProfileDao().selectChildren(dbSession, singleton(profile));
List<QProfileDto> allProfiles = new ArrayList<>();
allProfiles.add(profile);
allProfiles.addAll(ancestors);
allProfiles.addAll(children);
Statistics statistics = new Statistics(dbSession, allProfiles);
writeProtobuf(buildResponse(profile, ancestors, children, statistics), request, response);
}
}
private List<QProfileDto> ancestors(QProfileDto profile, DbSession dbSession) {
List<QProfileDto> ancestors = new ArrayList<>();
collectAncestors(profile, ancestors, dbSession);
return ancestors;
}
private void collectAncestors(QProfileDto profile, List<QProfileDto> ancestors, DbSession session) {
if (profile.getParentKee() == null) {
return;
}
QProfileDto parent = getParent(session, profile);
ancestors.add(parent);
collectAncestors(parent, ancestors, session);
}
private QProfileDto getParent(DbSession dbSession, QProfileDto profile) {
QProfileDto parent = dbClient.qualityProfileDao().selectByUuid(dbSession, profile.getParentKee());
if (parent == null) {
throw new IllegalStateException("Cannot find parent of profile: " + profile.getKee());
}
return parent;
}
private static InheritanceWsResponse buildResponse(QProfileDto profile, List<QProfileDto> ancestors, List<QProfileDto> children, Statistics statistics) {
return InheritanceWsResponse.newBuilder()
.setProfile(buildProfile(profile, statistics))
.addAllAncestors(buildAncestors(ancestors, statistics))
.addAllChildren(buildChildren(children, statistics))
.build();
}
private static Iterable<QualityProfile> buildAncestors(List<QProfileDto> ancestors, Statistics statistics) {
return ancestors.stream()
.map(ancestor -> buildProfile(ancestor, statistics))
.toList();
}
private static Iterable<QualityProfile> buildChildren(List<QProfileDto> children, Statistics statistics) {
return children.stream()
.map(child -> buildProfile(child, statistics))
.toList();
}
private static QualityProfile buildProfile(QProfileDto qualityProfile, Statistics statistics) {
String key = qualityProfile.getKee();
QualityProfile.Builder builder = QualityProfile.newBuilder()
.setKey(key)
.setName(qualityProfile.getName())
.setActiveRuleCount(statistics.countRulesByProfileKey.getOrDefault(key, 0L))
.setOverridingRuleCount(statistics.countOverridingRulesByProfileKey.getOrDefault(key, 0L))
.setIsBuiltIn(qualityProfile.isBuiltIn());
ofNullable(qualityProfile.getParentKee()).ifPresent(builder::setParent);
return builder.build();
}
private class Statistics {
private final Map<String, Long> countRulesByProfileKey;
private final Map<String, Long> countOverridingRulesByProfileKey;
private Statistics(DbSession dbSession, List<QProfileDto> profiles) {
ActiveRuleDao dao = dbClient.activeRuleDao();
ActiveRuleCountQuery.Builder builder = ActiveRuleCountQuery.builder();
countRulesByProfileKey = dao.countActiveRulesByQuery(dbSession, builder.setProfiles(profiles).build());
countOverridingRulesByProfileKey = dao.countActiveRulesByQuery(dbSession, builder.setProfiles(profiles).setInheritance(OVERRIDES).build());
}
}
}
| 6,258 | 40.450331 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/ProjectsAction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.server.ws.WebService.SelectionMode;
import org.sonar.api.utils.Paging;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ProjectQprofileAssociationDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static java.util.Comparator.comparing;
import static org.sonar.api.utils.Paging.forPageIndex;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
public class ProjectsAction implements QProfileWsAction {
private static final int MAX_PAGE_SIZE = 500;
private final DbClient dbClient;
private final UserSession userSession;
public ProjectsAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(NewController controller) {
NewAction action = controller.createAction("projects")
.setSince("5.2")
.setHandler(this)
.setDescription("List projects with their association status regarding a quality profile <br/>" +
"See api/qualityprofiles/search in order to get the Quality Profile Key")
.setResponseExample(getClass().getResource("projects-example.json"));
action.setChangelog(
new Change("10.0", "deprecated 'more' response field has been removed"),
new Change("8.8", "deprecated 'id' response field has been removed"),
new Change("8.8", "deprecated 'uuid' response field has been removed"),
new Change("7.2", "'more' response field is deprecated"),
new Change("6.5", "'id' response field is deprecated"),
new Change("6.0", "'uuid' response field is deprecated and replaced by 'id'"),
new Change("6.0", "'key' response field has been added to return the project key"));
action.createParam(PARAM_KEY)
.setDescription("Quality profile key")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_01);
action.addSelectionModeParam();
action.createSearchQuery("sonar", "projects");
action.createPageParam();
action.createPageSize(100, MAX_PAGE_SIZE);
}
@Override
public void handle(Request request, Response response) throws Exception {
String profileKey = request.mandatoryParam(PARAM_KEY);
try (DbSession session = dbClient.openSession(false)) {
String selected = request.param(Param.SELECTED);
String query = request.param(Param.TEXT_QUERY);
int page = request.mandatoryParamAsInt(Param.PAGE);
int pageSize = request.mandatoryParamAsInt(Param.PAGE_SIZE);
List<ProjectQprofileAssociationDto> projects = loadAllProjects(profileKey, session, selected, query).stream()
.sorted(comparing(ProjectQprofileAssociationDto::getProjectName)
.thenComparing(ProjectQprofileAssociationDto::getProjectUuid))
.toList();
Collection<String> projectUuids = projects.stream()
.map(ProjectQprofileAssociationDto::getProjectUuid)
.collect(Collectors.toSet());
Set<String> authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(session, projectUuids, userSession.getUuid(), UserRole.USER);
Paging paging = forPageIndex(page).withPageSize(pageSize).andTotal(authorizedProjectUuids.size());
List<ProjectQprofileAssociationDto> authorizedProjects = projects.stream()
.filter(input -> authorizedProjectUuids.contains(input.getProjectUuid()))
.skip(paging.offset())
.limit(paging.pageSize())
.toList();
writeProjects(response, authorizedProjects, paging);
}
}
private List<ProjectQprofileAssociationDto> loadAllProjects(String profileKey, DbSession session, String selected, String query) {
QProfileDto profile = dbClient.qualityProfileDao().selectByUuid(session, profileKey);
if (profile == null) {
throw new NotFoundException("Quality profile not found: " + profileKey);
}
List<ProjectQprofileAssociationDto> projects;
SelectionMode selectionMode = SelectionMode.fromParam(selected);
if (SelectionMode.SELECTED == selectionMode) {
projects = dbClient.qualityProfileDao().selectSelectedProjects(session, profile, query);
} else if (SelectionMode.DESELECTED == selectionMode) {
projects = dbClient.qualityProfileDao().selectDeselectedProjects(session, profile, query);
} else {
projects = dbClient.qualityProfileDao().selectProjectAssociations(session, profile, query);
}
return projects;
}
private static void writeProjects(Response response, List<ProjectQprofileAssociationDto> projects, Paging paging) {
JsonWriter json = response.newJsonWriter();
json.beginObject();
json.name("results").beginArray();
for (ProjectQprofileAssociationDto project : projects) {
json.beginObject()
.prop("key", project.getProjectKey())
.prop("name", project.getProjectName())
.prop("selected", project.isAssociated())
.endObject();
}
json.endArray();
json.name("paging").beginObject()
.prop("pageIndex", paging.pageIndex())
.prop("pageSize", paging.pageSize())
.prop("total", paging.total())
.endObject();
json.endObject();
json.close();
}
}
| 6,709 | 39.914634 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualityprofile/ws/QProfileReference.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.qualityprofile.ws;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
/**
* Reference to a Quality profile as defined by requests to web services api/qualityprofiles.
* The two exclusive options to reference a profile are:
* <ul>
* <li>by its id (to be deprecated)</li>
* <li>by the tuple {language, name}</li>
* </ul>
*/
public class QProfileReference {
private enum Type {
KEY, NAME
}
private final Type type;
private final String key;
private final String language;
private final String name;
private QProfileReference(Type type, @Nullable String key, @Nullable String language, @Nullable String name) {
this.type = type;
if (type == Type.KEY) {
this.key = requireNonNull(key);
this.language = null;
this.name = null;
} else {
this.key = null;
this.language = requireNonNull(language);
this.name = requireNonNull(name);
}
}
/**
* @return {@code true} if key is defined and {@link #getKey()} can be called. If {@code false}, then
* the couple {language, name} is defined and the methods {@link #getLanguage()}/{@link #getName()}
* can be called.
*/
public boolean hasKey() {
return type == Type.KEY;
}
/**
* @return non-null key
* @throws IllegalStateException if {@link #hasKey()} does not return {@code true}
*/
public String getKey() {
checkState(key != null, "Key is not defined. Please call hasKey().");
return key;
}
/**
* @return non-null language
* @throws IllegalStateException if {@link #hasKey()} does not return {@code false}
*/
public String getLanguage() {
checkState(type == Type.NAME, "Language is not defined. Please call hasKey().");
return language;
}
/**
* @return non-null name
* @throws IllegalStateException if {@link #hasKey()} does not return {@code false}
*/
public String getName() {
checkState(type == Type.NAME, "Name is not defined. Please call hasKey().");
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QProfileReference that = (QProfileReference) o;
return Objects.equals(key, that.key) && Objects.equals(language, that.language) && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(key, language, name);
}
public static QProfileReference fromName(Request request) {
String lang = request.mandatoryParam(PARAM_LANGUAGE);
String name = request.mandatoryParam(PARAM_QUALITY_PROFILE);
return fromName(lang, name);
}
public static QProfileReference fromKey(String key) {
return new QProfileReference(Type.KEY, key, null, null);
}
public static QProfileReference fromName(String lang, String name) {
return new QProfileReference(Type.NAME, null, requireNonNull(lang), requireNonNull(name));
}
public static void defineParams(WebService.NewAction action, Languages languages) {
action.createParam(PARAM_QUALITY_PROFILE)
.setDescription("Quality profile name.")
.setRequired(true)
.setExampleValue("Sonar way");
action.createParam(PARAM_LANGUAGE)
.setDescription("Quality profile language.")
.setRequired(true)
.setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet()));
}
}
| 4,824 | 31.823129 | 119 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.