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/measure/ws/ComponentDtoToWsComponent.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.measure.ws;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Measures;
import org.sonarqube.ws.Measures.Component;
import static java.util.Optional.ofNullable;
class ComponentDtoToWsComponent {
private ComponentDtoToWsComponent() {
// static methods only
}
static Component.Builder componentDtoToWsComponent(ComponentDto component, Map<MetricDto, LiveMeasureDto> measuresByMetric,
Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch,
@Nullable String pullRequest) {
Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
if (referenceComponent != null) {
wsComponent.setRefKey(referenceComponent.getKey());
}
Measures.Measure.Builder measureBuilder = Measures.Measure.newBuilder();
for (Map.Entry<MetricDto, LiveMeasureDto> entry : measuresByMetric.entrySet()) {
MeasureDtoToWsMeasure.updateMeasureBuilder(measureBuilder, entry.getKey(), entry.getValue());
wsComponent.addMeasures(measureBuilder);
measureBuilder.clear();
}
return wsComponent;
}
static Component.Builder componentDtoToWsComponent(ComponentDto component, @Nullable String branch, @Nullable String pullRequest) {
Component.Builder wsComponent = Component.newBuilder()
.setKey(ComponentDto.removeBranchAndPullRequestFromKey(component.getKey()))
.setName(component.name())
.setQualifier(component.qualifier());
ofNullable(branch).ifPresent(wsComponent::setBranch);
ofNullable(pullRequest).ifPresent(wsComponent::setPullRequest);
ofNullable(component.path()).ifPresent(wsComponent::setPath);
ofNullable(component.description()).ifPresent(wsComponent::setDescription);
ofNullable(component.language()).ifPresent(wsComponent::setLanguage);
return wsComponent;
}
}
| 3,041 | 42.457143 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeAction.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.measure.ws;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.resources.Scopes;
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.Param;
import org.sonar.api.utils.Paging;
import org.sonar.api.web.UserRole;
import org.sonar.core.i18n.I18n;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTreeQuery;
import org.sonar.db.component.ComponentTreeQuery.Strategy;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.measure.MeasureTreeQuery;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.metric.MetricDtoFunctions;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Measures;
import org.sonarqube.ws.Measures.ComponentTreeWsResponse;
import org.sonarqube.ws.client.component.ComponentsWsParameters;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static org.sonar.api.measures.Metric.ValueType.DATA;
import static org.sonar.api.measures.Metric.ValueType.DISTRIB;
import static org.sonar.api.utils.Paging.offset;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES;
import static org.sonar.server.component.ws.MeasuresWsParameters.ACTION_COMPONENT_TREE;
import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_METRICS;
import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_PERIOD;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_ADDITIONAL_FIELDS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_COMPONENT;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_KEYS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_PERIOD_SORT;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_SORT;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_SORT_FILTER;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_QUALIFIERS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_STRATEGY;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.measure.ws.ComponentDtoToWsComponent.componentDtoToWsComponent;
import static org.sonar.server.measure.ws.MeasureDtoToWsMeasure.updateMeasureBuilder;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createAdditionalFieldsParameter;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createMetricKeysParameter;
import static org.sonar.server.measure.ws.MetricDtoToWsMetric.metricDtoToWsMetric;
import static org.sonar.server.measure.ws.SnapshotDtoToWsPeriod.snapshotToWsPeriods;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter;
import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* <p>Navigate through components based on different strategy with specified measures.
* To limit the number of rows in database, a best value algorithm exists in database.</p>
* A measure is not stored in database if:
* <ul>
* <li>the component is a file (production or test)</li>
* <li>optimization algorithm is enabled on the metric</li>
* <li>the measure computed equals the metric best value</li>
* <li>the period values are all equal to 0</li>
* </ul>
* To recreate a best value 2 different cases:
* <ul>
* <li>Metric starts with 'new_' (ex: new_violations): the best value measure doesn't have a value and period values are all equal to 0</li>
* <li>Other metrics: the best value measure has a value of 0 and no period value</li>
* </ul>
*/
public class ComponentTreeAction implements MeasuresWsAction {
private static final int MAX_SIZE = 500;
private static final int QUERY_MINIMUM_LENGTH = 3;
// tree exploration strategies
static final String ALL_STRATEGY = "all";
static final String CHILDREN_STRATEGY = "children";
static final String LEAVES_STRATEGY = "leaves";
static final Map<String, Strategy> STRATEGIES = Map.of(
ALL_STRATEGY, LEAVES,
CHILDREN_STRATEGY, CHILDREN,
LEAVES_STRATEGY, LEAVES);
// sort
static final String NAME_SORT = "name";
static final String PATH_SORT = "path";
static final String QUALIFIER_SORT = "qualifier";
static final String METRIC_SORT = "metric";
static final String METRIC_PERIOD_SORT = "metricPeriod";
static final Set<String> SORTS = ImmutableSortedSet.of(NAME_SORT, PATH_SORT, QUALIFIER_SORT, METRIC_SORT, METRIC_PERIOD_SORT);
static final String ALL_METRIC_SORT_FILTER = "all";
static final String WITH_MEASURES_ONLY_METRIC_SORT_FILTER = "withMeasuresOnly";
static final Set<String> METRIC_SORT_FILTERS = ImmutableSortedSet.of(ALL_METRIC_SORT_FILTER, WITH_MEASURES_ONLY_METRIC_SORT_FILTER);
static final Set<String> FORBIDDEN_METRIC_TYPES = Set.of(DISTRIB.name(), DATA.name());
private static final int MAX_METRIC_KEYS = 15;
private static final String COMMA_JOIN_SEPARATOR = ", ";
private static final Set<String> QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE = Set.of(Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE);
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
private final I18n i18n;
private final ResourceTypes resourceTypes;
public ComponentTreeAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, I18n i18n,
ResourceTypes resourceTypes) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
this.i18n = i18n;
this.resourceTypes = resourceTypes;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_COMPONENT_TREE)
.setDescription(format("Navigate through components based on the chosen strategy with specified measures.<br>" +
"Requires the following permission: 'Browse' on the specified project.<br>" +
"For applications, it also requires 'Browse' permission on its child projects. <br>" +
"When limiting search with the %s parameter, directories are not returned.", Param.TEXT_QUERY))
.setResponseExample(getClass().getResource("component_tree-example.json"))
.setSince("5.4")
.setHandler(this)
.addPagingParams(100, MAX_SIZE)
.setChangelog(
new Change("10.1", String.format("The use of 'BRC' as value for parameter '%s' is removed", ComponentsWsParameters.PARAM_QUALIFIERS)),
new Change("10.0", format("The use of the following metrics in 'metricKeys' parameter is not deprecated anymore: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("10.0", "the response field periods under measures field is removed."),
new Change("10.0", "the option `periods` of 'additionalFields' request field is removed."),
new Change("9.3", format("The use of the following metrics in 'metricKeys' parameter is deprecated: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("8.8", "parameter 'component' is now required"),
new Change("8.8", "deprecated parameter 'baseComponentId' has been removed"),
new Change("8.8", "deprecated parameter 'baseComponentKey' has been removed."),
new Change("8.8", "deprecated response field 'id' has been removed"),
new Change("8.8", "deprecated response field 'refId' has been removed."),
new Change("8.1", "the response field periods under measures field is deprecated. Use period instead."),
new Change("8.1", "the response field periods is deprecated. Use period instead."),
new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)),
new Change("7.2", "field 'bestValue' is added to the response"),
new Change("6.3", format("Number of metric keys is limited to %s", MAX_METRIC_KEYS)),
new Change("6.6", "the response field 'id' is deprecated. Use 'key' instead."),
new Change("6.6", "the response field 'refId' is deprecated. Use 'refKey' instead."));
action.createSortParams(SORTS, NAME_SORT, true)
.setDescription("Comma-separated list of sort fields")
.setExampleValue(NAME_SORT + "," + PATH_SORT);
action.createParam(Param.TEXT_QUERY)
.setDescription("Limit search to: <ul>" +
"<li>component names that contain the supplied string</li>" +
"<li>component keys that are exactly the same as the supplied string</li>" +
"</ul>")
.setMinimumLength(QUERY_MINIMUM_LENGTH)
.setExampleValue("FILE_NAM");
action.createParam(PARAM_COMPONENT)
.setRequired(true)
.setDescription("Component key. The search is based on this component.")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setDescription("Branch key. Not available in the community edition.")
.setExampleValue(KEY_BRANCH_EXAMPLE_001)
.setSince("6.6");
action.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id. Not available in the community edition.")
.setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001)
.setSince("7.1");
action.createParam(PARAM_METRIC_SORT)
.setDescription(
format("Metric key to sort by. The '%s' parameter must contain the '%s' or '%s' value. It must be part of the '%s' parameter", Param.SORT, METRIC_SORT, METRIC_PERIOD_SORT,
PARAM_METRIC_KEYS))
.setExampleValue("ncloc");
action.createParam(PARAM_METRIC_PERIOD_SORT)
.setDescription(format("Sort measures by leak period or not ?. The '%s' parameter must contain the '%s' value.", Param.SORT, METRIC_PERIOD_SORT))
.setSince("5.5")
.setPossibleValues(1);
action.createParam(PARAM_METRIC_SORT_FILTER)
.setDescription(format("Filter components. Sort must be on a metric. Possible values are: " +
"<ul>" +
"<li>%s: return all components</li>" +
"<li>%s: filter out components that do not have a measure on the sorted metric</li>" +
"</ul>", ALL_METRIC_SORT_FILTER, WITH_MEASURES_ONLY_METRIC_SORT_FILTER))
.setDefaultValue(ALL_METRIC_SORT_FILTER)
.setPossibleValues(METRIC_SORT_FILTERS);
createMetricKeysParameter(action)
.setDescription("Comma-separated list of metric keys. Types %s are not allowed.", String.join(COMMA_JOIN_SEPARATOR, FORBIDDEN_METRIC_TYPES))
.setMaxValuesAllowed(MAX_METRIC_KEYS);
createAdditionalFieldsParameter(action);
createQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes));
action.createParam(PARAM_STRATEGY)
.setDescription("Strategy to search for base component descendants:" +
"<ul>" +
"<li>children: return the children components of the base component. Grandchildren components are not returned</li>" +
"<li>all: return all the descendants components of the base component. Grandchildren are returned.</li>" +
"<li>leaves: return all the descendant components (files, in general) which don't have other children. They are the leaves of the component tree.</li>" +
"</ul>")
.setPossibleValues(STRATEGIES.keySet())
.setDefaultValue(ALL_STRATEGY);
}
@Override
public void handle(Request request, Response response) throws Exception {
ComponentTreeWsResponse componentTreeWsResponse = doHandle(toComponentTreeWsRequest(request));
writeProtobuf(componentTreeWsResponse, request, response);
}
private ComponentTreeWsResponse doHandle(ComponentTreeRequest request) {
ComponentTreeData data = load(request);
if (data.getComponents() == null) {
return emptyResponse(data.getBaseComponent(), data.getBranch(), request);
}
return buildResponse(
request,
data,
Paging.forPageIndex(
request.getPage())
.withPageSize(request.getPageSize())
.andTotal(data.getComponentCount()));
}
private static ComponentTreeWsResponse buildResponse(ComponentTreeRequest request, ComponentTreeData data, Paging paging) {
ComponentTreeWsResponse.Builder response = ComponentTreeWsResponse.newBuilder();
response.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total())
.build();
boolean isMainBranch = data.getBranch() == null || data.getBranch().isMain();
response.setBaseComponent(
toWsComponent(
data.getBaseComponent(),
data.getMeasuresByComponentUuidAndMetric().row(data.getBaseComponent().uuid()),
data.getReferenceComponentsByUuid(), isMainBranch ? null : request.getBranch(), request.getPullRequest()));
for (ComponentDto componentDto : data.getComponents()) {
if (componentDto.getCopyComponentUuid() != null) {
String refBranch = data.getBranchByReferenceUuid().get(componentDto.getCopyComponentUuid());
response.addComponents(toWsComponent(
componentDto,
data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()),
data.getReferenceComponentsByUuid(), refBranch, null));
} else {
response.addComponents(toWsComponent(
componentDto,
data.getMeasuresByComponentUuidAndMetric().row(componentDto.uuid()),
data.getReferenceComponentsByUuid(), isMainBranch ? null : request.getBranch(), request.getPullRequest()));
}
}
if (areMetricsInResponse(request)) {
Measures.Metrics.Builder metricsBuilder = response.getMetricsBuilder();
for (MetricDto metricDto : data.getMetrics()) {
metricsBuilder.addMetrics(metricDtoToWsMetric(metricDto));
}
}
List<String> additionalFields = Optional.ofNullable(request.getAdditionalFields()).orElse(Collections.emptyList());
if (additionalFields.contains(ADDITIONAL_PERIOD) && data.getPeriod() != null) {
response.setPeriod(data.getPeriod());
}
return response.build();
}
private static boolean areMetricsInResponse(ComponentTreeRequest request) {
List<String> additionalFields = request.getAdditionalFields();
return additionalFields != null && additionalFields.contains(ADDITIONAL_METRICS);
}
private static ComponentTreeWsResponse emptyResponse(@Nullable ComponentDto baseComponent, @Nullable BranchDto branch, ComponentTreeRequest request) {
ComponentTreeWsResponse.Builder response = ComponentTreeWsResponse.newBuilder();
response.getPagingBuilder()
.setPageIndex(request.getPage())
.setPageSize(request.getPageSize())
.setTotal(0);
if (baseComponent != null) {
boolean isMainBranch = branch == null || branch.isMain();
response.setBaseComponent(componentDtoToWsComponent(baseComponent, isMainBranch ? null : request.getBranch(), request.getPullRequest()));
}
return response.build();
}
private static ComponentTreeRequest toComponentTreeWsRequest(Request request) {
List<String> metricKeys = request.mandatoryParamAsStrings(PARAM_METRIC_KEYS);
checkArgument(metricKeys.size() <= MAX_METRIC_KEYS, "Number of metrics keys is limited to %s, got %s", MAX_METRIC_KEYS, metricKeys.size());
ComponentTreeRequest componentTreeRequest = new ComponentTreeRequest()
.setComponent(request.mandatoryParam(PARAM_COMPONENT))
.setBranch(request.param(PARAM_BRANCH))
.setPullRequest(request.param(PARAM_PULL_REQUEST))
.setMetricKeys(metricKeys)
.setStrategy(request.mandatoryParam(PARAM_STRATEGY))
.setQualifiers(request.paramAsStrings(PARAM_QUALIFIERS))
.setAdditionalFields(request.paramAsStrings(PARAM_ADDITIONAL_FIELDS))
.setSort(request.paramAsStrings(Param.SORT))
.setAsc(request.paramAsBoolean(Param.ASCENDING))
.setMetricSort(request.param(PARAM_METRIC_SORT))
.setMetricSortFilter(request.mandatoryParam(PARAM_METRIC_SORT_FILTER))
.setMetricPeriodSort(request.paramAsInt(PARAM_METRIC_PERIOD_SORT))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setQuery(request.param(Param.TEXT_QUERY));
String metricSortValue = componentTreeRequest.getMetricSort();
checkRequest(!componentTreeRequest.getMetricKeys().isEmpty(), "The '%s' parameter must contain at least one metric key", PARAM_METRIC_KEYS);
List<String> sorts = Optional.ofNullable(componentTreeRequest.getSort()).orElse(emptyList());
checkRequest(metricSortValue == null ^ sorts.contains(METRIC_SORT) ^ sorts.contains(METRIC_PERIOD_SORT),
"To sort by a metric, the '%s' parameter must contain '%s' or '%s', and a metric key must be provided in the '%s' parameter",
Param.SORT, METRIC_SORT, METRIC_PERIOD_SORT, PARAM_METRIC_SORT);
checkRequest(metricSortValue == null ^ componentTreeRequest.getMetricKeys().contains(metricSortValue),
"To sort by the '%s' metric, it must be in the list of metric keys in the '%s' parameter", metricSortValue, PARAM_METRIC_KEYS);
checkRequest(componentTreeRequest.getMetricPeriodSort() == null ^ sorts.contains(METRIC_PERIOD_SORT),
"To sort by a metric period, the '%s' parameter must contain '%s' and the '%s' must be provided.", Param.SORT, METRIC_PERIOD_SORT, PARAM_METRIC_PERIOD_SORT);
checkRequest(ALL_METRIC_SORT_FILTER.equals(componentTreeRequest.getMetricSortFilter()) || metricSortValue != null,
"To filter components based on the sort metric, the '%s' parameter must contain '%s' or '%s' and the '%s' parameter must be provided",
Param.SORT, METRIC_SORT, METRIC_PERIOD_SORT, PARAM_METRIC_SORT);
return componentTreeRequest;
}
private static Measures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures,
Map<String, ComponentDto> referenceComponentsByUuid, @Nullable String branch, @Nullable String pullRequest) {
Measures.Component.Builder wsComponent = componentDtoToWsComponent(component, branch, pullRequest);
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid());
if (referenceComponent != null) {
wsComponent.setRefKey(referenceComponent.getKey());
String displayQualifier = getDisplayQualifier(component, referenceComponent);
wsComponent.setQualifier(displayQualifier);
}
Measures.Measure.Builder measureBuilder = Measures.Measure.newBuilder();
for (Map.Entry<MetricDto, ComponentTreeData.Measure> entry : measures.entrySet()) {
ComponentTreeData.Measure measure = entry.getValue();
boolean onNewCode = entry.getKey().getKey().startsWith("new_");
updateMeasureBuilder(measureBuilder, entry.getKey(), measure.getValue(), measure.getData(), onNewCode);
wsComponent.addMeasures(measureBuilder);
measureBuilder.clear();
}
return wsComponent;
}
// https://jira.sonarsource.com/browse/SONAR-13703 - for apps that were added as a local reference to a portfolio, we want to
// show them as apps, not sub-portfolios
private static String getDisplayQualifier(ComponentDto component, ComponentDto referenceComponent) {
String qualifier = component.qualifier();
if (qualifier.equals(Qualifiers.SUBVIEW) && referenceComponent.qualifier().equals(Qualifiers.APP)) {
return Qualifiers.APP;
}
return qualifier;
}
private ComponentTreeData load(ComponentTreeRequest wsRequest) {
try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto baseComponent = loadComponent(dbSession, wsRequest);
checkPermissions(baseComponent);
// portfolios don't have branches
BranchDto branchDto = dbClient.branchDao().selectByUuid(dbSession, baseComponent.branchUuid()).orElse(null);
Optional<SnapshotDto> baseSnapshot = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, baseComponent.branchUuid());
if (baseSnapshot.isEmpty()) {
return ComponentTreeData.builder()
.setBranch(branchDto)
.setBaseComponent(baseComponent)
.build();
}
Set<String> requestedMetricKeys = new HashSet<>(wsRequest.getMetricKeys());
Set<String> metricKeysToSearch = new HashSet<>(requestedMetricKeys);
boolean isPR = isPR(wsRequest.getPullRequest());
if (isPR) {
PrMeasureFix.addReplacementMetricKeys(metricKeysToSearch);
}
ComponentTreeQuery componentTreeQuery = toComponentTreeQuery(wsRequest, baseComponent);
List<ComponentDto> components = searchComponents(dbSession, componentTreeQuery);
List<MetricDto> metrics = searchMetrics(dbSession, metricKeysToSearch);
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric = searchMeasuresByComponentUuidAndMetric(dbSession, baseComponent, componentTreeQuery,
components,
metrics);
if (isPR) {
PrMeasureFix.removeMetricsNotRequested(metrics, requestedMetricKeys);
PrMeasureFix.createReplacementMeasures(metrics, measuresByComponentUuidAndMetric, requestedMetricKeys);
}
components = filterComponents(components, measuresByComponentUuidAndMetric, metrics, wsRequest);
components = filterAuthorizedComponents(components);
components = sortComponents(components, wsRequest, metrics, measuresByComponentUuidAndMetric);
int componentCount = components.size();
components = paginateComponents(components, wsRequest);
Map<String, ComponentDto> referencesByUuid = searchReferenceComponentsById(dbSession, components);
Map<String, String> branchByReferenceUuid = searchReferenceBranchKeys(dbSession, referencesByUuid.keySet());
return ComponentTreeData.builder()
.setBaseComponent(baseComponent)
.setBranch(branchDto)
.setComponentsFromDb(components)
.setComponentCount(componentCount)
.setBranchByReferenceUuid(branchByReferenceUuid)
.setMeasuresByComponentUuidAndMetric(measuresByComponentUuidAndMetric)
.setMetrics(metrics)
.setPeriod(snapshotToWsPeriods(baseSnapshot.get()).orElse(null))
.setReferenceComponentsByUuid(referencesByUuid)
.build();
}
}
private Map<String, String> searchReferenceBranchKeys(DbSession dbSession, Set<String> referenceUuids) {
return dbClient.branchDao().selectByUuids(dbSession, referenceUuids).stream()
.filter(b -> !b.isMain())
.collect(Collectors.toMap(BranchDto::getUuid, BranchDto::getBranchKey));
}
private static boolean isPR(@Nullable String pullRequest) {
return pullRequest != null;
}
private ComponentDto loadComponent(DbSession dbSession, ComponentTreeRequest request) {
String componentKey = request.getComponent();
String branch = request.getBranch();
String pullRequest = request.getPullRequest();
return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
}
private Map<String, ComponentDto> searchReferenceComponentsById(DbSession dbSession, List<ComponentDto> components) {
List<String> referenceComponentUUids = components.stream()
.map(ComponentDto::getCopyComponentUuid)
.filter(Objects::nonNull)
.toList();
if (referenceComponentUUids.isEmpty()) {
return emptyMap();
}
return FluentIterable.from(dbClient.componentDao().selectByUuids(dbSession, referenceComponentUUids))
.uniqueIndex(ComponentDto::uuid);
}
private List<ComponentDto> searchComponents(DbSession dbSession, ComponentTreeQuery componentTreeQuery) {
Collection<String> qualifiers = componentTreeQuery.getQualifiers();
if (qualifiers != null && qualifiers.isEmpty()) {
return Collections.emptyList();
}
return dbClient.componentDao().selectDescendants(dbSession, componentTreeQuery);
}
private List<MetricDto> searchMetrics(DbSession dbSession, Set<String> metricKeys) {
List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, metricKeys);
if (metrics.size() < metricKeys.size()) {
List<String> foundMetricKeys = Lists.transform(metrics, MetricDto::getKey);
Set<String> missingMetricKeys = Sets.difference(
new LinkedHashSet<>(metricKeys),
new LinkedHashSet<>(foundMetricKeys));
throw new NotFoundException(format("The following metric keys are not found: %s", String.join(COMMA_JOIN_SEPARATOR, missingMetricKeys)));
}
String forbiddenMetrics = metrics.stream()
.filter(metric -> ComponentTreeAction.FORBIDDEN_METRIC_TYPES.contains(metric.getValueType()))
.map(MetricDto::getKey)
.sorted()
.collect(Collectors.joining(COMMA_JOIN_SEPARATOR));
checkArgument(forbiddenMetrics.isEmpty(), "Metrics %s can't be requested in this web service. Please use api/measures/component", forbiddenMetrics);
return metrics;
}
private Table<String, MetricDto, ComponentTreeData.Measure> searchMeasuresByComponentUuidAndMetric(DbSession dbSession, ComponentDto baseComponent,
ComponentTreeQuery componentTreeQuery, List<ComponentDto> components, List<MetricDto> metrics) {
Map<String, MetricDto> metricsByUuid = Maps.uniqueIndex(metrics, MetricDto::getUuid);
MeasureTreeQuery measureQuery = MeasureTreeQuery.builder()
.setStrategy(MeasureTreeQuery.Strategy.valueOf(componentTreeQuery.getStrategy().name()))
.setNameOrKeyQuery(componentTreeQuery.getNameOrKeyQuery())
.setQualifiers(componentTreeQuery.getQualifiers())
.setMetricUuids(new ArrayList<>(metricsByUuid.keySet()))
.build();
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric = HashBasedTable.create(components.size(), metrics.size());
dbClient.liveMeasureDao().selectTreeByQuery(dbSession, baseComponent, measureQuery, result -> {
LiveMeasureDto measureDto = result.getResultObject();
measuresByComponentUuidAndMetric.put(
measureDto.getComponentUuid(),
metricsByUuid.get(measureDto.getMetricUuid()),
ComponentTreeData.Measure.createFromMeasureDto(measureDto));
});
addBestValuesToMeasures(measuresByComponentUuidAndMetric, components, metrics);
return measuresByComponentUuidAndMetric;
}
/**
* Conditions for best value measure:
* <ul>
* <li>component is a production file or test file</li>
* <li>metric is optimized for best value</li>
* </ul>
*/
private static void addBestValuesToMeasures(Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric, List<ComponentDto> components,
List<MetricDto> metrics) {
List<MetricDtoWithBestValue> metricDtosWithBestValueMeasure = metrics.stream()
.filter(MetricDtoFunctions.isOptimizedForBestValue())
.map(new MetricDtoToMetricDtoWithBestValue())
.toList();
if (metricDtosWithBestValueMeasure.isEmpty()) {
return;
}
Stream<ComponentDto> componentsEligibleForBestValue = components.stream().filter(ComponentTreeAction::isFileComponent);
componentsEligibleForBestValue.forEach(component -> {
for (MetricDtoWithBestValue metricWithBestValue : metricDtosWithBestValueMeasure) {
if (measuresByComponentUuidAndMetric.get(component.uuid(), metricWithBestValue.getMetric()) == null) {
measuresByComponentUuidAndMetric.put(component.uuid(), metricWithBestValue.getMetric(),
ComponentTreeData.Measure.createFromMeasureDto(metricWithBestValue.getBestValue()));
}
}
});
}
private static List<ComponentDto> filterComponents(List<ComponentDto> components,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric, List<MetricDto> metrics, ComponentTreeRequest wsRequest) {
if (!componentWithMeasuresOnly(wsRequest)) {
return components;
}
String metricKeyToSort = wsRequest.getMetricSort();
Optional<MetricDto> metricToSort = metrics.stream().filter(m -> metricKeyToSort.equals(m.getKey())).findFirst();
checkState(metricToSort.isPresent(), "Metric '%s' not found", metricKeyToSort, wsRequest.getMetricKeys());
return components
.stream()
.filter(new HasMeasure(measuresByComponentUuidAndMetric, metricToSort.get()))
.toList();
}
private List<ComponentDto> filterAuthorizedComponents(List<ComponentDto> components) {
return userSession.keepAuthorizedComponents(UserRole.USER, components);
}
private static boolean componentWithMeasuresOnly(ComponentTreeRequest wsRequest) {
return WITH_MEASURES_ONLY_METRIC_SORT_FILTER.equals(wsRequest.getMetricSortFilter());
}
private static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
return ComponentTreeSort.sortComponents(components, wsRequest, metrics, measuresByComponentUuidAndMetric);
}
private static List<ComponentDto> paginateComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest) {
return components.stream()
.skip(offset(wsRequest.getPage(), wsRequest.getPageSize()))
.limit(wsRequest.getPageSize())
.toList();
}
@CheckForNull
private List<String> childrenQualifiers(ComponentTreeRequest request, String baseQualifier) {
List<String> requestQualifiers = request.getQualifiers();
List<String> childrenQualifiers = null;
if (LEAVES_STRATEGY.equals(request.getStrategy())) {
childrenQualifiers = resourceTypes.getLeavesQualifiers(baseQualifier);
}
if (requestQualifiers == null) {
return childrenQualifiers;
}
if (childrenQualifiers == null) {
return requestQualifiers;
}
Sets.SetView<String> qualifiersIntersection = Sets.intersection(new HashSet<>(childrenQualifiers), new HashSet<Object>(requestQualifiers));
return new ArrayList<>(qualifiersIntersection);
}
private ComponentTreeQuery toComponentTreeQuery(ComponentTreeRequest wsRequest, ComponentDto baseComponent) {
List<String> childrenQualifiers = childrenQualifiers(wsRequest, baseComponent.qualifier());
ComponentTreeQuery.Builder componentTreeQueryBuilder = ComponentTreeQuery.builder()
.setBaseUuid(baseComponent.uuid())
.setStrategy(STRATEGIES.get(wsRequest.getStrategy()));
if (wsRequest.getQuery() != null) {
componentTreeQueryBuilder.setNameOrKeyQuery(wsRequest.getQuery());
}
if (childrenQualifiers != null) {
componentTreeQueryBuilder.setQualifiers(childrenQualifiers);
}
return componentTreeQueryBuilder.build();
}
private void checkPermissions(ComponentDto baseComponent) {
userSession.checkComponentPermission(UserRole.USER, baseComponent);
if (Scopes.PROJECT.equals(baseComponent.scope()) && Qualifiers.APP.equals(baseComponent.qualifier())) {
userSession.checkChildProjectsPermission(UserRole.USER, baseComponent);
}
}
public static boolean isFileComponent(@Nonnull ComponentDto input) {
return QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(input.qualifier());
}
private static class MetricDtoToMetricDtoWithBestValue implements Function<MetricDto, MetricDtoWithBestValue> {
@Override
public MetricDtoWithBestValue apply(@Nonnull MetricDto input) {
return new MetricDtoWithBestValue(input);
}
}
}
| 34,091 | 49.431953 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeData.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.measure.ws;
import com.google.common.collect.Table;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Measures;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
import static java.util.Objects.requireNonNull;
class ComponentTreeData {
private final ComponentDto baseComponent;
private final BranchDto branch;
private final List<ComponentDto> components;
private final int componentCount;
private final Map<String, ComponentDto> referenceComponentsByUuid;
private final Map<String, String> branchByReferenceUuid;
private final List<MetricDto> metrics;
private final Measures.Period period;
private final Table<String, MetricDto, Measure> measuresByComponentUuidAndMetric;
private ComponentTreeData(Builder builder) {
this.baseComponent = builder.baseComponent;
this.components = builder.componentsFromDb;
this.componentCount = builder.componentCount;
this.branch = builder.branch;
this.referenceComponentsByUuid = builder.referenceComponentsByUuid;
this.branchByReferenceUuid = builder.branchByReferenceUuid;
this.metrics = builder.metrics;
this.measuresByComponentUuidAndMetric = builder.measuresByComponentUuidAndMetric;
this.period = builder.period;
}
public Map<String, String> getBranchByReferenceUuid() {
return branchByReferenceUuid;
}
public ComponentDto getBaseComponent() {
return baseComponent;
}
@CheckForNull
public BranchDto getBranch() {
return branch;
}
@CheckForNull
List<ComponentDto> getComponents() {
return components;
}
@CheckForNull
int getComponentCount() {
return componentCount;
}
public Map<String, ComponentDto> getReferenceComponentsByUuid() {
return referenceComponentsByUuid;
}
@CheckForNull
List<MetricDto> getMetrics() {
return metrics;
}
Measures.Period getPeriod() {
return period;
}
@CheckForNull
Table<String, MetricDto, Measure> getMeasuresByComponentUuidAndMetric() {
return measuresByComponentUuidAndMetric;
}
static Builder builder() {
return new Builder();
}
static class Builder {
private ComponentDto baseComponent;
private List<ComponentDto> componentsFromDb;
private Map<String, ComponentDto> referenceComponentsByUuid;
private Map<String, String> branchByReferenceUuid;
private int componentCount;
private List<MetricDto> metrics;
private Measures.Period period;
private BranchDto branch;
private Table<String, MetricDto, Measure> measuresByComponentUuidAndMetric;
private Builder() {
// private constructor
}
public Builder setBranchByReferenceUuid(Map<String, String> branchByReferenceUuid) {
this.branchByReferenceUuid = branchByReferenceUuid;
return this;
}
public Builder setBaseComponent(ComponentDto baseComponent) {
this.baseComponent = baseComponent;
return this;
}
public Builder setComponentsFromDb(List<ComponentDto> componentsFromDbQuery) {
this.componentsFromDb = componentsFromDbQuery;
return this;
}
public Builder setComponentCount(int componentCount) {
this.componentCount = componentCount;
return this;
}
public Builder setBranch(@Nullable BranchDto branch) {
this.branch = branch;
return this;
}
public Builder setMetrics(List<MetricDto> metrics) {
this.metrics = metrics;
return this;
}
public Builder setPeriod(@Nullable Measures.Period period) {
this.period = period;
return this;
}
public Builder setMeasuresByComponentUuidAndMetric(Table<String, MetricDto, Measure> measuresByComponentUuidAndMetric) {
this.measuresByComponentUuidAndMetric = measuresByComponentUuidAndMetric;
return this;
}
public Builder setReferenceComponentsByUuid(Map<String, ComponentDto> referenceComponentsByUuid) {
this.referenceComponentsByUuid = referenceComponentsByUuid;
return this;
}
public ComponentTreeData build() {
requireNonNull(baseComponent);
return new ComponentTreeData(this);
}
}
static class Measure {
private double value;
private String data;
public Measure(@Nullable String data, @Nullable Double value) {
this.data = data;
this.value = toPrimitive(value);
}
private Measure(LiveMeasureDto measureDto) {
this(measureDto.getDataAsString(), measureDto.getValue());
}
public double getValue() {
return value;
}
public boolean isValueSet() {
return !isNaN(value);
}
@CheckForNull
public String getData() {
return data;
}
static Measure createFromMeasureDto(LiveMeasureDto measureDto) {
return new Measure(measureDto);
}
private static double toPrimitive(@Nullable Double value) {
return value == null ? NaN : value;
}
}
}
| 5,992 | 27.951691 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeRequest.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.measure.ws;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
class ComponentTreeRequest {
private String component;
private String branch;
private String pullRequest;
private String strategy;
private List<String> qualifiers;
private List<String> additionalFields;
private String query;
private List<String> sort;
private Boolean asc;
private String metricSort;
private Integer metricPeriodSort;
private String metricSortFilter;
private List<String> metricKeys;
private Integer page;
private Integer pageSize;
public String getComponent() {
return component;
}
public ComponentTreeRequest setComponent(String component) {
this.component = component;
return this;
}
@CheckForNull
public String getBranch() {
return branch;
}
public ComponentTreeRequest setBranch(@Nullable String branch) {
this.branch = branch;
return this;
}
@CheckForNull
public String getPullRequest() {
return pullRequest;
}
public ComponentTreeRequest setPullRequest(@Nullable String pullRequest) {
this.pullRequest = pullRequest;
return this;
}
@CheckForNull
public String getStrategy() {
return strategy;
}
public ComponentTreeRequest setStrategy(String strategy) {
this.strategy = strategy;
return this;
}
@CheckForNull
public List<String> getQualifiers() {
return qualifiers;
}
public ComponentTreeRequest setQualifiers(@Nullable List<String> qualifiers) {
this.qualifiers = qualifiers;
return this;
}
@CheckForNull
public List<String> getAdditionalFields() {
return additionalFields;
}
public ComponentTreeRequest setAdditionalFields(@Nullable List<String> additionalFields) {
this.additionalFields = additionalFields;
return this;
}
@CheckForNull
public String getQuery() {
return query;
}
public ComponentTreeRequest setQuery(@Nullable String query) {
this.query = query;
return this;
}
@CheckForNull
public List<String> getSort() {
return sort;
}
public ComponentTreeRequest setSort(@Nullable List<String> sort) {
this.sort = sort;
return this;
}
@CheckForNull
public String getMetricSort() {
return metricSort;
}
public ComponentTreeRequest setMetricSort(@Nullable String metricSort) {
this.metricSort = metricSort;
return this;
}
@CheckForNull
public String getMetricSortFilter() {
return metricSortFilter;
}
public ComponentTreeRequest setMetricSortFilter(@Nullable String metricSortFilter) {
this.metricSortFilter = metricSortFilter;
return this;
}
@CheckForNull
public List<String> getMetricKeys() {
return metricKeys;
}
public ComponentTreeRequest setMetricKeys(List<String> metricKeys) {
this.metricKeys = metricKeys;
return this;
}
@CheckForNull
public Boolean getAsc() {
return asc;
}
public ComponentTreeRequest setAsc(@Nullable Boolean asc) {
this.asc = asc;
return this;
}
@CheckForNull
public Integer getPage() {
return page;
}
public ComponentTreeRequest setPage(int page) {
this.page = page;
return this;
}
@CheckForNull
public Integer getPageSize() {
return pageSize;
}
public ComponentTreeRequest setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
@CheckForNull
public Integer getMetricPeriodSort() {
return metricPeriodSort;
}
public ComponentTreeRequest setMetricPeriodSort(@Nullable Integer metricPeriodSort) {
this.metricPeriodSort = metricPeriodSort;
return this;
}
}
| 4,490 | 22.390625 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/ComponentTreeSort.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.measure.ws;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Table;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.exceptions.BadRequestException;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
import static java.lang.String.format;
import static org.sonar.api.measures.Metric.ValueType.BOOL;
import static org.sonar.api.measures.Metric.ValueType.FLOAT;
import static org.sonar.api.measures.Metric.ValueType.INT;
import static org.sonar.api.measures.Metric.ValueType.MILLISEC;
import static org.sonar.api.measures.Metric.ValueType.PERCENT;
import static org.sonar.api.measures.Metric.ValueType.RATING;
import static org.sonar.api.measures.Metric.ValueType.STRING;
import static org.sonar.api.measures.Metric.ValueType.WORK_DUR;
import static org.sonar.server.measure.ws.ComponentTreeAction.METRIC_PERIOD_SORT;
import static org.sonar.server.measure.ws.ComponentTreeAction.METRIC_SORT;
import static org.sonar.server.measure.ws.ComponentTreeAction.NAME_SORT;
import static org.sonar.server.measure.ws.ComponentTreeAction.PATH_SORT;
import static org.sonar.server.measure.ws.ComponentTreeAction.QUALIFIER_SORT;
public class ComponentTreeSort {
private static final Set<ValueType> NUMERIC_VALUE_TYPES = EnumSet.of(BOOL, FLOAT, INT, MILLISEC, WORK_DUR, PERCENT, RATING);
private static final Set<ValueType> TEXTUAL_VALUE_TYPES = EnumSet.of(STRING);
private ComponentTreeSort() {
// static method only
}
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sortParameters.isEmpty()) {
return components;
}
boolean isAscending = wsRequest.getAsc();
Map<String, Ordering<ComponentDto>> orderingsBySortField = ImmutableMap.<String, Ordering<ComponentDto>>builder()
.put(NAME_SORT, componentNameOrdering(isAscending))
.put(QUALIFIER_SORT, componentQualifierOrdering(isAscending))
.put(PATH_SORT, componentPathOrdering(isAscending))
.put(METRIC_SORT, metricValueOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric))
.put(METRIC_PERIOD_SORT, metricPeriodOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric))
.build();
String firstSortParameter = sortParameters.get(0);
Ordering<ComponentDto> primaryOrdering = orderingsBySortField.get(firstSortParameter);
if (sortParameters.size() > 1) {
for (int i = 1; i < sortParameters.size(); i++) {
String secondarySortParameter = sortParameters.get(i);
Ordering<ComponentDto> secondaryOrdering = orderingsBySortField.get(secondarySortParameter);
primaryOrdering = primaryOrdering.compound(secondaryOrdering);
}
}
primaryOrdering = primaryOrdering.compound(componentNameOrdering(true));
return primaryOrdering.immutableSortedCopy(components);
}
private static Ordering<ComponentDto> componentNameOrdering(boolean isAscending) {
return stringOrdering(isAscending, ComponentDto::name);
}
private static Ordering<ComponentDto> componentQualifierOrdering(boolean isAscending) {
return stringOrdering(isAscending, ComponentDto::qualifier);
}
private static Ordering<ComponentDto> componentPathOrdering(boolean isAscending) {
return stringOrdering(isAscending, ComponentDto::path);
}
private static Ordering<ComponentDto> stringOrdering(boolean isAscending, Function<ComponentDto, String> function) {
Ordering<String> ordering = Ordering.from(CASE_INSENSITIVE_ORDER);
if (!isAscending) {
ordering = ordering.reverse();
}
return ordering.nullsLast().onResultOf(function);
}
private static Ordering<ComponentDto> metricValueOrdering(ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
if (wsRequest.getMetricSort() == null) {
return componentNameOrdering(wsRequest.getAsc());
}
Map<String, MetricDto> metricsByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
MetricDto metric = metricsByKey.get(wsRequest.getMetricSort());
boolean isAscending = wsRequest.getAsc();
ValueType metricValueType = ValueType.valueOf(metric.getValueType());
if (NUMERIC_VALUE_TYPES.contains(metricValueType)) {
return numericalMetricOrdering(isAscending, metric, measuresByComponentUuidAndMetric);
} else if (TEXTUAL_VALUE_TYPES.contains(metricValueType)) {
return stringOrdering(isAscending, new ComponentDtoToTextualMeasureValue(metric, measuresByComponentUuidAndMetric));
} else if (ValueType.LEVEL.equals(ValueType.valueOf(metric.getValueType()))) {
return levelMetricOrdering(isAscending, metric, measuresByComponentUuidAndMetric);
}
throw new IllegalStateException("Unrecognized metric value type: " + metric.getValueType());
}
private static Ordering<ComponentDto> metricPeriodOrdering(ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
if (wsRequest.getMetricSort() == null || wsRequest.getMetricPeriodSort() == null) {
return componentNameOrdering(wsRequest.getAsc());
}
Map<String, MetricDto> metricsByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
MetricDto metric = metricsByKey.get(wsRequest.getMetricSort());
ValueType metricValueType = ValueType.valueOf(metric.getValueType());
if (NUMERIC_VALUE_TYPES.contains(metricValueType)) {
return numericalMetricPeriodOrdering(wsRequest, metric, measuresByComponentUuidAndMetric);
}
throw BadRequestException.create(format("Impossible to sort metric '%s' by measure period.", metric.getKey()));
}
private static Ordering<ComponentDto> numericalMetricOrdering(boolean isAscending, @Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
Ordering<Double> ordering = Ordering.natural();
if (!isAscending) {
ordering = ordering.reverse();
}
return ordering.nullsLast().onResultOf(new ComponentDtoToNumericalMeasureValue(metric, measuresByComponentUuidAndMetric));
}
private static Ordering<ComponentDto> numericalMetricPeriodOrdering(ComponentTreeRequest request, @Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
Ordering<Double> ordering = Ordering.natural();
if (!request.getAsc()) {
ordering = ordering.reverse();
}
return ordering.nullsLast().onResultOf(new ComponentDtoToMeasureVariationValue(metric, measuresByComponentUuidAndMetric));
}
private static Ordering<ComponentDto> levelMetricOrdering(boolean isAscending, @Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
Ordering<Integer> ordering = Ordering.natural();
// inverse the order of org.sonar.api.measures.Metric.Level
if (isAscending) {
ordering = ordering.reverse();
}
return ordering.nullsLast().onResultOf(new ComponentDtoToLevelIndex(metric, measuresByComponentUuidAndMetric));
}
private static class ComponentDtoToNumericalMeasureValue implements Function<ComponentDto, Double> {
private final MetricDto metric;
private final Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric;
private ComponentDtoToNumericalMeasureValue(@Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
this.metric = metric;
this.measuresByComponentUuidAndMetric = measuresByComponentUuidAndMetric;
}
@Override
public Double apply(@Nonnull ComponentDto input) {
ComponentTreeData.Measure measure = measuresByComponentUuidAndMetric.get(input.uuid(), metric);
if (measure == null || !measure.isValueSet()) {
return null;
}
return measure.getValue();
}
}
private static class ComponentDtoToLevelIndex implements Function<ComponentDto, Integer> {
private final MetricDto metric;
private final Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric;
private ComponentDtoToLevelIndex(@Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
this.metric = metric;
this.measuresByComponentUuidAndMetric = measuresByComponentUuidAndMetric;
}
@Override
public Integer apply(@Nonnull ComponentDto input) {
ComponentTreeData.Measure measure = measuresByComponentUuidAndMetric.get(input.uuid(), metric);
if (measure == null || measure.getData() == null) {
return null;
}
return Metric.Level.names().indexOf(measure.getData());
}
}
private static class ComponentDtoToMeasureVariationValue implements Function<ComponentDto, Double> {
private final MetricDto metric;
private final Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric;
private ComponentDtoToMeasureVariationValue(@Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
this.metric = metric;
this.measuresByComponentUuidAndMetric = measuresByComponentUuidAndMetric;
}
@Override
public Double apply(@Nonnull ComponentDto input) {
ComponentTreeData.Measure measure = measuresByComponentUuidAndMetric.get(input.uuid(), metric);
if (measure == null || !metric.getKey().startsWith("new_")) {
return null;
}
return measure.getValue();
}
}
private static class ComponentDtoToTextualMeasureValue implements Function<ComponentDto, String> {
private final MetricDto metric;
private final Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric;
private ComponentDtoToTextualMeasureValue(@Nullable MetricDto metric,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
this.metric = metric;
this.measuresByComponentUuidAndMetric = measuresByComponentUuidAndMetric;
}
@Override
public String apply(@Nonnull ComponentDto input) {
ComponentTreeData.Measure measure = measuresByComponentUuidAndMetric.get(input.uuid(), metric);
if (measure == null || measure.getData() == null) {
return null;
}
return measure.getData();
}
}
}
| 12,199 | 44.35316 | 157 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/HasMeasure.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.measure.ws;
import com.google.common.collect.Table;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.metric.MetricDto;
import static org.sonar.server.measure.ws.ComponentTreeData.Measure;
class HasMeasure implements Predicate<ComponentDto> {
private final Predicate<ComponentDto> predicate;
HasMeasure(Table<String, MetricDto, ComponentTreeData.Measure> table, MetricDto metric) {
this.predicate = new HasValue(table, metric);
}
@Override
public boolean test(@Nonnull ComponentDto input) {
return predicate.test(input);
}
private static class HasValue implements Predicate<ComponentDto> {
private final Table<String, MetricDto, ComponentTreeData.Measure> table;
private final MetricDto metric;
private HasValue(Table<String, MetricDto, ComponentTreeData.Measure> table, MetricDto metric) {
this.table = table;
this.metric = metric;
}
@Override
public boolean test(@Nonnull ComponentDto input) {
Measure measure = table.get(input.uuid(), metric);
return measure != null && (measure.isValueSet() || measure.getData() != null);
}
}
}
| 2,068 | 34.672414 | 99 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasureDtoToWsMeasure.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.measure.ws;
import javax.annotation.Nullable;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Measures;
import org.sonarqube.ws.Measures.Measure;
import static java.lang.Double.compare;
import static java.util.Optional.ofNullable;
import static org.sonar.server.measure.ws.MeasureValueFormatter.formatMeasureValue;
class MeasureDtoToWsMeasure {
private MeasureDtoToWsMeasure() {
// static methods
}
static void updateMeasureBuilder(Measure.Builder measureBuilder, MetricDto metricDto, MeasureDto measureDto) {
double value = measureDto.getValue() == null ? Double.NaN : measureDto.getValue();
boolean onNewCode = metricDto.getKey().startsWith("new_");
updateMeasureBuilder(measureBuilder, metricDto, value, measureDto.getData(), onNewCode);
}
static void updateMeasureBuilder(Measure.Builder measureBuilder, MetricDto metricDto, LiveMeasureDto measureDto) {
double value = measureDto.getValue() == null ? Double.NaN : measureDto.getValue();
boolean onNewCode = metricDto.getKey().startsWith("new_");
updateMeasureBuilder(measureBuilder, metricDto, value, measureDto.getDataAsString(), onNewCode);
}
static void updateMeasureBuilder(Measure.Builder measureBuilder, MetricDto metric, double doubleValue, @Nullable String stringValue, boolean onNewCode) {
measureBuilder.setMetric(metric.getKey());
Double bestValue = metric.getBestValue();
if (Double.isNaN(doubleValue) && stringValue == null) {
return;
}
if (!onNewCode) {
measureBuilder.setValue(formatMeasureValue(doubleValue, stringValue, metric));
ofNullable(bestValue).ifPresent(v -> measureBuilder.setBestValue(compare(doubleValue, v) == 0));
} else {
Measures.PeriodValue.Builder periodBuilder = Measures.PeriodValue.newBuilder();
Measures.PeriodValue.Builder builderForValue = periodBuilder
.clear()
.setIndex(1)
.setValue(formatMeasureValue(doubleValue, stringValue, metric));
ofNullable(bestValue).ifPresent(v -> builderForValue.setBestValue(compare(doubleValue, v) == 0));
measureBuilder.setPeriod(builderForValue);
}
}
}
| 3,095 | 41.410959 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasureValueFormatter.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.measure.ws;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
public class MeasureValueFormatter {
private static final double DELTA = 0.000001D;
private MeasureValueFormatter() {
// static methods
}
@CheckForNull
public static String formatMeasureValue(LiveMeasureDto measure, MetricDto metric) {
Double doubleValue = measure.getValue();
String stringValue = measure.getDataAsString();
return formatMeasureValue(doubleValue == null ? Double.NaN : doubleValue, stringValue, metric);
}
@CheckForNull
static String formatMeasureValue(MeasureDto measure, MetricDto metric) {
Double doubleValue = measure.getValue();
String stringValue = measure.getData();
return formatMeasureValue(doubleValue == null ? Double.NaN : doubleValue, stringValue, metric);
}
@CheckForNull
static String formatMeasureValue(double doubleValue, @Nullable String stringValue, MetricDto metric) {
Metric.ValueType metricType = Metric.ValueType.valueOf(metric.getValueType());
return switch (metricType) {
case BOOL -> formatBoolean(doubleValue);
case INT -> formatInteger(doubleValue);
case MILLISEC, WORK_DUR -> formatLong(doubleValue);
case FLOAT, PERCENT, RATING -> String.valueOf(doubleValue);
case LEVEL, STRING, DATA, DISTRIB -> stringValue;
default -> throw new IllegalArgumentException("Unsupported metric type: " + metricType.name());
};
}
static String formatNumericalValue(double value, MetricDto metric) {
Metric.ValueType metricType = Metric.ValueType.valueOf(metric.getValueType());
return switch (metricType) {
case BOOL -> formatBoolean(value);
case INT -> formatInteger(value);
case MILLISEC, WORK_DUR -> formatLong(value);
case FLOAT, PERCENT, RATING -> String.valueOf(value);
default -> throw new IllegalArgumentException(String.format("Unsupported metric type '%s' for numerical value", metricType.name()));
};
}
private static String formatBoolean(double value) {
return Math.abs(value - 1.0D) < DELTA ? "true" : "false";
}
private static String formatInteger(double value) {
return String.valueOf((int) value);
}
private static String formatLong(double value) {
return String.valueOf((long) value);
}
}
| 3,327 | 37.252874 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasuresWs.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.measure.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.component.ws.MeasuresWsParameters;
public class MeasuresWs implements WebService {
private final MeasuresWsAction[] actions;
public MeasuresWs(MeasuresWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(MeasuresWsParameters.CONTROLLER_MEASURES)
.setSince("5.4")
.setDescription("Get components or children with specified measures.");
for (MeasuresWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,528 | 32.977778 | 97 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasuresWsAction.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.measure.ws;
import org.sonar.server.ws.WsAction;
public interface MeasuresWsAction extends WsAction {
// marker interface
}
| 996 | 35.925926 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasuresWsModule.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.measure.ws;
import org.sonar.core.platform.Module;
public class MeasuresWsModule extends Module {
@Override
protected void configureModule() {
add(
MeasuresWs.class,
ComponentTreeAction.class,
ComponentAction.class,
SearchAction.class,
SearchHistoryAction.class);
}
public static String getDeprecatedMetrics() {
return String.join(", ", "releasability_effort", "security_rating_effort", "reliability_rating_effort", "security_review_rating_effort",
"maintainability_rating_effort", "last_change_on_maintainability_rating", "last_change_on_releasability_rating", "last_change_on_reliability_rating",
"last_change_on_security_rating", "last_change_on_security_review_rating");
}
}
| 1,611 | 37.380952 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MeasuresWsParametersBuilder.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.measure.ws;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewParam;
import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_FIELDS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_ADDITIONAL_FIELDS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_KEYS;
class MeasuresWsParametersBuilder {
private MeasuresWsParametersBuilder() {
// prevent instantiation
}
static NewParam createAdditionalFieldsParameter(NewAction action) {
return action.createParam(PARAM_ADDITIONAL_FIELDS)
.setDescription("Comma-separated list of additional fields that can be returned in the response.")
.setPossibleValues(ADDITIONAL_FIELDS)
.setExampleValue("period,metrics");
}
static NewParam createMetricKeysParameter(NewAction action) {
return action.createParam(PARAM_METRIC_KEYS)
.setDescription("Comma-separated list of metric keys")
.setRequired(true)
.setExampleValue("ncloc,complexity,violations");
}
}
| 1,940 | 38.612245 | 104 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MetricDtoToWsMetric.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.measure.ws;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Common.Metric;
import static java.util.Optional.ofNullable;
import static org.sonar.server.measure.ws.MeasureValueFormatter.formatNumericalValue;
class MetricDtoToWsMetric {
private MetricDtoToWsMetric() {
// static methods only
}
static Metric metricDtoToWsMetric(MetricDto metricDto) {
Metric.Builder metric = Metric.newBuilder();
metric.setKey(metricDto.getKey());
metric.setType(metricDto.getValueType());
metric.setName(metricDto.getShortName());
ofNullable(metricDto.getDescription()).ifPresent(metric::setDescription);
ofNullable(metricDto.getDomain()).ifPresent(metric::setDomain);
if (metricDto.getDirection() != 0) {
metric.setHigherValuesAreBetter(metricDto.getDirection() > 0);
}
metric.setQualitative(metricDto.isQualitative());
metric.setHidden(metricDto.isHidden());
ofNullable(metricDto.getDecimalScale()).ifPresent(metric::setDecimalScale);
ofNullable(metricDto.getBestValue()).ifPresent(bv -> metric.setBestValue(formatNumericalValue(bv, metricDto)));
ofNullable(metricDto.getWorstValue()).ifPresent(wv -> metric.setWorstValue(formatNumericalValue(wv, metricDto)));
return metric.build();
}
}
| 2,132 | 40.019231 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/MetricDtoWithBestValue.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.measure.ws;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Set;
import java.util.function.Predicate;
import org.sonar.api.resources.Qualifiers;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
public class MetricDtoWithBestValue {
private static final Set<String> QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE = ImmutableSortedSet.of(Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE);
private final MetricDto metric;
private final LiveMeasureDto bestValue;
MetricDtoWithBestValue(MetricDto metric) {
this.metric = metric;
LiveMeasureDto measure = new LiveMeasureDto().setMetricUuid(metric.getUuid());
measure.setValue(metric.getBestValue());
this.bestValue = measure;
}
MetricDto getMetric() {
return metric;
}
LiveMeasureDto getBestValue() {
return bestValue;
}
static Predicate<ComponentDto> isEligibleForBestValue() {
return component -> QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(component.qualifier());
}
}
| 1,921 | 33.945455 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/PrMeasureFix.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.measure.ws;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import static org.sonar.api.measures.CoreMetrics.BLOCKER_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.BUGS_KEY;
import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS_KEY;
import static org.sonar.api.measures.CoreMetrics.CRITICAL_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.INFO_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.MAJOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.MINOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_BLOCKER_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_BUGS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_CODE_SMELLS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_CRITICAL_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_INFO_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAJOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MINOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_VULNERABILITIES_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
import static org.sonar.api.measures.CoreMetrics.VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY;
/**
* See SONAR-11736
* This class should be removed in 8.0.
*/
class PrMeasureFix {
static final BiMap<String, String> METRICS;
static {
METRICS = HashBiMap.create();
METRICS.put(NEW_VIOLATIONS_KEY, VIOLATIONS_KEY);
// issue severities
METRICS.put(NEW_BLOCKER_VIOLATIONS_KEY, BLOCKER_VIOLATIONS_KEY);
METRICS.put(NEW_CRITICAL_VIOLATIONS_KEY, CRITICAL_VIOLATIONS_KEY);
METRICS.put(NEW_MAJOR_VIOLATIONS_KEY, MAJOR_VIOLATIONS_KEY);
METRICS.put(NEW_MINOR_VIOLATIONS_KEY, MINOR_VIOLATIONS_KEY);
METRICS.put(NEW_INFO_VIOLATIONS_KEY, INFO_VIOLATIONS_KEY);
// issue types
METRICS.put(NEW_BUGS_KEY, BUGS_KEY);
METRICS.put(NEW_CODE_SMELLS_KEY, CODE_SMELLS_KEY);
METRICS.put(NEW_VULNERABILITIES_KEY, VULNERABILITIES_KEY);
// ratings
METRICS.put(NEW_SECURITY_RATING_KEY, SECURITY_RATING_KEY);
METRICS.put(NEW_RELIABILITY_RATING_KEY, RELIABILITY_RATING_KEY);
// effort
METRICS.put(NEW_TECHNICAL_DEBT_KEY, TECHNICAL_DEBT_KEY);
METRICS.put(NEW_SECURITY_REMEDIATION_EFFORT_KEY, SECURITY_REMEDIATION_EFFORT_KEY);
METRICS.put(NEW_RELIABILITY_REMEDIATION_EFFORT_KEY, RELIABILITY_REMEDIATION_EFFORT_KEY);
}
private PrMeasureFix() {
// static only
}
static void addReplacementMetricKeys(Collection<String> metricKeys) {
Set<String> keysToAdd = metricKeys.stream()
.filter(METRICS::containsKey)
.map(METRICS::get)
.collect(Collectors.toSet());
metricKeys.addAll(keysToAdd);
}
static void removeMetricsNotRequested(List<MetricDto> metrics, Set<String> requestedMetricKeys) {
metrics.removeIf(m -> !requestedMetricKeys.contains(m.getKey()));
}
static void createReplacementMeasures(List<MetricDto> metrics, Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric,
Set<String> requestedMetricKeys) {
Map<String, MetricDto> metricByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
for (MetricDto metric : measuresByComponentUuidAndMetric.columnKeySet()) {
Map<String, ComponentTreeData.Measure> newEntries = new HashMap<>();
String originalKey = METRICS.inverse().get(metric.getKey());
if (originalKey != null && requestedMetricKeys.contains(originalKey)) {
for (Map.Entry<String, ComponentTreeData.Measure> e : measuresByComponentUuidAndMetric.column(metric).entrySet()) {
newEntries.put(e.getKey(), e.getValue());
}
MetricDto originalMetric = metricByKey.get(originalKey);
newEntries.forEach((k, v) -> measuresByComponentUuidAndMetric.put(k, originalMetric, v));
}
}
List<MetricDto> toRemove = measuresByComponentUuidAndMetric.columnKeySet().stream().filter(m -> !requestedMetricKeys.contains(m.getKey())).toList();
measuresByComponentUuidAndMetric.columnKeySet().removeAll(toRemove);
}
static void createReplacementMeasures(List<MetricDto> metrics, Map<MetricDto, LiveMeasureDto> measuresByMetric, Set<String> requestedMetricKeys) {
Map<String, MetricDto> metricByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
Map<MetricDto, LiveMeasureDto> newEntries = new HashMap<>();
for (Map.Entry<MetricDto, LiveMeasureDto> e : measuresByMetric.entrySet()) {
String originalKey = METRICS.inverse().get(e.getKey().getKey());
if (originalKey != null && requestedMetricKeys.contains(originalKey)) {
MetricDto metricDto = metricByKey.get(originalKey);
newEntries.put(metricDto, copyMeasure(e.getValue(), metricDto.getUuid()));
}
}
measuresByMetric.entrySet().removeIf(e -> !requestedMetricKeys.contains(e.getKey().getKey()));
measuresByMetric.putAll(newEntries);
}
private static LiveMeasureDto copyMeasure(LiveMeasureDto dto, String metricUuid) {
LiveMeasureDto copy = new LiveMeasureDto();
copy.setValue(dto.getValue());
copy.setProjectUuid(dto.getProjectUuid());
copy.setComponentUuid(dto.getComponentUuid());
copy.setMetricUuid(metricUuid);
return copy;
}
}
| 7,335 | 44.283951 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/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.measure.ws;
import com.google.common.collect.ImmutableSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
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.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Measures.Measure;
import org.sonarqube.ws.Measures.SearchWsResponse;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Comparator.comparing;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.SUBVIEW;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_KEYS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PROJECT_KEYS;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.measure.ws.MeasureDtoToWsMeasure.updateMeasureBuilder;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createMetricKeysParameter;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements MeasuresWsAction {
private static final int MAX_NB_PROJECTS = 100;
private static final Set<String> ALLOWED_QUALIFIERS = ImmutableSet.of(PROJECT, APP, VIEW, SUBVIEW);
private final UserSession userSession;
private final DbClient dbClient;
public SearchAction(UserSession userSession, DbClient dbClient) {
this.userSession = userSession;
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("search")
.setInternal(true)
.setDescription("Search for project measures ordered by project names.<br>" +
"At most %d projects can be provided.<br>" +
"Returns the projects with the 'Browse' permission.",
MAX_NB_PROJECTS)
.setSince("6.2")
.setResponseExample(getClass().getResource("search-example.json"))
.setHandler(this)
.setChangelog(
new Change("10.0", format("The use of the following metrics in 'metricKeys' parameter is not deprecated anymore: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("9.3", format("The use of the following metrics in 'metricKeys' parameter is deprecated: %s",
MeasuresWsModule.getDeprecatedMetrics())));
createMetricKeysParameter(action);
action.createParam(PARAM_PROJECT_KEYS)
.setDescription("Comma-separated list of project, view or sub-view keys")
.setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002))
.setRequired(true);
}
@Override
public void handle(Request httpRequest, Response httpResponse) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
SearchWsResponse response = new ResponseBuilder(httpRequest, dbSession).build();
writeProtobuf(response, httpRequest, httpResponse);
}
}
private class ResponseBuilder {
private final DbSession dbSession;
private final Request httpRequest;
private SearchRequest request;
private List<ComponentDto> projects;
private List<MetricDto> metrics;
private List<LiveMeasureDto> measures;
ResponseBuilder(Request httpRequest, DbSession dbSession) {
this.dbSession = dbSession;
this.httpRequest = httpRequest;
}
SearchWsResponse build() {
this.request = createRequest();
this.projects = searchProjects();
this.metrics = searchMetrics();
this.measures = searchMeasures();
return buildResponse();
}
private SearchRequest createRequest() {
request = SearchRequest.builder()
.setMetricKeys(httpRequest.mandatoryParamAsStrings(PARAM_METRIC_KEYS))
.setProjectKeys(httpRequest.paramAsStrings(PARAM_PROJECT_KEYS))
.build();
return request;
}
private List<ComponentDto> searchProjects() {
List<ComponentDto> componentDtos = searchByProjectKeys(dbSession, request.getProjectKeys());
checkArgument(ALLOWED_QUALIFIERS.containsAll(componentDtos.stream().map(ComponentDto::qualifier).collect(Collectors.toSet())),
"Only component of qualifiers %s are allowed", ALLOWED_QUALIFIERS);
return getAuthorizedProjects(componentDtos);
}
private List<ComponentDto> searchByProjectKeys(DbSession dbSession, List<String> projectKeys) {
return dbClient.componentDao().selectByKeys(dbSession, projectKeys);
}
private List<ComponentDto> getAuthorizedProjects(List<ComponentDto> componentDtos) {
return userSession.keepAuthorizedComponents(UserRole.USER, componentDtos);
}
private List<MetricDto> searchMetrics() {
List<MetricDto> dbMetrics = dbClient.metricDao().selectByKeys(dbSession, request.getMetricKeys());
List<String> metricKeys = dbMetrics.stream().map(MetricDto::getKey).toList();
checkRequest(request.getMetricKeys().size() == dbMetrics.size(), "The following metrics are not found: %s",
String.join(", ", difference(request.getMetricKeys(), metricKeys)));
return dbMetrics;
}
private List<String> difference(Collection<String> expected, Collection<String> actual) {
Set<String> actualSet = new HashSet<>(actual);
return expected.stream()
.filter(value -> !actualSet.contains(value))
.sorted(String::compareTo)
.toList();
}
private List<LiveMeasureDto> searchMeasures() {
return dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession,
projects.stream().map(ComponentDto::uuid).toList(),
metrics.stream().map(MetricDto::getUuid).toList());
}
private SearchWsResponse buildResponse() {
List<Measure> wsMeasures = buildWsMeasures();
return SearchWsResponse.newBuilder()
.addAllMeasures(wsMeasures)
.build();
}
private List<Measure> buildWsMeasures() {
Map<String, ComponentDto> componentsByUuid = projects.stream().collect(toMap(ComponentDto::uuid, Function.identity()));
Map<String, String> componentNamesByKey = projects.stream().collect(toMap(ComponentDto::getKey, ComponentDto::name));
Map<String, MetricDto> metricsByUuid = metrics.stream().collect(toMap(MetricDto::getUuid, identity()));
Function<LiveMeasureDto, MetricDto> dbMeasureToDbMetric = dbMeasure -> metricsByUuid.get(dbMeasure.getMetricUuid());
Function<Measure, String> byMetricKey = Measure::getMetric;
Function<Measure, String> byComponentName = wsMeasure -> componentNamesByKey.get(wsMeasure.getComponent());
Measure.Builder measureBuilder = Measure.newBuilder();
return measures.stream()
.map(dbMeasure -> {
updateMeasureBuilder(measureBuilder, dbMeasureToDbMetric.apply(dbMeasure), dbMeasure);
measureBuilder.setComponent(componentsByUuid.get(dbMeasure.getComponentUuid()).getKey());
Measure measure = measureBuilder.build();
measureBuilder.clear();
return measure;
})
.sorted(comparing(byMetricKey).thenComparing(byComponentName))
.toList();
}
}
private static class SearchRequest {
private final List<String> metricKeys;
private final List<String> projectKeys;
public SearchRequest(Builder builder) {
metricKeys = builder.metricKeys;
projectKeys = builder.projectKeys;
}
public List<String> getMetricKeys() {
return metricKeys;
}
public List<String> getProjectKeys() {
return projectKeys;
}
public static Builder builder() {
return new Builder();
}
}
private static class Builder {
private List<String> metricKeys;
private List<String> projectKeys;
private Builder() {
// enforce method constructor
}
public Builder setMetricKeys(List<String> metricKeys) {
this.metricKeys = metricKeys;
return this;
}
public Builder setProjectKeys(List<String> projectKeys) {
this.projectKeys = projectKeys;
return this;
}
public SearchAction.SearchRequest build() {
checkArgument(metricKeys != null && !metricKeys.isEmpty(), "Metric keys must be provided");
checkArgument(projectKeys != null && !projectKeys.isEmpty(), "Project keys must be provided");
int nbComponents = projectKeys.size();
checkArgument(nbComponents <= MAX_NB_PROJECTS,
"%s projects provided, more than maximum authorized (%s)", nbComponents, MAX_NB_PROJECTS);
return new SearchAction.SearchRequest(this);
}
}
}
| 10,229 | 38.651163 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/SearchHistoryAction.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.measure.ws;
import com.google.common.collect.Sets;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
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.Param;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotQuery;
import org.sonar.db.component.SnapshotQuery.SORT_FIELD;
import org.sonar.db.component.SnapshotQuery.SORT_ORDER;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.measure.PastMeasureQuery;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.KeyExamples;
import org.sonarqube.ws.Measures.SearchHistoryResponse;
import static java.lang.String.format;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.server.component.ws.MeasuresWsParameters.ACTION_SEARCH_HISTORY;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_COMPONENT;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_FROM;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRICS;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST;
import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_TO;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchHistoryAction implements MeasuresWsAction {
private static final int MAX_PAGE_SIZE = 1_000;
private static final int DEFAULT_PAGE_SIZE = 100;
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
public SearchHistoryAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_SEARCH_HISTORY)
.setDescription("Search measures history of a component.<br>" +
"Measures are ordered chronologically.<br>" +
"Pagination applies to the number of measures for each metric.<br>" +
"Requires the following permission: 'Browse' on the specified component. <br>" +
"For applications, it also requires 'Browse' permission on its child projects.")
.setResponseExample(getClass().getResource("search_history-example.json"))
.setSince("6.3")
.setChangelog(
new Change("10.0", format("The use of the following metrics in 'metricKeys' parameter is not deprecated anymore: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("9.3", format("The use of the following metrics in 'metrics' parameter is deprecated: %s",
MeasuresWsModule.getDeprecatedMetrics())),
new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT)))
.setHandler(this);
action.createParam(PARAM_COMPONENT)
.setDescription("Component key")
.setRequired(true)
.setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setDescription("Branch key. Not available in the community edition.")
.setSince("6.6")
.setExampleValue(KEY_BRANCH_EXAMPLE_001);
action.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id. Not available in the community edition.")
.setSince("7.1")
.setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001);
action.createParam(PARAM_METRICS)
.setDescription("Comma-separated list of metric keys")
.setRequired(true)
.setExampleValue("ncloc,coverage,new_violations");
action.createParam(PARAM_FROM)
.setDescription("Filter measures created after the given date (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_TO)
.setDescription("Filter measures created before the given date (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchHistoryResponse searchHistoryResponse = Optional.of(request)
.map(SearchHistoryAction::toWsRequest)
.map(search())
.map(result -> new SearchHistoryResponseFactory(result).apply())
.orElseThrow();
writeProtobuf(searchHistoryResponse, request, response);
}
private static SearchHistoryRequest toWsRequest(Request request) {
return SearchHistoryRequest.builder()
.setComponent(request.mandatoryParam(PARAM_COMPONENT))
.setBranch(request.param(PARAM_BRANCH))
.setPullRequest(request.param(PARAM_PULL_REQUEST))
.setMetrics(request.mandatoryParamAsStrings(PARAM_METRICS))
.setFrom(request.param(PARAM_FROM))
.setTo(request.param(PARAM_TO))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.build();
}
private Function<SearchHistoryRequest, SearchHistoryResult> search() {
return request -> {
try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto component = searchComponent(request, dbSession);
SearchHistoryResult result = new SearchHistoryResult(request.page, request.pageSize)
.setComponent(component)
.setAnalyses(searchAnalyses(dbSession, request, component))
.setMetrics(searchMetrics(dbSession, request));
return result.setMeasures(searchMeasures(dbSession, request, result));
}
};
}
private ComponentDto searchComponent(SearchHistoryRequest request, DbSession dbSession) {
ComponentDto component = loadComponent(dbSession, request);
userSession.checkComponentPermission(UserRole.USER, component);
if (Scopes.PROJECT.equals(component.scope()) && Qualifiers.APP.equals(component.qualifier())) {
userSession.checkChildProjectsPermission(UserRole.USER, component);
}
return component;
}
private List<MeasureDto> searchMeasures(DbSession dbSession, SearchHistoryRequest request, SearchHistoryResult result) {
Date from = parseStartingDateOrDateTime(request.getFrom());
Date to = parseEndingDateOrDateTime(request.getTo());
PastMeasureQuery dbQuery = new PastMeasureQuery(
result.getComponent().uuid(),
result.getMetrics().stream().map(MetricDto::getUuid).toList(),
from == null ? null : from.getTime(),
to == null ? null : (to.getTime() + 1_000L));
return dbClient.measureDao().selectPastMeasures(dbSession, dbQuery);
}
private List<SnapshotDto> searchAnalyses(DbSession dbSession, SearchHistoryRequest request, ComponentDto component) {
SnapshotQuery dbQuery = new SnapshotQuery()
.setRootComponentUuid(component.branchUuid())
.setStatus(STATUS_PROCESSED)
.setSort(SORT_FIELD.BY_DATE, SORT_ORDER.ASC);
ofNullable(request.getFrom()).ifPresent(from -> dbQuery.setCreatedAfter(parseStartingDateOrDateTime(from).getTime()));
ofNullable(request.getTo()).ifPresent(to -> dbQuery.setCreatedBefore(parseEndingDateOrDateTime(to).getTime() + 1_000L));
return dbClient.snapshotDao().selectAnalysesByQuery(dbSession, dbQuery);
}
private List<MetricDto> searchMetrics(DbSession dbSession, SearchHistoryRequest request) {
List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, request.getMetrics());
if (request.getMetrics().size() > metrics.size()) {
Set<String> requestedMetrics = request.getMetrics().stream().collect(Collectors.toSet());
Set<String> foundMetrics = metrics.stream().map(MetricDto::getKey).collect(Collectors.toSet());
Set<String> unfoundMetrics = Sets.difference(requestedMetrics, foundMetrics).immutableCopy();
throw new IllegalArgumentException(format("Metrics %s are not found", String.join(", ", unfoundMetrics)));
}
return metrics;
}
private ComponentDto loadComponent(DbSession dbSession, SearchHistoryRequest request) {
String componentKey = request.getComponent();
String branch = request.getBranch();
String pullRequest = request.getPullRequest();
return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest);
}
static class SearchHistoryRequest {
private final String component;
private final String branch;
private final String pullRequest;
private final List<String> metrics;
private final String from;
private final String to;
private final int page;
private final int pageSize;
public SearchHistoryRequest(Builder builder) {
this.component = builder.component;
this.branch = builder.branch;
this.pullRequest = builder.pullRequest;
this.metrics = builder.metrics;
this.from = builder.from;
this.to = builder.to;
this.page = builder.page;
this.pageSize = builder.pageSize;
}
public String getComponent() {
return component;
}
@CheckForNull
public String getBranch() {
return branch;
}
@CheckForNull
public String getPullRequest() {
return pullRequest;
}
public List<String> getMetrics() {
return metrics;
}
@CheckForNull
public String getFrom() {
return from;
}
@CheckForNull
public String getTo() {
return to;
}
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
public static Builder builder() {
return new Builder();
}
}
static class Builder {
private String component;
private String branch;
private String pullRequest;
private List<String> metrics;
private String from;
private String to;
private int page = 1;
private int pageSize = DEFAULT_PAGE_SIZE;
private Builder() {
// enforce build factory method
}
public Builder setComponent(String component) {
this.component = component;
return this;
}
public Builder setBranch(@Nullable String branch) {
this.branch = branch;
return this;
}
public Builder setPullRequest(@Nullable String pullRequest) {
this.pullRequest = pullRequest;
return this;
}
public Builder setMetrics(List<String> metrics) {
this.metrics = metrics;
return this;
}
public Builder setFrom(@Nullable String from) {
this.from = from;
return this;
}
public Builder setTo(@Nullable String to) {
this.to = to;
return this;
}
public Builder setPage(int page) {
this.page = page;
return this;
}
public Builder setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public SearchHistoryRequest build() {
checkArgument(component != null && !component.isEmpty(), "Component key is required");
checkArgument(metrics != null && !metrics.isEmpty(), "Metric keys are required");
checkArgument(pageSize <= MAX_PAGE_SIZE, "Page size (%d) must be lower than or equal to %d", pageSize, MAX_PAGE_SIZE);
return new SearchHistoryRequest(this);
}
private static void checkArgument(boolean condition, String message, Object... args) {
if (!condition) {
throw new IllegalArgumentException(format(message, args));
}
}
}
}
| 13,453 | 36.792135 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/SearchHistoryResponseFactory.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.measure.ws;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Measures.SearchHistoryResponse;
import org.sonarqube.ws.Measures.SearchHistoryResponse.HistoryMeasure;
import org.sonarqube.ws.Measures.SearchHistoryResponse.HistoryValue;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.measure.ws.MeasureValueFormatter.formatMeasureValue;
class SearchHistoryResponseFactory {
private final SearchHistoryResult result;
private final HistoryMeasure.Builder measure;
private final HistoryValue.Builder value;
SearchHistoryResponseFactory(SearchHistoryResult result) {
this.result = result;
this.measure = HistoryMeasure.newBuilder();
this.value = HistoryValue.newBuilder();
}
public SearchHistoryResponse apply() {
return Optional.of(SearchHistoryResponse.newBuilder())
.map(addPaging())
.map(addMeasures())
.map(SearchHistoryResponse.Builder::build)
.orElseThrow();
}
private UnaryOperator<SearchHistoryResponse.Builder> addPaging() {
return response -> response.setPaging(result.getPaging());
}
private UnaryOperator<SearchHistoryResponse.Builder> addMeasures() {
Map<String, MetricDto> metricsByUuid = result.getMetrics().stream().collect(Collectors.toMap(MetricDto::getUuid, Function.identity()));
Map<String, SnapshotDto> analysesByUuid = result.getAnalyses().stream().collect(Collectors.toMap(SnapshotDto::getUuid, Function.identity()));
Table<MetricDto, SnapshotDto, MeasureDto> measuresByMetricByAnalysis = HashBasedTable.create(result.getMetrics().size(), result.getAnalyses().size());
result.getMeasures().forEach(m -> measuresByMetricByAnalysis.put(metricsByUuid.get(m.getMetricUuid()), analysesByUuid.get(m.getAnalysisUuid()), m));
return response -> {
result.getMetrics().stream()
.map(clearMetric())
.map(addMetric())
.map(metric -> addValues(measuresByMetricByAnalysis.row(metric)).apply(metric))
.forEach(metric -> response.addMeasures(measure));
return response;
};
}
private UnaryOperator<MetricDto> addMetric() {
return metric -> {
measure.setMetric(metric.getKey());
return metric;
};
}
private UnaryOperator<MetricDto> addValues(Map<SnapshotDto, MeasureDto> measuresByAnalysis) {
return metric -> {
result.getAnalyses().stream()
.map(clearValue())
.map(addDate())
.map(analysis -> addValue(analysis, metric, measuresByAnalysis.get(analysis)))
.forEach(analysis -> measure.addHistory(value));
return metric;
};
}
private UnaryOperator<SnapshotDto> addDate() {
return analysis -> {
value.setDate(formatDateTime(analysis.getCreatedAt()));
return analysis;
};
}
private SnapshotDto addValue(SnapshotDto analysis, MetricDto dbMetric, @Nullable MeasureDto dbMeasure) {
if (dbMeasure != null) {
String measureValue = formatMeasureValue(dbMeasure, dbMetric);
if (measureValue != null) {
value.setValue(measureValue);
}
}
return analysis;
}
private UnaryOperator<MetricDto> clearMetric() {
return metric -> {
measure.clear();
return metric;
};
}
private UnaryOperator<SnapshotDto> clearValue() {
return analysis -> {
value.clear();
return analysis;
};
}
}
| 4,597 | 34.099237 | 154 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/SearchHistoryResult.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.measure.ws;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Table;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonarqube.ws.Common;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Paging.offset;
import static org.sonar.db.metric.MetricDtoFunctions.isOptimizedForBestValue;
import static org.sonar.server.measure.ws.MetricDtoWithBestValue.isEligibleForBestValue;
public class SearchHistoryResult {
private final int page;
private final int pageSize;
private List<SnapshotDto> analyses;
private List<MetricDto> metrics;
private List<MeasureDto> measures;
private Common.Paging paging;
private ComponentDto component;
public SearchHistoryResult(int page, int pageSize) {
this.page = page;
this.pageSize = pageSize;
}
public ComponentDto getComponent() {
return requireNonNull(component);
}
public SearchHistoryResult setComponent(ComponentDto component) {
this.component = component;
return this;
}
public List<SnapshotDto> getAnalyses() {
return requireNonNull(analyses);
}
public SearchHistoryResult setAnalyses(List<SnapshotDto> analyses) {
this.paging = Common.Paging.newBuilder().setPageIndex(page).setPageSize(pageSize).setTotal(analyses.size()).build();
this.analyses = analyses.stream().skip(offset(page, pageSize)).limit(pageSize).toList();
return this;
}
public List<MetricDto> getMetrics() {
return requireNonNull(metrics);
}
public SearchHistoryResult setMetrics(List<MetricDto> metrics) {
this.metrics = metrics;
return this;
}
public List<MeasureDto> getMeasures() {
return requireNonNull(measures);
}
public SearchHistoryResult setMeasures(List<MeasureDto> measures) {
Set<String> analysisUuids = analyses.stream().map(SnapshotDto::getUuid).collect(Collectors.toSet());
ImmutableList.Builder<MeasureDto> measuresBuilder = ImmutableList.builder();
List<MeasureDto> filteredMeasures = measures.stream()
.filter(measure -> analysisUuids.contains(measure.getAnalysisUuid()))
.toList();
measuresBuilder.addAll(filteredMeasures);
measuresBuilder.addAll(computeBestValues(filteredMeasures));
this.measures = measuresBuilder.build();
return this;
}
/**
* Conditions for best value measure:
* <ul>
* <li>component is a production file or test file</li>
* <li>metric is optimized for best value</li>
* </ul>
*/
private List<MeasureDto> computeBestValues(List<MeasureDto> measures) {
if (!isEligibleForBestValue().test(component)) {
return emptyList();
}
requireNonNull(metrics);
requireNonNull(analyses);
Table<String, String, MeasureDto> measuresByMetricUuidAndAnalysisUuid = HashBasedTable.create(metrics.size(), analyses.size());
measures.forEach(measure -> measuresByMetricUuidAndAnalysisUuid.put(measure.getMetricUuid(), measure.getAnalysisUuid(), measure));
List<MeasureDto> bestValues = new ArrayList<>();
metrics.stream()
.filter(isOptimizedForBestValue())
.forEach(metric -> analyses.stream()
.filter(analysis -> !measuresByMetricUuidAndAnalysisUuid.contains(metric.getUuid(), analysis.getUuid()))
.map(analysis -> toBestValue(metric, analysis))
.forEach(bestValues::add));
return bestValues;
}
private static MeasureDto toBestValue(MetricDto metric, SnapshotDto analysis) {
return new MeasureDto()
.setMetricUuid(metric.getUuid())
.setAnalysisUuid(analysis.getUuid())
.setValue(metric.getBestValue());
}
Common.Paging getPaging() {
return requireNonNull(paging);
}
}
| 4,851 | 33.169014 | 134 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/ws/SnapshotDtoToWsPeriod.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.measure.ws;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.db.component.SnapshotDto;
import org.sonarqube.ws.Measures;
import static org.sonar.api.utils.DateUtils.formatDateTime;
class SnapshotDtoToWsPeriod {
private SnapshotDtoToWsPeriod() {
// prevent instantiation
}
static Optional<Measures.Period> snapshotToWsPeriods(@Nullable SnapshotDto snapshot) {
if (snapshot == null || snapshot.getPeriodMode() == null) {
return Optional.empty();
}
return Optional.of(snapshotDtoToWsPeriod(snapshot));
}
private static Measures.Period snapshotDtoToWsPeriod(SnapshotDto snapshot) {
Measures.Period.Builder period = Measures.Period.newBuilder();
period.setIndex(1);
String periodMode = snapshot.getPeriodMode();
if (periodMode != null) {
period.setMode(periodMode);
}
String periodModeParameter = snapshot.getPeriodModeParameter();
if (periodModeParameter != null) {
period.setParameter(periodModeParameter);
}
Long periodDate = snapshot.getPeriodDate();
if (periodDate != null) {
period.setDate(formatDateTime(periodDate));
}
return period.build();
}
}
| 2,052 | 33.216667 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/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.measure.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/ws/MetricJsonWriter.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.metric.ws;
import java.util.List;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.metric.MetricDto;
public class MetricJsonWriter {
public static final String FIELD_ID = "id";
public static final String FIELD_KEY = "key";
public static final String FIELD_NAME = "name";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_DOMAIN = "domain";
public static final String FIELD_TYPE = "type";
public static final String FIELD_DIRECTION = "direction";
public static final String FIELD_QUALITATIVE = "qualitative";
public static final String FIELD_HIDDEN = "hidden";
public static final String FIELD_DECIMAL_SCALE = "decimalScale";
private MetricJsonWriter() {
// static stuff only for the time being
}
public static void write(JsonWriter json, List<MetricDto> metrics) {
json.name("metrics");
json.beginArray();
for (MetricDto metric : metrics) {
write(json, metric);
}
json.endArray();
}
public static void write(JsonWriter json, MetricDto metric) {
json.beginObject();
json.prop(FIELD_ID, String.valueOf(metric.getUuid()));
json.prop(FIELD_KEY, metric.getKey());
json.prop(FIELD_TYPE, metric.getValueType());
json.prop(FIELD_NAME, metric.getShortName());
json.prop(FIELD_DESCRIPTION, metric.getDescription());
json.prop(FIELD_DOMAIN, metric.getDomain());
json.prop(FIELD_DIRECTION, metric.getDirection());
json.prop(FIELD_QUALITATIVE, metric.isQualitative());
json.prop(FIELD_HIDDEN, metric.isHidden());
json.prop(FIELD_DECIMAL_SCALE, metric.getDecimalScale());
json.endObject();
}
}
| 2,523 | 37.242424 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/ws/MetricsWs.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.metric.ws;
import org.sonar.api.server.ws.WebService;
public class MetricsWs implements WebService {
public static final String ENDPOINT = "api/metrics";
private final MetricsWsAction[] actions;
public MetricsWs(MetricsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(ENDPOINT);
controller.setDescription("Get information on automatic metrics");
controller.setSince("2.6");
for (MetricsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,491 | 30.744681 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/ws/MetricsWsAction.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.metric.ws;
import org.sonar.server.ws.WsAction;
public interface MetricsWsAction extends WsAction {
// marker interface
}
| 994 | 35.851852 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/ws/MetricsWsModule.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.metric.ws;
import org.sonar.core.platform.Module;
public class MetricsWsModule extends Module {
@Override
protected void configureModule() {
add(
MetricsWs.class,
SearchAction.class,
TypesAction.class);
}
}
| 1,105 | 32.515152 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/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.metric.ws;
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.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.es.SearchOptions;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
public class SearchAction implements MetricsWsAction {
private static final String ACTION = "search";
private final DbClient dbClient;
public SearchAction(DbClient dbClient) {
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController context) {
context.createAction(ACTION)
.setSince("5.2")
.setDescription("Search for metrics")
.setResponseExample(getClass().getResource("example-search.json"))
.addPagingParams(100, MAX_PAGE_SIZE)
.setChangelog(
new Change("8.4", "Field 'id' in the response is deprecated"))
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchOptions searchOptions = new SearchOptions()
.setPage(request.mandatoryParamAsInt(Param.PAGE),
request.mandatoryParamAsInt(Param.PAGE_SIZE));
try (DbSession dbSession = dbClient.openSession(false)) {
List<MetricDto> metrics = dbClient.metricDao().selectEnabled(dbSession, searchOptions.getOffset(), searchOptions.getLimit());
int nbMetrics = dbClient.metricDao().countEnabled(dbSession);
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
MetricJsonWriter.write(json, metrics);
searchOptions.writeJson(json, nbMetrics);
json.endObject();
}
}
}
}
| 2,735 | 35.48 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/ws/TypesAction.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.metric.ws;
import org.sonar.api.measures.Metric;
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;
public class TypesAction implements MetricsWsAction {
@Override
public void define(WebService.NewController context) {
context.createAction("types")
.setDescription("List all available metric types.")
.setResponseExample(getClass().getResource("example-types.json"))
.setSince("5.2")
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
JsonWriter json = response.newJsonWriter();
json.beginObject();
json.name("types");
json.beginArray();
for (Metric.ValueType metricType : Metric.ValueType.values()) {
json.value(metricType.name());
}
json.endArray();
json.endObject();
json.close();
}
}
| 1,812 | 33.865385 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/metric/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.metric.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 39.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/monitoring/MetricsAction.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.monitoring;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.platform.ws.SafeModeMonitoringMetricAction;
import org.sonar.server.user.BearerPasscode;
import org.sonar.server.user.SystemPasscode;
import org.sonar.server.user.UserSession;
public class MetricsAction extends SafeModeMonitoringMetricAction {
private final UserSession userSession;
public MetricsAction(SystemPasscode systemPasscode, BearerPasscode bearerPasscode, UserSession userSession) {
super(systemPasscode, bearerPasscode);
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
context.createAction("metrics")
.setSince("9.3")
.setDescription("""
Return monitoring metrics in Prometheus format.\s
Support content type 'text/plain' (default) and 'application/openmetrics-text'.
this endpoint can be access using a Bearer token, that needs to be defined in sonar.properties with the 'sonar.web.systemPasscode' key.""")
.setResponseExample(getClass().getResource("monitoring-metrics.txt"))
.setHandler(this);
isWebUpGauge.set(1D);
}
@Override
public boolean isSystemAdmin() {
return userSession.isSystemAdministrator();
}
}
| 2,115 | 36.122807 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/monitoring/MonitoringWs.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.monitoring;
import org.sonar.api.server.ws.WebService;
public class MonitoringWs implements WebService {
private final MonitoringWsAction[] actions;
public MonitoringWs(MonitoringWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/monitoring")
.setDescription("Monitoring")
.setSince("9.3");
for (MonitoringWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,414 | 31.159091 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/monitoring/MonitoringWsAction.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.monitoring;
import org.sonar.server.ws.WsAction;
public interface MonitoringWsAction extends WsAction {
}
| 977 | 35.222222 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/monitoring/MonitoringWsModule.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.monitoring;
import org.sonar.core.platform.Module;
import org.sonar.server.user.BearerPasscode;
public class MonitoringWsModule extends Module {
public MonitoringWsModule() {
// nothing to do
}
@Override
protected void configureModule() {
add(
BearerPasscode.class,
MonitoringWs.class,
MetricsAction.class);
}
}
| 1,220 | 30.307692 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/monitoring/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.monitoring;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/CaycUtils.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.newcodeperiod;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
public interface CaycUtils {
static boolean isNewCodePeriodCompliant(NewCodePeriodType type, String value) {
if (type == NewCodePeriodType.NUMBER_OF_DAYS) {
return parseDays(value) > 0 && parseDays(value) <= 90;
}
return true;
}
static int parseDays(String value) {
try {
return Integer.parseInt(value);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse number of days: " + value);
}
}
}
| 1,403 | 34.1 | 85 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/NewCodeDefinitionResolver.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.newcodeperiod;
import com.google.common.base.Preconditions;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodParser;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
public class NewCodeDefinitionResolver {
private static final String BEGIN_LIST = "<ul>";
private static final String END_LIST = "</ul>";
private static final String BEGIN_ITEM_LIST = "<li>";
private static final String END_ITEM_LIST = "</li>";
public static final String NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION = "Project New Code Definition Type<br/>" +
"New code definitions of the following types are allowed:" +
BEGIN_LIST +
BEGIN_ITEM_LIST + PREVIOUS_VERSION.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + NUMBER_OF_DAYS.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + REFERENCE_BRANCH.name() + " - will default to the main branch." + END_ITEM_LIST +
END_LIST;
public static final String NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION = "Project New Code Definition Value<br/>" +
"For each new code definition type, a different value is expected:" +
BEGIN_LIST +
BEGIN_ITEM_LIST + "no value, when the new code definition type is " + PREVIOUS_VERSION.name() + " and " + REFERENCE_BRANCH.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + "a number between 1 and 90, when the new code definition type is " + NUMBER_OF_DAYS.name() + END_ITEM_LIST +
END_LIST;
private static final String UNEXPECTED_VALUE_ERROR_MESSAGE = "Unexpected value for newCodeDefinitionType '%s'";
private static final EnumSet<NewCodePeriodType> projectCreationNCDTypes = EnumSet.of(PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH);
private final DbClient dbClient;
private final PlatformEditionProvider editionProvider;
public NewCodeDefinitionResolver(DbClient dbClient, PlatformEditionProvider editionProvider) {
this.dbClient = dbClient;
this.editionProvider = editionProvider;
}
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String defaultBranchName, String newCodeDefinitionType, String newCodeDefinitionValue) {
boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent();
NewCodePeriodType newCodePeriodType = parseNewCodeDefinitionType(newCodeDefinitionType);
NewCodePeriodDto dto = new NewCodePeriodDto();
dto.setType(newCodePeriodType);
dto.setProjectUuid(projectUuid);
if (isCommunityEdition) {
dto.setBranchUuid(projectUuid);
}
getNewCodeDefinitionValueProjectCreation(newCodePeriodType, newCodeDefinitionValue, defaultBranchName).ifPresent(dto::setValue);
if (!CaycUtils.isNewCodePeriodCompliant(dto.getType(), dto.getValue())) {
throw new IllegalArgumentException("Failed to set the New Code Definition. The given value is not compatible with the Clean as You Code methodology. "
+ "Please refer to the documentation for compliant options.");
}
dbClient.newCodePeriodDao().insert(dbSession, dto);
}
public static void checkNewCodeDefinitionParam(@Nullable String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) {
if (newCodeDefinitionType == null && newCodeDefinitionValue != null) {
throw new IllegalArgumentException("New code definition type is required when new code definition value is provided");
}
}
private static Optional<String> getNewCodeDefinitionValueProjectCreation(NewCodePeriodType type, @Nullable String value, String defaultBranchName) {
return switch (type) {
case PREVIOUS_VERSION -> {
Preconditions.checkArgument(value == null, UNEXPECTED_VALUE_ERROR_MESSAGE, type);
yield Optional.empty();
}
case NUMBER_OF_DAYS -> {
requireValue(type, value);
yield Optional.of(parseDays(value));
}
case REFERENCE_BRANCH -> {
Preconditions.checkArgument(value == null, UNEXPECTED_VALUE_ERROR_MESSAGE, type);
yield Optional.of(defaultBranchName);
}
default -> throw new IllegalStateException("Unexpected type: " + type);
};
}
private static String parseDays(String value) {
try {
return Integer.toString(NewCodePeriodParser.parseDays(value));
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse number of days: " + value);
}
}
private static void requireValue(NewCodePeriodType type, @Nullable String value) {
Preconditions.checkArgument(value != null, "New code definition type '%s' requires a newCodeDefinitionValue", type);
}
private static NewCodePeriodType parseNewCodeDefinitionType(String typeStr) {
NewCodePeriodType type;
try {
type = NewCodePeriodType.valueOf(typeStr.toUpperCase(Locale.US));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid type: " + typeStr);
}
validateType(type);
return type;
}
private static void validateType(NewCodePeriodType type) {
Preconditions.checkArgument(projectCreationNCDTypes.contains(type), "Invalid type '%s'. `newCodeDefinitionType` can only be set with types: %s",
type, projectCreationNCDTypes);
}
}
| 6,575 | 43.134228 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/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.newcodeperiod;
import javax.annotation.ParametersAreNonnullByDefault;
| 970 | 39.458333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/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.newcodeperiod.ws;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
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.DateUtils;
import org.sonar.api.web.UserRole;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.NewCodePeriods;
import org.sonarqube.ws.NewCodePeriods.ListWSResponse;
import static org.sonar.server.ws.WsUtils.createHtmlExternalLink;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.NewCodePeriods.ShowWSResponse.newBuilder;
public class ListAction implements NewCodePeriodsWsAction {
private static final String PARAM_PROJECT = "project";
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final NewCodePeriodDao newCodePeriodDao;
private final String newCodeDefinitionDocumentationUrl;
public ListAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, NewCodePeriodDao newCodePeriodDao,
DocumentationLinkGenerator documentationLinkGenerator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.newCodePeriodDao = newCodePeriodDao;
this.newCodeDefinitionDocumentationUrl = documentationLinkGenerator.getDocumentationLink("/project-administration/defining-new-code/");
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("list")
.setDescription("Lists the " + createHtmlExternalLink(newCodeDefinitionDocumentationUrl, "new code definition") +
" for all branches in a project.<br>" +
"Requires the permission to browse the project")
.setSince("8.0")
.setResponseExample(getClass().getResource("list-example.json"))
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setRequired(true)
.setDescription("Project key");
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.mandatoryParam(PARAM_PROJECT);
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey);
userSession.checkEntityPermission(UserRole.USER, project);
Collection<BranchDto> branches = dbClient.branchDao().selectByProject(dbSession, project).stream()
.filter(b -> b.getBranchType() == BranchType.BRANCH)
.sorted(Comparator.comparing(BranchDto::getKey))
.toList();
List<NewCodePeriodDto> newCodePeriods = newCodePeriodDao.selectAllByProject(dbSession, project.getUuid());
Map<String, InheritedNewCodePeriod> newCodePeriodByBranchUuid = newCodePeriods
.stream()
.collect(Collectors.toMap(NewCodePeriodDto::getBranchUuid, dto -> new InheritedNewCodePeriod(dto, dto.getBranchUuid() == null)));
InheritedNewCodePeriod projectDefault = newCodePeriodByBranchUuid.getOrDefault(null, getGlobalOrDefault(dbSession));
Map<String, String> analysis = newCodePeriods.stream()
.filter(newCodePeriodDto -> newCodePeriodDto.getType().equals(NewCodePeriodType.SPECIFIC_ANALYSIS))
.collect(Collectors.toMap(NewCodePeriodDto::getUuid, NewCodePeriodDto::getValue));
Map<String, Long> analysisUuidDateMap = dbClient.snapshotDao().selectByUuids(dbSession, new HashSet<>(analysis.values()))
.stream()
.collect(Collectors.toMap(SnapshotDto::getUuid, SnapshotDto::getCreatedAt));
ListWSResponse.Builder builder = ListWSResponse.newBuilder();
for (BranchDto branch : branches) {
InheritedNewCodePeriod inherited = newCodePeriodByBranchUuid.getOrDefault(branch.getUuid(), projectDefault);
String effectiveValue = null;
//handles specific analysis only
Long analysisDate = analysisUuidDateMap.get(analysis.get(inherited.getUuid()));
if (analysisDate != null) {
effectiveValue = DateUtils.formatDateTime(analysisDate);
}
builder.addNewCodePeriods(
build(projectKey, branch.getKey(), inherited.getType(), inherited.getValue(), inherited.inherited, effectiveValue));
}
writeProtobuf(builder.build(), request, response);
}
}
private InheritedNewCodePeriod getGlobalOrDefault(DbSession dbSession) {
return newCodePeriodDao.selectGlobal(dbSession)
.map(dto -> new InheritedNewCodePeriod(dto, true))
.orElse(new InheritedNewCodePeriod(NewCodePeriodDto.defaultInstance(), true));
}
private static NewCodePeriods.ShowWSResponse build(String projectKey, String branchKey, NewCodePeriodType newCodePeriodType,
@Nullable String value, boolean inherited, @Nullable String effectiveValue) {
NewCodePeriods.ShowWSResponse.Builder builder = newBuilder()
.setType(convertType(newCodePeriodType))
.setInherited(inherited)
.setBranchKey(branchKey)
.setProjectKey(projectKey);
if (effectiveValue != null) {
builder.setEffectiveValue(effectiveValue);
}
if (value != null) {
builder.setValue(value);
}
return builder.build();
}
private static NewCodePeriods.NewCodePeriodType convertType(NewCodePeriodType type) {
switch (type) {
case NUMBER_OF_DAYS:
return NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS;
case PREVIOUS_VERSION:
return NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION;
case SPECIFIC_ANALYSIS:
return NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS;
case REFERENCE_BRANCH:
return NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH;
default:
throw new IllegalStateException("Unexpected type: " + type);
}
}
private static class InheritedNewCodePeriod {
NewCodePeriodDto newCodePeriod;
boolean inherited;
InheritedNewCodePeriod(NewCodePeriodDto newCodePeriod, boolean inherited) {
this.newCodePeriod = newCodePeriod;
this.inherited = inherited;
}
NewCodePeriodType getType() {
return newCodePeriod.getType();
}
String getValue() {
return newCodePeriod.getValue();
}
String getUuid() {
return newCodePeriod.getUuid();
}
}
}
| 7,827 | 38.938776 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWs.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.newcodeperiod.ws;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import static org.sonar.server.ws.WsUtils.createHtmlExternalLink;
public class NewCodePeriodsWs implements WebService {
private final NewCodePeriodsWsAction[] actions;
private final DocumentationLinkGenerator documentationLinkGenerator;
public NewCodePeriodsWs(DocumentationLinkGenerator documentationLinkGenerator, NewCodePeriodsWsAction... actions) {
this.actions = actions;
this.documentationLinkGenerator = documentationLinkGenerator;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/new_code_periods")
.setDescription("Manage "+ createHtmlExternalLink(documentationLinkGenerator.getDocumentationLink("/project-administration/defining-new-code/"), "new code definition") +".")
.setSince("8.0");
for (NewCodePeriodsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,912 | 38.854167 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsAction.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.newcodeperiod.ws;
import org.sonar.server.ws.WsAction;
public interface NewCodePeriodsWsAction extends WsAction {
// marker interface
}
| 1,008 | 36.37037 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsModule.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.newcodeperiod.ws;
import org.sonar.core.platform.Module;
public class NewCodePeriodsWsModule extends Module {
@Override
protected void configureModule() {
add(
NewCodePeriodsWs.class,
ShowAction.class,
SetAction.class,
UnsetAction.class,
ListAction.class);
}
}
| 1,171 | 32.485714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/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.newcodeperiod.ws;
import com.google.common.base.Preconditions;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Set;
import javax.annotation.Nullable;
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.documentation.DocumentationLinkGenerator;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
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.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodParser;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.newcodeperiod.CaycUtils;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.SPECIFIC_ANALYSIS;
import static org.sonar.server.ws.WsUtils.createHtmlExternalLink;
public class SetAction implements NewCodePeriodsWsAction {
private static final String PARAM_BRANCH = "branch";
private static final String PARAM_PROJECT = "project";
private static final String PARAM_TYPE = "type";
private static final String PARAM_VALUE = "value";
private static final String BEGIN_LIST = "<ul>";
private static final String END_LIST = "</ul>";
private static final String BEGIN_ITEM_LIST = "<li>";
private static final String END_ITEM_LIST = "</li>";
private static final Set<NewCodePeriodType> OVERALL_TYPES = EnumSet.of(PREVIOUS_VERSION, NUMBER_OF_DAYS);
private static final Set<NewCodePeriodType> PROJECT_TYPES = EnumSet.of(PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH);
private static final Set<NewCodePeriodType> BRANCH_TYPES = EnumSet.of(PREVIOUS_VERSION, NUMBER_OF_DAYS, SPECIFIC_ANALYSIS,
REFERENCE_BRANCH);
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final PlatformEditionProvider editionProvider;
private final NewCodePeriodDao newCodePeriodDao;
private final String newCodeDefinitionDocumentationUrl;
public SetAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, PlatformEditionProvider editionProvider,
NewCodePeriodDao newCodePeriodDao, DocumentationLinkGenerator documentationLinkGenerator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.editionProvider = editionProvider;
this.newCodePeriodDao = newCodePeriodDao;
this.newCodeDefinitionDocumentationUrl = documentationLinkGenerator.getDocumentationLink("/project-administration/defining-new-code/");
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("set")
.setPost(true)
.setDescription("Updates the " + createHtmlExternalLink(newCodeDefinitionDocumentationUrl, "new code definition") +
" on different levels:<br>" +
BEGIN_LIST +
BEGIN_ITEM_LIST + "Not providing a project key and a branch key will update the default value at global level. " +
"Existing projects or branches having a specific new code definition will not be impacted" + END_ITEM_LIST +
BEGIN_ITEM_LIST + "Project key must be provided to update the value for a project" + END_ITEM_LIST +
BEGIN_ITEM_LIST + "Both project and branch keys must be provided to update the value for a branch" + END_ITEM_LIST +
END_LIST +
"Requires one of the following permissions: " +
BEGIN_LIST +
BEGIN_ITEM_LIST + "'Administer System' to change the global setting" + END_ITEM_LIST +
BEGIN_ITEM_LIST + "'Administer' rights on the specified project to change the project setting" + END_ITEM_LIST +
END_LIST)
.setSince("8.0")
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project key");
action.createParam(PARAM_BRANCH)
.setDescription("Branch key");
action.createParam(PARAM_TYPE)
.setRequired(true)
.setDescription("Type<br/>" +
"New code definitions of the following types are allowed:" +
BEGIN_LIST +
BEGIN_ITEM_LIST + SPECIFIC_ANALYSIS.name() + " - can be set at branch level only" + END_ITEM_LIST +
BEGIN_ITEM_LIST + PREVIOUS_VERSION.name() + " - can be set at any level (global, project, branch)" + END_ITEM_LIST +
BEGIN_ITEM_LIST + NUMBER_OF_DAYS.name() + " - can be set at any level (global, project, branch)" + END_ITEM_LIST +
BEGIN_ITEM_LIST + REFERENCE_BRANCH.name() + " - can only be set for projects and branches" + END_ITEM_LIST +
END_LIST
);
action.createParam(PARAM_VALUE)
.setDescription("Value<br/>" +
"For each type, a different value is expected:" +
BEGIN_LIST +
BEGIN_ITEM_LIST + "the uuid of an analysis, when type is " + SPECIFIC_ANALYSIS.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + "no value, when type is " + PREVIOUS_VERSION.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + "a number between 1 and 90, when type is " + NUMBER_OF_DAYS.name() + END_ITEM_LIST +
BEGIN_ITEM_LIST + "a string, when type is " + REFERENCE_BRANCH.name() + END_ITEM_LIST +
END_LIST
);
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.getParam(PARAM_PROJECT).emptyAsNull().or(() -> null);
String branchKey = request.getParam(PARAM_BRANCH).emptyAsNull().or(() -> null);
if (projectKey == null && branchKey != null) {
throw new IllegalArgumentException("If branch key is specified, project key needs to be specified too");
}
try (DbSession dbSession = dbClient.openSession(false)) {
String typeStr = request.mandatoryParam(PARAM_TYPE);
String valueStr = request.getParam(PARAM_VALUE).emptyAsNull().or(() -> null);
boolean isCommunityEdition = editionProvider.get().filter(t -> t == EditionProvider.Edition.COMMUNITY).isPresent();
NewCodePeriodType type = validateType(typeStr, projectKey == null, branchKey != null || isCommunityEdition);
NewCodePeriodDto dto = new NewCodePeriodDto();
dto.setType(type);
ProjectDto project = null;
BranchDto branch = null;
if (projectKey != null) {
project = getProject(dbSession, projectKey);
userSession.checkEntityPermission(UserRole.ADMIN, project);
if (branchKey != null) {
branch = getBranch(dbSession, project, branchKey);
dto.setBranchUuid(branch.getUuid());
} else if (isCommunityEdition) {
// in CE set main branch value instead of project value
branch = getMainBranch(dbSession, project);
dto.setBranchUuid(branch.getUuid());
}
dto.setProjectUuid(project.getUuid());
} else {
userSession.checkIsSystemAdministrator();
}
setValue(dbSession, dto, type, project, branch, valueStr);
if (!CaycUtils.isNewCodePeriodCompliant(dto.getType(), dto.getValue())) {
throw new IllegalArgumentException("Failed to set the New Code Definition. The given value is not compatible with the Clean as " +
"You Code methodology. Please refer to the documentation for compliant options.");
}
newCodePeriodDao.upsert(dbSession, dto);
dbSession.commit();
}
}
private void setValue(DbSession dbSession, NewCodePeriodDto dto, NewCodePeriodType type, @Nullable ProjectDto project,
@Nullable BranchDto branch, @Nullable String value) {
switch (type) {
case PREVIOUS_VERSION -> Preconditions.checkArgument(value == null, "Unexpected value for type '%s'", type);
case NUMBER_OF_DAYS -> {
requireValue(type, value);
dto.setValue(parseDays(value));
}
case SPECIFIC_ANALYSIS -> {
checkValuesForSpecificBranch(type, value, project, branch);
dto.setValue(getAnalysis(dbSession, value, project, branch).getUuid());
}
case REFERENCE_BRANCH -> {
requireValue(type, value);
dto.setValue(value);
}
default -> throw new IllegalStateException("Unexpected type: " + type);
}
}
private static void checkValuesForSpecificBranch(NewCodePeriodType type, @Nullable String value, @Nullable ProjectDto project, @Nullable BranchDto branch) {
requireValue(type, value);
requireProject(type, project);
requireBranch(type, branch);
}
private static String parseDays(String value) {
try {
return Integer.toString(NewCodePeriodParser.parseDays(value));
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse number of days: " + value);
}
}
private static void requireValue(NewCodePeriodType type, @Nullable String value) {
Preconditions.checkArgument(value != null, "New code definition type '%s' requires a value", type);
}
private static void requireBranch(NewCodePeriodType type, @Nullable BranchDto branch) {
Preconditions.checkArgument(branch != null, "New code definition type '%s' requires a branch", type);
}
private static void requireProject(NewCodePeriodType type, @Nullable ProjectDto project) {
Preconditions.checkArgument(project != null, "New code definition type '%s' requires a project", type);
}
private BranchDto getBranch(DbSession dbSession, ProjectDto project, String branchKey) {
return dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), branchKey)
.orElseThrow(() -> new NotFoundException(format("Branch '%s' in project '%s' not found", branchKey, project.getKey())));
}
private ProjectDto getProject(DbSession dbSession, String projectKey) {
return componentFinder.getProjectByKey(dbSession, projectKey);
}
private BranchDto getMainBranch(DbSession dbSession, ProjectDto project) {
return dbClient.branchDao().selectByProject(dbSession, project)
.stream().filter(BranchDto::isMain)
.findFirst()
.orElseThrow(() -> new NotFoundException(format("Main branch in project '%s' is not found", project.getKey())));
}
private static NewCodePeriodType validateType(String typeStr, boolean isOverall, boolean isBranch) {
NewCodePeriodType type;
try {
type = NewCodePeriodType.valueOf(typeStr.toUpperCase(Locale.US));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid type: " + typeStr);
}
if (isOverall) {
checkType("Overall setting", OVERALL_TYPES, type);
} else if (isBranch) {
checkType("Branches", BRANCH_TYPES, type);
} else {
checkType("Projects", PROJECT_TYPES, type);
}
return type;
}
private SnapshotDto getAnalysis(DbSession dbSession, String analysisUuid, ProjectDto project, BranchDto branch) {
SnapshotDto snapshotDto = dbClient.snapshotDao().selectByUuid(dbSession, analysisUuid)
.orElseThrow(() -> new NotFoundException(format("Analysis '%s' is not found", analysisUuid)));
checkAnalysis(dbSession, project, branch, snapshotDto);
return snapshotDto;
}
private void checkAnalysis(DbSession dbSession, ProjectDto project, BranchDto branch, SnapshotDto analysis) {
BranchDto analysisBranch = dbClient.branchDao().selectByUuid(dbSession, analysis.getRootComponentUuid()).orElse(null);
boolean analysisMatchesProjectBranch = analysisBranch != null && analysisBranch.getUuid().equals(branch.getUuid());
checkArgument(analysisMatchesProjectBranch,
"Analysis '%s' does not belong to branch '%s' of project '%s'",
analysis.getUuid(), branch.getKey(), project.getKey());
}
private static void checkType(String name, Set<NewCodePeriodType> validTypes, NewCodePeriodType type) {
if (!validTypes.contains(type)) {
throw new IllegalArgumentException(String.format("Invalid type '%s'. %s can only be set with types: %s", type, name, validTypes));
}
}
}
| 13,450 | 45.543253 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/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.newcodeperiod.ws;
import java.util.Optional;
import javax.annotation.Nullable;
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.documentation.DocumentationLinkGenerator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.NewCodePeriods;
import static java.lang.String.format;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.WsUtils.createHtmlExternalLink;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.NewCodePeriods.ShowWSResponse;
public class ShowAction implements NewCodePeriodsWsAction {
private static final String PARAM_BRANCH = "branch";
private static final String PARAM_PROJECT = "project";
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final NewCodePeriodDao newCodePeriodDao;
private final String newCodeDefinitionDocumentationUrl;
public ShowAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, NewCodePeriodDao newCodePeriodDao,
DocumentationLinkGenerator documentationLinkGenerator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.newCodePeriodDao = newCodePeriodDao;
this.newCodeDefinitionDocumentationUrl = documentationLinkGenerator.getDocumentationLink("/project-administration/defining-new-code/");
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("show")
.setDescription("Shows the " + createHtmlExternalLink(newCodeDefinitionDocumentationUrl, "new code definition") + ".<br> " +
"If the component requested doesn't exist or if no new code definition is set for it, a value is inherited from the project or from the global setting." +
"Requires one of the following permissions if a component is specified: " +
"<ul>" +
"<li>'Administer' rights on the specified component</li>" +
"<li>'Execute analysis' rights on the specified component</li>" +
"</ul>")
.setSince("8.0")
.setResponseExample(getClass().getResource("show-example.json"))
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project key");
action.createParam(PARAM_BRANCH)
.setDescription("Branch key");
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.getParam(PARAM_PROJECT).emptyAsNull().or(() -> null);
String branchKey = request.getParam(PARAM_BRANCH).emptyAsNull().or(() -> null);
if (projectKey == null && branchKey != null) {
throw new IllegalArgumentException("If branch key is specified, project key needs to be specified too");
}
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = null;
BranchDto branch = null;
boolean inherited = false;
if (projectKey != null) {
try {
project = getProject(dbSession, projectKey);
checkPermission(project);
if (branchKey != null) {
try {
branch = getBranch(dbSession, project, branchKey);
} catch (NotFoundException e) {
inherited = true;
}
}
} catch (NotFoundException e) {
inherited = true;
}
}
ShowWSResponse.Builder builder = get(dbSession, project, branch, inherited);
if (project != null) {
builder.setProjectKey(project.getKey());
}
if (branch != null) {
builder.setBranchKey(branch.getKey());
}
writeProtobuf(builder.build(), request, response);
}
}
private void checkPermission(ProjectDto project) {
if (userSession.hasEntityPermission(UserRole.SCAN, project) ||
userSession.hasEntityPermission(UserRole.ADMIN, project) ||
userSession.hasPermission(SCAN)) {
return;
}
throw insufficientPrivilegesException();
}
private ShowWSResponse.Builder get(DbSession dbSession, @Nullable ProjectDto project, @Nullable BranchDto branch, boolean inherited) {
if (project == null) {
Optional<NewCodePeriodDto> dto = newCodePeriodDao.selectGlobal(dbSession);
return dto.map(d -> build(d, inherited))
.orElseGet(() -> buildDefault(inherited));
}
if (branch == null) {
Optional<NewCodePeriodDto> dto = newCodePeriodDao.selectByProject(dbSession, project.getUuid());
return dto.map(d -> build(d, inherited))
.orElseGet(() -> get(dbSession, null, null, true));
}
Optional<NewCodePeriodDto> dto = newCodePeriodDao.selectByBranch(dbSession, project.getUuid(), branch.getUuid());
return dto.map(d -> build(d, inherited))
.orElseGet(() -> get(dbSession, project, null, true));
}
private static ShowWSResponse.Builder build(NewCodePeriodDto dto, boolean inherited) {
ShowWSResponse.Builder builder = ShowWSResponse.newBuilder()
.setType(convertType(dto.getType()))
.setInherited(inherited);
if (dto.getValue() != null) {
builder.setValue(dto.getValue());
}
return builder;
}
private static ShowWSResponse.Builder buildDefault(boolean inherited) {
return ShowWSResponse.newBuilder()
.setType(convertType(NewCodePeriodType.PREVIOUS_VERSION))
.setInherited(inherited);
}
private static NewCodePeriods.NewCodePeriodType convertType(NewCodePeriodType type) {
switch (type) {
case NUMBER_OF_DAYS:
return NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS;
case PREVIOUS_VERSION:
return NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION;
case SPECIFIC_ANALYSIS:
return NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS;
case REFERENCE_BRANCH:
return NewCodePeriods.NewCodePeriodType.REFERENCE_BRANCH;
default:
throw new IllegalStateException("Unexpected type: " + type);
}
}
private BranchDto getBranch(DbSession dbSession, ProjectDto project, String branchKey) {
return dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), branchKey)
.orElseThrow(() -> new NotFoundException(format("Branch '%s' in project '%s' not found", branchKey, project.getKey())));
}
private ProjectDto getProject(DbSession dbSession, String projectKey) {
return componentFinder.getProjectByKey(dbSession, projectKey);
}
}
| 7,963 | 39.426396 | 162 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/ws/UnsetAction.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.newcodeperiod.ws;
import javax.annotation.Nullable;
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.documentation.DocumentationLinkGenerator;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.newcodeperiod.CaycUtils;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static org.sonar.server.ws.WsUtils.createHtmlExternalLink;
public class UnsetAction implements NewCodePeriodsWsAction {
private static final String BRANCH = "branch";
private static final String PROJECT = "project";
private static final String INSTANCE = "instance";
private static final String NON_COMPLIANT_CAYC_ERROR_MESSAGE = "Failed to unset the New Code Definition. Your %s " +
"New Code Definition is not compatible with the Clean as You Code methodology. Please update your %s New Code Definition";
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final PlatformEditionProvider editionProvider;
private final NewCodePeriodDao newCodePeriodDao;
private final String newCodeDefinitionDocumentationUrl;
public UnsetAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder,
PlatformEditionProvider editionProvider, NewCodePeriodDao newCodePeriodDao, DocumentationLinkGenerator documentationLinkGenerator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.editionProvider = editionProvider;
this.newCodePeriodDao = newCodePeriodDao;
this.newCodeDefinitionDocumentationUrl = documentationLinkGenerator.getDocumentationLink("/project-administration/defining-new-code/");
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("unset")
.setPost(true)
.setDescription("Unsets the " + createHtmlExternalLink(newCodeDefinitionDocumentationUrl, "new code definition") +
" for a branch, project or global. It requires the inherited New Code Definition to be compatible with the Clean as You Code methodology, " +
"and one of the following permissions: " +
"<ul>" +
"<li>'Administer System' to change the global setting</li>" +
"<li>'Administer' rights for a specified component</li>" +
"</ul>")
.setSince("8.0")
.setHandler(this);
action.createParam(PROJECT)
.setDescription("Project key");
action.createParam(BRANCH)
.setDescription("Branch key");
}
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.getParam(PROJECT).emptyAsNull().or(() -> null);
String branchKey = request.getParam(BRANCH).emptyAsNull().or(() -> null);
if (projectKey == null && branchKey != null) {
throw new IllegalArgumentException("If branch key is specified, project key needs to be specified too");
}
try (DbSession dbSession = dbClient.openSession(false)) {
String projectUuid = null;
String branchUuid = null;
// in CE set main branch value instead of project value
boolean isCommunityEdition = editionProvider.get().filter(t -> t == EditionProvider.Edition.COMMUNITY).isPresent();
if (projectKey != null) {
ProjectDto project = getProject(dbSession, projectKey);
userSession.checkEntityPermission(UserRole.ADMIN, project);
projectUuid = project.getUuid();
if (branchKey != null) {
branchUuid = getBranch(dbSession, project, branchKey).getUuid();
} else if (isCommunityEdition) {
branchUuid = getMainBranch(dbSession, project).getUuid();
}
checkInheritedNcdCompliant(dbSession, projectUuid, branchUuid);
} else {
userSession.checkIsSystemAdministrator();
}
newCodePeriodDao.delete(dbSession, projectUuid, branchUuid);
if (isCommunityEdition && projectUuid != null) {
// also delete project default in case it was somehow set (downgrade from another edition, for example)
newCodePeriodDao.delete(dbSession, projectUuid, null);
}
dbSession.commit();
}
}
private void checkInheritedNcdCompliant(DbSession dbSession, String projectUuid, @Nullable String branchUuid) {
if (branchUuid != null) {
if (dbClient.newCodePeriodDao().selectByBranch(dbSession, projectUuid, branchUuid).isPresent()) {
checkBranchInheritedNcdCompliant(dbSession, projectUuid);
}
} else if (dbClient.newCodePeriodDao().selectByProject(dbSession, projectUuid).isPresent()) {
checkInstanceNcdCompliant(dbSession);
}
}
private BranchDto getMainBranch(DbSession dbSession, ProjectDto project) {
return dbClient.branchDao().selectByProject(dbSession, project)
.stream().filter(BranchDto::isMain)
.findFirst()
.orElseThrow(() -> new NotFoundException(format("Main branch in project '%s' not found", project.getKey())));
}
private BranchDto getBranch(DbSession dbSession, ProjectDto project, String branchKey) {
return dbClient.branchDao().selectByBranchKey(dbSession, project.getUuid(), branchKey)
.orElseThrow(() -> new NotFoundException(format("Branch '%s' in project '%s' not found", branchKey, project.getKey())));
}
private ProjectDto getProject(DbSession dbSession, String projectKey) {
return componentFinder.getProjectByKey(dbSession, projectKey);
}
private void checkInstanceNcdCompliant(DbSession dbSession) {
var instanceNcd = newCodePeriodDao.selectGlobal(dbSession);
if (instanceNcd.isPresent()) {
var ncd = instanceNcd.get();
if (!CaycUtils.isNewCodePeriodCompliant(ncd.getType(), ncd.getValue())) {
throw new IllegalArgumentException(format(NON_COMPLIANT_CAYC_ERROR_MESSAGE, INSTANCE, INSTANCE));
}
}
}
private void checkBranchInheritedNcdCompliant(DbSession dbSession, String projectUuid) {
var projectNcd = newCodePeriodDao.selectByProject(dbSession, projectUuid);
if (projectNcd.isPresent()) {
var ncd = projectNcd.get();
if (!CaycUtils.isNewCodePeriodCompliant(ncd.getType(), ncd.getValue())) {
throw new IllegalArgumentException(format(NON_COMPLIANT_CAYC_ERROR_MESSAGE, PROJECT, PROJECT));
}
} else {
checkInstanceNcdCompliant(dbSession);
}
}
}
| 7,734 | 42.455056 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/newcodeperiod/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.newcodeperiod.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 973 | 39.583333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/AddAction.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.notification.ws;
import java.util.List;
import java.util.Optional;
import org.sonar.api.notifications.NotificationChannel;
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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.KeyExamples;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.notification.ws.NotificationsWsParameters.ACTION_ADD;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_CHANNEL;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_LOGIN;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_PROJECT;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_TYPE;
public class AddAction implements NotificationsWsAction {
private final NotificationCenter notificationCenter;
private final NotificationUpdater notificationUpdater;
private final Dispatchers dispatchers;
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
public AddAction(NotificationCenter notificationCenter, NotificationUpdater notificationUpdater, Dispatchers dispatchers, DbClient dbClient, ComponentFinder componentFinder,
UserSession userSession) {
this.notificationCenter = notificationCenter;
this.notificationUpdater = notificationUpdater;
this.dispatchers = dispatchers;
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_ADD)
.setDescription("Add a notification for the authenticated user.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>Authentication if no login is provided. If a project is provided, requires the 'Browse' permission on the specified project.</li>" +
" <li>System administration if a login is provided. If a project is provided, requires the 'Browse' permission on the specified project.</li>" +
"</ul>")
.setSince("6.3")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001);
List<NotificationChannel> channels = notificationCenter.getChannels();
action.createParam(PARAM_CHANNEL)
.setDescription("Channel through which the notification is sent. For example, notifications can be sent by email.")
.setPossibleValues(channels)
.setDefaultValue(EmailNotificationChannel.class.getSimpleName());
action.createParam(PARAM_TYPE)
.setDescription("Notification type. Possible values are for:" +
"<ul>" +
" <li>Global notifications: %s</li>" +
" <li>Per project notifications: %s</li>" +
"</ul>",
String.join(", ", dispatchers.getGlobalDispatchers()),
String.join(", ", dispatchers.getProjectDispatchers()))
.setRequired(true)
.setExampleValue(MyNewIssuesNotificationHandler.KEY);
action.createParam(PARAM_LOGIN)
.setDescription("User login")
.setSince("6.4");
}
@Override
public void handle(Request request, Response response) throws Exception {
AddRequest addRequest = toWsRequest(request);
add(addRequest);
response.noContent();
}
private void add(AddRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
checkPermissions(request);
UserDto user = getUser(dbSession, request);
Optional<ProjectDto> project = searchProject(dbSession, request);
notificationUpdater.add(dbSession, request.getChannel(), request.getType(), user, project.orElse(null));
dbSession.commit();
}
}
private UserDto getUser(DbSession dbSession, AddRequest request) {
String login = request.getLogin() == null ? userSession.getLogin() : request.getLogin();
return checkFound(dbClient.userDao().selectByLogin(dbSession, login), "User '%s' not found", login);
}
private Optional<ProjectDto> searchProject(DbSession dbSession, AddRequest request) {
Optional<ProjectDto> project = request.getProject() == null ? empty() : Optional.of(componentFinder.getProjectByKey(dbSession, request.getProject()));
project.ifPresent(p -> userSession.checkEntityPermission(UserRole.USER, p));
return project;
}
private void checkPermissions(AddRequest request) {
if (request.getLogin() == null) {
userSession.checkLoggedIn();
} else {
userSession.checkIsSystemAdministrator();
}
}
private AddRequest toWsRequest(Request request) {
AddRequest add = new AddRequest()
.setType(request.mandatoryParam(PARAM_TYPE))
.setChannel(request.mandatoryParam(PARAM_CHANNEL));
ofNullable(request.param(PARAM_PROJECT)).ifPresent(add::setProject);
ofNullable(request.param(PARAM_LOGIN)).ifPresent(add::setLogin);
if (add.getProject() == null) {
checkRequest(dispatchers.getGlobalDispatchers().contains(add.getType()), "Value of parameter '%s' (%s) must be one of: %s",
PARAM_TYPE,
add.getType(),
dispatchers.getGlobalDispatchers());
} else {
checkRequest(dispatchers.getProjectDispatchers().contains(add.getType()), "Value of parameter '%s' (%s) must be one of: %s",
PARAM_TYPE,
add.getType(),
dispatchers.getProjectDispatchers());
}
return add;
}
private static class AddRequest {
private String channel;
private String login;
private String project;
private String type;
public AddRequest setChannel(String channel) {
this.channel = channel;
return this;
}
public String getChannel() {
return channel;
}
public AddRequest setLogin(String login) {
this.login = login;
return this;
}
public String getLogin() {
return login;
}
public AddRequest setProject(String project) {
this.project = project;
return this;
}
public String getProject() {
return project;
}
public AddRequest setType(String type) {
this.type = type;
return this;
}
public String getType() {
return type;
}
}
}
| 7,811 | 36.37799 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/Dispatchers.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.notification.ws;
import java.util.List;
public interface Dispatchers {
List<String> getGlobalDispatchers();
List<String> getProjectDispatchers();
}
| 1,024 | 33.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/DispatchersImpl.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.notification.ws;
import java.util.List;
import org.sonar.api.Startable;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
public class DispatchersImpl implements Dispatchers, Startable {
private final NotificationCenter notificationCenter;
private List<String> projectDispatchers;
private List<String> globalDispatchers;
public DispatchersImpl(NotificationCenter notificationCenter) {
this.notificationCenter = notificationCenter;
}
@Override
public List<String> getGlobalDispatchers() {
return globalDispatchers;
}
@Override
public List<String> getProjectDispatchers() {
return projectDispatchers;
}
@Override
public void start() {
this.globalDispatchers = notificationCenter.getDispatcherKeysForProperty(GLOBAL_NOTIFICATION, "true")
.stream()
.sorted()
.toList();
this.projectDispatchers = notificationCenter.getDispatcherKeysForProperty(PER_PROJECT_NOTIFICATION, "true")
.stream()
.sorted()
.toList();
}
@Override
public void stop() {
// nothing to do
}
}
| 2,078 | 30.5 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/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.notification.ws;
import com.google.common.base.Splitter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import org.sonar.api.notifications.NotificationChannel;
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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Notifications.ListResponse;
import org.sonarqube.ws.Notifications.Notification;
import org.sonarqube.ws.Notifications.Notification.Builder;
import static java.util.Comparator.comparing;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsFirst;
import static java.util.Optional.ofNullable;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.notification.ws.NotificationsWsParameters.ACTION_LIST;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_LOGIN;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class ListAction implements NotificationsWsAction {
private static final Splitter PROPERTY_KEY_SPLITTER = Splitter.on(".");
private final DbClient dbClient;
private final UserSession userSession;
private final List<String> channels;
private final Dispatchers dispatchers;
public ListAction(NotificationCenter notificationCenter, DbClient dbClient, UserSession userSession, Dispatchers dispatchers) {
this.dbClient = dbClient;
this.userSession = userSession;
this.channels = notificationCenter.getChannels().stream().map(NotificationChannel::getKey).sorted().toList();
this.dispatchers = dispatchers;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_LIST)
.setDescription("List notifications of the authenticated user.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>Authentication if no login is provided</li>" +
" <li>System administration if a login is provided</li>" +
"</ul>")
.setSince("6.3")
.setResponseExample(getClass().getResource("list-example.json"))
.setHandler(this);
action.createParam(PARAM_LOGIN)
.setDescription("User login")
.setSince("6.4");
}
@Override
public void handle(Request request, Response response) throws Exception {
ListResponse listResponse = search(request);
writeProtobuf(listResponse, request, response);
}
private ListResponse search(Request request) {
try (DbSession dbSession = dbClient.openSession(false)) {
checkPermissions(request);
UserDto user = getUser(dbSession, request);
return Optional
.of(ListResponse.newBuilder())
.map(r -> r.addAllChannels(channels))
.map(r -> r.addAllGlobalTypes(dispatchers.getGlobalDispatchers()))
.map(r -> r.addAllPerProjectTypes(dispatchers.getProjectDispatchers()))
.map(addNotifications(dbSession, user))
.map(ListResponse.Builder::build)
.orElseThrow();
}
}
private UserDto getUser(DbSession dbSession, Request request) {
String login = request.param(PARAM_LOGIN) == null ? userSession.getLogin() : request.param(PARAM_LOGIN);
return checkFound(dbClient.userDao().selectByLogin(dbSession, login), "User '%s' not found", login);
}
private UnaryOperator<ListResponse.Builder> addNotifications(DbSession dbSession, UserDto user) {
return response -> {
List<PropertyDto> properties = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).build(), dbSession);
Map<String, EntityDto> entitiesByUuid = searchProjects(dbSession, properties);
Predicate<PropertyDto> isNotification = prop -> prop.getKey().startsWith("notification.");
Predicate<PropertyDto> isComponentInDb = prop -> prop.getEntityUuid() == null || entitiesByUuid.containsKey(prop.getEntityUuid());
Notification.Builder notification = Notification.newBuilder();
properties.stream()
.filter(isNotification)
.filter(channelAndDispatcherAuthorized())
.filter(isComponentInDb)
.map(toWsNotification(notification, entitiesByUuid))
.sorted(comparing(Notification::getProject, nullsFirst(naturalOrder()))
.thenComparing(Notification::getChannel)
.thenComparing(Notification::getType))
.forEach(response::addNotifications);
return response;
};
}
private Predicate<PropertyDto> channelAndDispatcherAuthorized() {
return prop -> {
List<String> key = PROPERTY_KEY_SPLITTER.splitToList(prop.getKey());
return key.size() == 3
&& channels.contains(key.get(2))
&& isDispatcherAuthorized(prop, key.get(1));
};
}
private boolean isDispatcherAuthorized(PropertyDto prop, String dispatcher) {
return (prop.getEntityUuid() != null && dispatchers.getProjectDispatchers().contains(dispatcher)) || dispatchers.getGlobalDispatchers().contains(dispatcher);
}
private Map<String, EntityDto> searchProjects(DbSession dbSession, List<PropertyDto> properties) {
Set<String> entityUuids = properties.stream()
.map(PropertyDto::getEntityUuid)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<String> authorizedProjectUuids = dbClient.authorizationDao().keepAuthorizedEntityUuids(dbSession, entityUuids, userSession.getUuid(), UserRole.USER);
return dbClient.entityDao().selectByUuids(dbSession, entityUuids)
.stream()
.filter(c -> authorizedProjectUuids.contains(c.getUuid()))
.collect(Collectors.toMap(EntityDto::getUuid, Function.identity()));
}
private static Function<PropertyDto, Notification> toWsNotification(Notification.Builder notification, Map<String, EntityDto> projectsByUuid) {
return property -> {
notification.clear();
List<String> propertyKey = Splitter.on(".").splitToList(property.getKey());
notification.setType(propertyKey.get(1));
notification.setChannel(propertyKey.get(2));
ofNullable(property.getEntityUuid()).ifPresent(componentUuid -> populateProjectFields(notification, componentUuid, projectsByUuid));
return notification.build();
};
}
private static void populateProjectFields(Builder notification, String componentUuid, Map<String, EntityDto> projectsByUuid) {
EntityDto project = projectsByUuid.get(componentUuid);
notification
.setProject(project.getKey())
.setProjectName(project.getName());
}
private void checkPermissions(Request request) {
if (request.param(PARAM_LOGIN) == null) {
userSession.checkLoggedIn();
} else {
userSession.checkIsSystemAdministrator();
}
}
}
| 8,066 | 40.369231 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationCenter.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.notification.ws;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.notifications.NotificationChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.springframework.beans.factory.annotation.Autowired;
public class NotificationCenter {
private static final Logger LOG = LoggerFactory.getLogger(NotificationCenter.class);
private final NotificationDispatcherMetadata[] dispatchersMetadata;
private final NotificationChannel[] channels;
@Autowired(required = false)
public NotificationCenter(NotificationDispatcherMetadata[] metadata, NotificationChannel[] channels) {
this.dispatchersMetadata = metadata;
this.channels = channels;
}
/**
* Default constructor when no channels.
*/
@Autowired(required = false)
public NotificationCenter(NotificationDispatcherMetadata[] metadata) {
this(metadata, new NotificationChannel[0]);
LOG.warn("There is no notification channel - no notification will be delivered!");
}
/**
* Default constructor when no dispatcher metadata.
*/
@Autowired(required = false)
public NotificationCenter(NotificationChannel[] channels) {
this(new NotificationDispatcherMetadata[0], channels);
}
@Autowired(required = false)
public NotificationCenter() {
this(new NotificationDispatcherMetadata[0], new NotificationChannel[0]);
LOG.warn("There is no notification channel - no notification will be delivered!");
}
public List<NotificationChannel> getChannels() {
return Arrays.asList(channels);
}
/**
* Returns all the available dispatchers which metadata matches the given property and its value.
* <br/>
* If "propertyValue" is null, the verification is done on the existence of such a property (whatever the value).
*/
public List<String> getDispatcherKeysForProperty(String propertyKey, @Nullable String propertyValue) {
ImmutableList.Builder<String> keys = ImmutableList.builder();
for (NotificationDispatcherMetadata metadata : dispatchersMetadata) {
String dispatcherKey = metadata.getDispatcherKey();
String value = metadata.getProperty(propertyKey);
if (value != null && (propertyValue == null || value.equals(propertyValue))) {
keys.add(dispatcherKey);
}
}
return keys.build();
}
}
| 3,324 | 35.944444 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationUpdater.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.notification.ws;
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkArgument;
public class NotificationUpdater {
private static final String PROP_NOTIFICATION_PREFIX = "notification";
private static final String PROP_NOTIFICATION_VALUE = "true";
private final DbClient dbClient;
public NotificationUpdater(DbClient dbClient) {
this.dbClient = dbClient;
}
/**
* Add a notification to a user.
*/
public void add(DbSession dbSession, String channel, String dispatcher, UserDto user, @Nullable EntityDto project) {
String key = String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel);
String projectUuid = project == null ? null : project.getUuid();
String projectKey = project == null ? null : project.getKey();
String projectName = project == null ? null : project.getName();
String qualifier = project == null ? null : project.getQualifier();
List<PropertyDto> existingNotification = dbClient.propertiesDao().selectByQuery(
PropertyQuery.builder()
.setKey(key)
.setEntityUuid(projectUuid)
.setUserUuid(user.getUuid())
.build(),
dbSession).stream()
.filter(notificationScope(project))
.toList();
checkArgument(existingNotification.isEmpty()
|| !PROP_NOTIFICATION_VALUE.equals(existingNotification.get(0).getValue()), "Notification already added");
dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto()
.setKey(key)
.setUserUuid(user.getUuid())
.setValue(PROP_NOTIFICATION_VALUE)
.setEntityUuid(projectUuid),
user.getLogin(), projectKey, projectName, qualifier);
}
/**
* Remove a notification from a user.
*/
public void remove(DbSession dbSession, String channel, String dispatcher, UserDto user, @Nullable EntityDto project) {
String key = String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel);
String projectUuid = project == null ? null : project.getUuid();
String projectKey = project == null ? null : project.getKey();
String projectName = project == null ? null : project.getName();
String qualifier = project == null ? null : project.getQualifier();
List<PropertyDto> existingNotification = dbClient.propertiesDao().selectByQuery(
PropertyQuery.builder()
.setKey(key)
.setEntityUuid(projectUuid)
.setUserUuid(user.getUuid())
.build(),
dbSession).stream()
.filter(notificationScope(project))
.toList();
checkArgument(!existingNotification.isEmpty() && PROP_NOTIFICATION_VALUE.equals(existingNotification.get(0).getValue()), "Notification doesn't exist");
dbClient.propertiesDao().delete(dbSession, new PropertyDto()
.setKey(key)
.setUserUuid(user.getUuid())
.setValue(PROP_NOTIFICATION_VALUE)
.setEntityUuid(projectUuid), user.getLogin(), projectKey, projectName, qualifier);
}
private static Predicate<PropertyDto> notificationScope(@Nullable EntityDto project) {
return prop -> project == null ? (prop.getEntityUuid() == null) : (prop.getEntityUuid() != null);
}
}
| 4,314 | 39.707547 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationWsModule.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.notification.ws;
import org.sonar.core.platform.Module;
public class NotificationWsModule extends Module {
@Override
protected void configureModule() {
add(
NotificationCenter.class,
NotificationUpdater.class,
DispatchersImpl.class,
// WS
NotificationsWs.class,
AddAction.class,
RemoveAction.class,
ListAction.class);
}
}
| 1,250 | 31.921053 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationsWs.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.notification.ws;
import org.sonar.api.server.ws.WebService;
import static org.sonar.server.notification.ws.NotificationsWsParameters.CONTROLLER;
public class NotificationsWs implements WebService {
private final NotificationsWsAction[] actions;
public NotificationsWs(NotificationsWsAction[] actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER)
.setDescription("Manage notifications of the authenticated user")
.setSince("6.3");
for (NotificationsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,549 | 32.695652 | 84 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationsWsAction.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.notification.ws;
import org.sonar.server.ws.WsAction;
public interface NotificationsWsAction extends WsAction {
// marker interface
}
| 1,006 | 36.296296 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/NotificationsWsParameters.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.notification.ws;
public class NotificationsWsParameters {
public static final String CONTROLLER = "api/notifications";
public static final String ACTION_ADD = "add";
public static final String ACTION_REMOVE = "remove";
public static final String ACTION_LIST = "list";
public static final String PARAM_PROJECT = "project";
public static final String PARAM_CHANNEL = "channel";
public static final String PARAM_TYPE = "type";
public static final String PARAM_LOGIN = "login";
private NotificationsWsParameters() {
// prevent instantiation
}
}
| 1,436 | 37.837838 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/ws/RemoveAction.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.notification.ws;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.sonar.api.notifications.NotificationChannel;
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.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.KeyExamples;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.notification.ws.NotificationsWsParameters.ACTION_REMOVE;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_CHANNEL;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_LOGIN;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_PROJECT;
import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_TYPE;
public class RemoveAction implements NotificationsWsAction {
private final NotificationCenter notificationCenter;
private final NotificationUpdater notificationUpdater;
private final Dispatchers dispatchers;
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
public RemoveAction(NotificationCenter notificationCenter, NotificationUpdater notificationUpdater, Dispatchers dispatchers, DbClient dbClient, ComponentFinder componentFinder,
UserSession userSession) {
this.notificationCenter = notificationCenter;
this.notificationUpdater = notificationUpdater;
this.dispatchers = dispatchers;
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_REMOVE)
.setDescription("Remove a notification for the authenticated user.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>Authentication if no login is provided</li>" +
" <li>System administration if a login is provided</li>" +
"</ul>")
.setSince("6.3")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001);
List<NotificationChannel> channels = notificationCenter.getChannels();
action.createParam(PARAM_CHANNEL)
.setDescription("Channel through which the notification is sent. For example, notifications can be sent by email.")
.setPossibleValues(channels)
.setDefaultValue(EmailNotificationChannel.class.getSimpleName());
action.createParam(PARAM_TYPE)
.setDescription("Notification type. Possible values are for:" +
"<ul>" +
" <li>Global notifications: %s</li>" +
" <li>Per project notifications: %s</li>" +
"</ul>",
dispatchers.getGlobalDispatchers().stream().sorted().collect(Collectors.joining(", ")),
dispatchers.getProjectDispatchers().stream().sorted().collect(Collectors.joining(", ")))
.setRequired(true)
.setExampleValue(MyNewIssuesNotificationHandler.KEY);
action.createParam(PARAM_LOGIN)
.setDescription("User login")
.setSince("6.4");
}
@Override
public void handle(Request request, Response response) throws Exception {
RemoveRequest removeRequest = toWsRequest(request);
remove(removeRequest);
response.noContent();
}
private void remove(RemoveRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
checkPermissions(request);
UserDto user = getUser(dbSession, request);
Optional<ProjectDto> project = searchProject(dbSession, request);
notificationUpdater.remove(dbSession, request.getChannel(), request.getType(), user, project.orElse(null));
dbSession.commit();
}
}
private UserDto getUser(DbSession dbSession, RemoveRequest request) {
String login = request.getLogin() == null ? userSession.getLogin() : request.getLogin();
return checkFound(dbClient.userDao().selectByLogin(dbSession, login), "User '%s' not found", login);
}
private Optional<ProjectDto> searchProject(DbSession dbSession, RemoveRequest request) {
return request.getProject() == null ? empty() : Optional.of(componentFinder.getProjectByKey(dbSession, request.getProject()));
}
private void checkPermissions(RemoveRequest request) {
if (request.getLogin() == null) {
userSession.checkLoggedIn();
} else {
userSession.checkIsSystemAdministrator();
}
}
private RemoveRequest toWsRequest(Request request) {
RemoveRequest remove = new RemoveRequest()
.setType(request.mandatoryParam(PARAM_TYPE))
.setChannel(request.mandatoryParam(PARAM_CHANNEL));
ofNullable(request.param(PARAM_PROJECT)).ifPresent(remove::setProject);
ofNullable(request.param(PARAM_LOGIN)).ifPresent(remove::setLogin);
if (remove.getProject() == null) {
checkRequest(dispatchers.getGlobalDispatchers().contains(remove.getType()), "Value of parameter '%s' (%s) must be one of: %s",
PARAM_TYPE,
remove.getType(),
dispatchers.getGlobalDispatchers());
} else {
checkRequest(dispatchers.getProjectDispatchers().contains(remove.getType()), "Value of parameter '%s' (%s) must be one of: %s",
PARAM_TYPE,
remove.getType(),
dispatchers.getProjectDispatchers());
}
return remove;
}
static class RemoveRequest {
private String channel;
private String login;
private String project;
private String type;
public RemoveRequest setChannel(String channel) {
this.channel = channel;
return this;
}
public String getChannel() {
return channel;
}
public RemoveRequest setLogin(String login) {
this.login = login;
return this;
}
public String getLogin() {
return login;
}
public RemoveRequest setProject(String project) {
this.project = project;
return this;
}
public String getProject() {
return project;
}
public RemoveRequest setType(String type) {
this.type = type;
return this;
}
public String getType() {
return type;
}
}
}
| 7,671 | 36.062802 | 178 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/notification/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.notification.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 973 | 37.96 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ApplyPermissionTemplateQuery.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.permission;
import java.util.List;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public class ApplyPermissionTemplateQuery {
private final String templateUuid;
private List<String> componentKeys;
private ApplyPermissionTemplateQuery(String templateUuid, List<String> componentKeys) {
this.templateUuid = templateUuid;
this.componentKeys = componentKeys;
validate();
}
public static ApplyPermissionTemplateQuery create(String templateUuid, List<String> componentKeys) {
return new ApplyPermissionTemplateQuery(templateUuid, componentKeys);
}
public String getTemplateUuid() {
return templateUuid;
}
public List<String> getComponentKeys() {
return componentKeys;
}
private void validate() {
checkRequest(isNotBlank(templateUuid), "Permission template is mandatory");
checkRequest(componentKeys != null && !componentKeys.isEmpty(), "No project provided. Please provide at least one project.");
}
}
| 1,920 | 33.927273 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolver.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.permission;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.DbSession;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
public interface DefaultTemplatesResolver {
/**
* Resolve the effective default templates uuid for the specified {@link DefaultTemplates}.
* <ul>
* <li>{@link ResolvedDefaultTemplates#project} is always the same as {@link DefaultTemplates#projectUuid}</li>
* <li>when Governance is not installed, {@link ResolvedDefaultTemplates#application} is always {@code null}</li>
* <li>when Governance is installed, {@link ResolvedDefaultTemplates#application} is {@link DefaultTemplates#applicationsUuid}
* when it is non {@code null}, otherwise it is {@link DefaultTemplates#projectUuid}</li>
* <li>when Governance is installed, {@link ResolvedDefaultTemplates#portfolio} is {@link DefaultTemplates#portfoliosUuid}
* when it is non {@code null}, otherwise it is {@link DefaultTemplates#projectUuid}</li>
* </ul>
*/
ResolvedDefaultTemplates resolve(DbSession dbSession);
@Immutable
final class ResolvedDefaultTemplates {
private final String project;
private final String application;
private final String portfolio;
public ResolvedDefaultTemplates(String project, @Nullable String application, @Nullable String portfolio) {
this.project = requireNonNull(project, "project can't be null");
this.application = application;
this.portfolio = portfolio;
}
public String getProject() {
return project;
}
public Optional<String> getApplication() {
return ofNullable(application);
}
public Optional<String> getPortfolio() {
return ofNullable(portfolio);
}
}
}
| 2,705 | 38.217391 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.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.permission;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.property.InternalProperties;
public class DefaultTemplatesResolverImpl implements DefaultTemplatesResolver {
private final DbClient dbClient;
private final ResourceTypes resourceTypes;
public DefaultTemplatesResolverImpl(DbClient dbClient, ResourceTypes resourceTypes) {
this.dbClient = dbClient;
this.resourceTypes = resourceTypes;
}
@Override
public ResolvedDefaultTemplates resolve(DbSession dbSession) {
String defaultProjectTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE).orElseThrow(() -> {
throw new IllegalStateException("Default template for project is missing");
});
String defaultPortfolioTemplate = null;
String defaultApplicationTemplate = null;
if (isPortfolioEnabled(resourceTypes)) {
defaultPortfolioTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE).orElse(defaultProjectTemplate);
}
if (isApplicationEnabled(resourceTypes)) {
defaultApplicationTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE).orElse(defaultProjectTemplate);
}
return new ResolvedDefaultTemplates(defaultProjectTemplate, defaultApplicationTemplate, defaultPortfolioTemplate);
}
private static boolean isPortfolioEnabled(ResourceTypes resourceTypes) {
return resourceTypes.getRoots()
.stream()
.map(ResourceType::getQualifier)
.anyMatch(Qualifiers.VIEW::equals);
}
private static boolean isApplicationEnabled(ResourceTypes resourceTypes) {
return resourceTypes.getRoots()
.stream()
.map(ResourceType::getQualifier)
.anyMatch(Qualifiers.APP::equals);
}
}
| 2,886 | 39.097222 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChange.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.permission;
import javax.annotation.Nullable;
import org.sonar.db.entity.EntityDto;
public class GroupPermissionChange extends PermissionChange {
private final GroupUuidOrAnyone group;
public GroupPermissionChange(Operation operation, String permission, @Nullable EntityDto entityDto,
GroupUuidOrAnyone group, PermissionService permissionService) {
super(operation, permission, entityDto, permissionService);
this.group = group;
}
public GroupUuidOrAnyone getGroupUuidOrAnyone() {
return group;
}
}
| 1,398 | 34.871795 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/GroupPermissionChanger.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.permission;
import java.util.List;
import java.util.Optional;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.user.GroupDto;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionChange.Operation.ADD;
import static org.sonar.server.permission.PermissionChange.Operation.REMOVE;
public class GroupPermissionChanger {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
public GroupPermissionChanger(DbClient dbClient, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
}
public boolean apply(DbSession dbSession, GroupPermissionChange change) {
ensureConsistencyWithVisibility(change);
if (isImplicitlyAlreadyDone(change)) {
return false;
}
switch (change.getOperation()) {
case ADD:
return addPermission(dbSession, change);
case REMOVE:
return removePermission(dbSession, change);
default:
throw new UnsupportedOperationException("Unsupported permission change: " + change.getOperation());
}
}
private static boolean isImplicitlyAlreadyDone(GroupPermissionChange change) {
EntityDto project = change.getEntity();
if (project != null) {
return isImplicitlyAlreadyDone(project, change);
}
return false;
}
private static boolean isImplicitlyAlreadyDone(EntityDto project, GroupPermissionChange change) {
return isAttemptToAddPublicPermissionToPublicComponent(change, project)
|| isAttemptToRemovePermissionFromAnyoneOnPrivateComponent(change, project);
}
private static boolean isAttemptToAddPublicPermissionToPublicComponent(GroupPermissionChange change, EntityDto project) {
return !project.isPrivate()
&& change.getOperation() == ADD
&& UserRole.PUBLIC_PERMISSIONS.contains(change.getPermission());
}
private static boolean isAttemptToRemovePermissionFromAnyoneOnPrivateComponent(GroupPermissionChange change, EntityDto project) {
return project.isPrivate()
&& change.getOperation() == REMOVE
&& change.getGroupUuidOrAnyone().isAnyone();
}
private static void ensureConsistencyWithVisibility(GroupPermissionChange change) {
EntityDto project = change.getEntity();
if (project != null) {
checkRequest(
!isAttemptToAddPermissionToAnyoneOnPrivateComponent(change, project),
"No permission can be granted to Anyone on a private component");
checkRequest(
!isAttemptToRemovePublicPermissionFromPublicComponent(change, project),
"Permission %s can't be removed from a public component", change.getPermission());
}
}
private static boolean isAttemptToAddPermissionToAnyoneOnPrivateComponent(GroupPermissionChange change, EntityDto project) {
return project.isPrivate()
&& change.getOperation() == ADD
&& change.getGroupUuidOrAnyone().isAnyone();
}
private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(GroupPermissionChange change, EntityDto project) {
return !project.isPrivate()
&& change.getOperation() == REMOVE
&& UserRole.PUBLIC_PERMISSIONS.contains(change.getPermission());
}
private boolean addPermission(DbSession dbSession, GroupPermissionChange change) {
if (loadExistingPermissions(dbSession, change).contains(change.getPermission())) {
return false;
}
validateNotAnyoneAndAdminPermission(change.getPermission(), change.getGroupUuidOrAnyone());
String groupUuid = change.getGroupUuidOrAnyone().getUuid();
GroupPermissionDto addedDto = new GroupPermissionDto()
.setUuid(uuidFactory.create())
.setRole(change.getPermission())
.setGroupUuid(groupUuid)
.setEntityName(change.getProjectName())
.setEntityUuid(change.getProjectUuid());
Optional.ofNullable(groupUuid)
.map(uuid -> dbClient.groupDao().selectByUuid(dbSession, groupUuid))
.map(GroupDto::getName)
.ifPresent(addedDto::setGroupName);
dbClient.groupPermissionDao().insert(dbSession, addedDto, change.getEntity(), null);
return true;
}
private static void validateNotAnyoneAndAdminPermission(String permission, GroupUuidOrAnyone group) {
checkRequest(!GlobalPermission.ADMINISTER.getKey().equals(permission) || !group.isAnyone(),
format("It is not possible to add the '%s' permission to group 'Anyone'.", permission));
}
private boolean removePermission(DbSession dbSession, GroupPermissionChange change) {
if (!loadExistingPermissions(dbSession, change).contains(change.getPermission())) {
return false;
}
checkIfRemainingGlobalAdministrators(dbSession, change);
String groupUuid = change.getGroupUuidOrAnyone().getUuid();
String groupName = Optional.ofNullable(groupUuid)
.map(uuid -> dbClient.groupDao().selectByUuid(dbSession, uuid))
.map(GroupDto::getName)
.orElse(null);
dbClient.groupPermissionDao().delete(dbSession,
change.getPermission(),
groupUuid,
groupName,
change.getEntity());
return true;
}
private List<String> loadExistingPermissions(DbSession dbSession, GroupPermissionChange change) {
String projectUuid = change.getProjectUuid();
if (projectUuid != null) {
return dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession,
change.getGroupUuidOrAnyone().getUuid(),
projectUuid);
}
return dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession,
change.getGroupUuidOrAnyone().getUuid());
}
private void checkIfRemainingGlobalAdministrators(DbSession dbSession, GroupPermissionChange change) {
GroupUuidOrAnyone groupUuidOrAnyone = change.getGroupUuidOrAnyone();
if (GlobalPermission.ADMINISTER.getKey().equals(change.getPermission()) &&
!groupUuidOrAnyone.isAnyone() &&
change.getProjectUuid() == null) {
String groupUuid = checkNotNull(groupUuidOrAnyone.getUuid());
// removing global admin permission from group
int remaining = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, GlobalPermission.ADMINISTER.getKey(), groupUuid);
checkRequest(remaining > 0, "Last group with permission '%s'. Permission cannot be removed.", GlobalPermission.ADMINISTER.getKey());
}
}
}
| 7,553 | 39.832432 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionChange.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.permission;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public abstract class PermissionChange {
public enum Operation {
ADD, REMOVE
}
private final Operation operation;
private final String permission;
private final EntityDto entity;
protected final PermissionService permissionService;
protected PermissionChange(Operation operation, String permission, @Nullable EntityDto entity, PermissionService permissionService) {
this.operation = requireNonNull(operation);
this.permission = requireNonNull(permission);
this.entity = entity;
this.permissionService = permissionService;
if (entity == null) {
checkRequest(permissionService.getGlobalPermissions().stream().anyMatch(p -> p.getKey().equals(permission)),
"Invalid global permission '%s'. Valid values are %s", permission,
permissionService.getGlobalPermissions().stream().map(GlobalPermission::getKey).toList());
} else {
checkRequest(permissionService.getAllProjectPermissions().contains(permission), "Invalid project permission '%s'. Valid values are %s", permission,
permissionService.getAllProjectPermissions());
}
}
public Operation getOperation() {
return operation;
}
public String getPermission() {
return permission;
}
@CheckForNull
public EntityDto getEntity() {
return entity;
}
@CheckForNull
public String getProjectName() {
return entity == null ? null : entity.getName();
}
@CheckForNull
public String getProjectUuid() {
return entity == null ? null : entity.getUuid();
}
}
| 2,690 | 33.063291 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.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.permission;
import javax.annotation.Nullable;
import org.sonar.api.config.Configuration;
import org.sonar.api.web.UserRole;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.user.UserSession;
import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE;
import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
public class PermissionPrivilegeChecker {
private PermissionPrivilegeChecker() {
// static methods only
}
public static void checkGlobalAdmin(UserSession userSession) {
userSession
.checkLoggedIn()
.checkPermission(GlobalPermission.ADMINISTER);
}
/**
* Checks that user is administrator of the specified project
* @throws org.sonar.server.exceptions.ForbiddenException if user is not administrator
*/
public static void checkProjectAdmin(UserSession userSession, Configuration config, @Nullable EntityDto entity) {
userSession.checkLoggedIn();
if (userSession.hasPermission(GlobalPermission.ADMINISTER)) {
return;
}
boolean allowChangingPermissionsByProjectAdmins = config.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)
.orElse(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE);
if (entity != null && allowChangingPermissionsByProjectAdmins) {
userSession.checkEntityPermission(UserRole.ADMIN, entity);
} else {
throw insufficientPrivilegesException();
}
}
}
| 2,529 | 38.53125 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionTemplateService.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.permission;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ServerSide;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.permission.UserPermissionDto;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateGroupDto;
import org.sonar.db.permission.template.PermissionTemplateUserDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserId;
import org.sonar.server.es.Indexers;
import org.sonar.server.exceptions.TemplateMatchingKeyException;
import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static org.sonar.api.security.DefaultGroups.isAnyone;
import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS;
import static org.sonar.db.permission.GlobalPermission.SCAN;
@ServerSide
public class PermissionTemplateService {
private final DbClient dbClient;
private final Indexers indexers;
private final UserSession userSession;
private final DefaultTemplatesResolver defaultTemplatesResolver;
private final UuidFactory uuidFactory;
public PermissionTemplateService(DbClient dbClient, Indexers indexers, UserSession userSession,
DefaultTemplatesResolver defaultTemplatesResolver, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.indexers = indexers;
this.userSession = userSession;
this.defaultTemplatesResolver = defaultTemplatesResolver;
this.uuidFactory = uuidFactory;
}
public boolean wouldUserHaveScanPermissionWithDefaultTemplate(DbSession dbSession, @Nullable String userUuid, String projectKey) {
if (userSession.hasPermission(SCAN)) {
return true;
}
ProjectDto projectDto = new ProjectDto().setKey(projectKey).setQualifier(Qualifiers.PROJECT);
PermissionTemplateDto template = findTemplate(dbSession, projectDto);
if (template == null) {
return false;
}
List<String> potentialPermissions = dbClient.permissionTemplateDao().selectPotentialPermissionsByUserUuidAndTemplateUuid(dbSession, userUuid, template.getUuid());
return potentialPermissions.contains(SCAN.getKey());
}
/**
* Apply a permission template to a set of projects. Authorization to administrate these projects
* is not verified. The projects must exist, so the "project creator" permissions defined in the
* template are ignored.
*/
public void applyAndCommit(DbSession dbSession, PermissionTemplateDto template, Collection<EntityDto> entities) {
if (entities.isEmpty()) {
return;
}
for (EntityDto entity : entities) {
dbClient.groupPermissionDao().deleteByEntityUuid(dbSession, entity);
dbClient.userPermissionDao().deleteEntityPermissions(dbSession, entity);
copyPermissions(dbSession, template, entity, null);
}
indexers.commitAndIndexEntities(dbSession, entities, Indexers.EntityEvent.PERMISSION_CHANGE);
}
/**
* Apply the default permission template to a new project (has no permissions yet).
*
* @param projectCreatorUserId id of the user creating the project.
*/
public void applyDefaultToNewComponent(DbSession dbSession, EntityDto entityDto, @Nullable String projectCreatorUserId) {
PermissionTemplateDto template = findTemplate(dbSession, entityDto);
checkArgument(template != null, "Cannot retrieve default permission template");
copyPermissions(dbSession, template, entityDto, projectCreatorUserId);
}
public boolean hasDefaultTemplateWithPermissionOnProjectCreator(DbSession dbSession, ProjectDto projectDto) {
PermissionTemplateDto template = findTemplate(dbSession, projectDto);
return hasProjectCreatorPermission(dbSession, template);
}
private boolean hasProjectCreatorPermission(DbSession dbSession, @Nullable PermissionTemplateDto template) {
return template != null && dbClient.permissionTemplateCharacteristicDao().selectByTemplateUuids(dbSession, singletonList(template.getUuid())).stream()
.anyMatch(PermissionTemplateCharacteristicDto::getWithProjectCreator);
}
private void copyPermissions(DbSession dbSession, PermissionTemplateDto template, EntityDto entity, @Nullable String projectCreatorUserUuid) {
List<PermissionTemplateUserDto> usersPermissions = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateId(dbSession, template.getUuid());
Set<String> permissionTemplateUserUuids = usersPermissions.stream().map(PermissionTemplateUserDto::getUserUuid).collect(Collectors.toSet());
Map<String, UserId> userIdByUuid = dbClient.userDao().selectByUuids(dbSession, permissionTemplateUserUuids).stream().collect(Collectors.toMap(UserDto::getUuid, u -> u));
usersPermissions
.stream()
.filter(up -> permissionValidForProject(entity.isPrivate(), up.getPermission()))
.forEach(up -> {
UserPermissionDto dto = new UserPermissionDto(uuidFactory.create(), up.getPermission(), up.getUserUuid(), entity.getUuid());
dbClient.userPermissionDao().insert(dbSession, dto, entity, userIdByUuid.get(up.getUserUuid()), template);
});
List<PermissionTemplateGroupDto> groupsPermissions = dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateUuid(dbSession, template.getUuid());
groupsPermissions
.stream()
.filter(gp -> groupNameValidForProject(entity.isPrivate(), gp.getGroupName()))
.filter(gp -> permissionValidForProject(entity.isPrivate(), gp.getPermission()))
.forEach(gp -> {
String groupUuid = isAnyone(gp.getGroupName()) ? null : gp.getGroupUuid();
String groupName = groupUuid == null ? null : dbClient.groupDao().selectByUuid(dbSession, groupUuid).getName();
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(uuidFactory.create())
.setGroupUuid(groupUuid)
.setGroupName(groupName)
.setRole(gp.getPermission())
.setEntityUuid(entity.getUuid())
.setEntityName(entity.getName());
dbClient.groupPermissionDao().insert(dbSession, dto, entity, template);
});
List<PermissionTemplateCharacteristicDto> characteristics = dbClient.permissionTemplateCharacteristicDao().selectByTemplateUuids(dbSession, singletonList(template.getUuid()));
if (projectCreatorUserUuid != null) {
Set<String> permissionsForCurrentUserAlreadyInDb = usersPermissions.stream()
.filter(userPermission -> projectCreatorUserUuid.equals(userPermission.getUserUuid()))
.map(PermissionTemplateUserDto::getPermission)
.collect(java.util.stream.Collectors.toSet());
UserDto userDto = dbClient.userDao().selectByUuid(dbSession, projectCreatorUserUuid);
characteristics.stream()
.filter(PermissionTemplateCharacteristicDto::getWithProjectCreator)
.filter(up -> permissionValidForProject(entity.isPrivate(), up.getPermission()))
.filter(characteristic -> !permissionsForCurrentUserAlreadyInDb.contains(characteristic.getPermission()))
.forEach(c -> {
UserPermissionDto dto = new UserPermissionDto(uuidFactory.create(), c.getPermission(), userDto.getUuid(), entity.getUuid());
dbClient.userPermissionDao().insert(dbSession, dto, entity, userDto, template);
});
}
}
private static boolean permissionValidForProject(boolean isPrivateEntity, String permission) {
return isPrivateEntity || !PUBLIC_PERMISSIONS.contains(permission);
}
private static boolean groupNameValidForProject(boolean isPrivateEntity, String groupName) {
return !isPrivateEntity || !isAnyone(groupName);
}
/**
* Return the permission template for the given component. If no template key pattern match then consider default
* template for the component qualifier.
*/
@CheckForNull
private PermissionTemplateDto findTemplate(DbSession dbSession, EntityDto entityDto) {
List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession, null);
List<PermissionTemplateDto> matchingTemplates = new ArrayList<>();
for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) {
String keyPattern = permissionTemplateDto.getKeyPattern();
if (StringUtils.isNotBlank(keyPattern) && entityDto.getKey().matches(keyPattern)) {
matchingTemplates.add(permissionTemplateDto);
}
}
checkAtMostOneMatchForComponentKey(entityDto.getKey(), matchingTemplates);
if (matchingTemplates.size() == 1) {
return matchingTemplates.get(0);
}
String qualifier = entityDto.getQualifier();
ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession);
switch (qualifier) {
case Qualifiers.PROJECT:
return dbClient.permissionTemplateDao().selectByUuid(dbSession, resolvedDefaultTemplates.getProject());
case Qualifiers.VIEW:
String portDefaultTemplateUuid = resolvedDefaultTemplates.getPortfolio().orElseThrow(
() -> new IllegalStateException("Failed to find default template for portfolios"));
return dbClient.permissionTemplateDao().selectByUuid(dbSession, portDefaultTemplateUuid);
case Qualifiers.APP:
String appDefaultTemplateUuid = resolvedDefaultTemplates.getApplication().orElseThrow(
() -> new IllegalStateException("Failed to find default template for applications"));
return dbClient.permissionTemplateDao().selectByUuid(dbSession, appDefaultTemplateUuid);
default:
throw new IllegalArgumentException(format("Qualifier '%s' is not supported", qualifier));
}
}
private static void checkAtMostOneMatchForComponentKey(String componentKey, List<PermissionTemplateDto> matchingTemplates) {
if (matchingTemplates.size() > 1) {
StringBuilder templatesNames = new StringBuilder();
for (Iterator<PermissionTemplateDto> it = matchingTemplates.iterator(); it.hasNext(); ) {
templatesNames.append("\"").append(it.next().getName()).append("\"");
if (it.hasNext()) {
templatesNames.append(", ");
}
}
throw new TemplateMatchingKeyException(MessageFormat.format(
"The \"{0}\" key matches multiple permission templates: {1}."
+ " A system administrator must update these templates so that only one of them matches the key.",
componentKey,
templatesNames.toString()));
}
}
}
| 12,029 | 48.102041 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionUpdater.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.permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.sonar.db.DbSession;
import org.sonar.server.es.Indexers;
/**
* Add or remove global/project permissions to a group. This class does not verify that caller has administration right on the related project.
*/
public class PermissionUpdater {
private final Indexers indexers;
private final UserPermissionChanger userPermissionChanger;
private final GroupPermissionChanger groupPermissionChanger;
public PermissionUpdater(Indexers indexers,
UserPermissionChanger userPermissionChanger, GroupPermissionChanger groupPermissionChanger) {
this.indexers = indexers;
this.userPermissionChanger = userPermissionChanger;
this.groupPermissionChanger = groupPermissionChanger;
}
public void apply(DbSession dbSession, Collection<PermissionChange> changes) {
List<String> projectOrViewUuids = new ArrayList<>();
for (PermissionChange change : changes) {
boolean changed = doApply(dbSession, change);
String projectUuid = change.getProjectUuid();
if (changed && projectUuid != null) {
projectOrViewUuids.add(projectUuid);
}
}
indexers.commitAndIndexOnEntityEvent(dbSession, projectOrViewUuids, Indexers.EntityEvent.PERMISSION_CHANGE);
}
private boolean doApply(DbSession dbSession, PermissionChange change) {
if (change instanceof UserPermissionChange userPermissionChange) {
return userPermissionChanger.apply(dbSession, userPermissionChange);
}
if (change instanceof GroupPermissionChange groupPermissionChange) {
return groupPermissionChanger.apply(dbSession, groupPermissionChange);
}
throw new UnsupportedOperationException("Unsupported permission change: " + change.getClass());
}
}
| 2,667 | 38.820896 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/RequestValidator.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.permission;
import com.google.common.base.Joiner;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.exceptions.BadRequestException;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
public class RequestValidator {
public static final String MSG_TEMPLATE_WITH_SAME_NAME = "A template with the name '%s' already exists (case insensitive).";
private final PermissionService permissionService;
private final String allProjectsPermissionsOnOneLine;
public RequestValidator(PermissionService permissionService) {
this.permissionService = permissionService;
allProjectsPermissionsOnOneLine = Joiner.on(", ").join(permissionService.getAllProjectPermissions());
}
public String validateProjectPermission(String permission) {
BadRequestException.checkRequest(permissionService.getAllProjectPermissions().contains(permission),
String.format("The '%s' parameter for project permissions must be one of %s. '%s' was passed.", PARAM_PERMISSION,
allProjectsPermissionsOnOneLine, permission));
return permission;
}
public static void validateGlobalPermission(String permission) {
checkRequest(GlobalPermission.contains(permission),
format("The '%s' parameter for global permissions must be one of %s. '%s' was passed.", PARAM_PERMISSION, GlobalPermission.ALL_ON_ONE_LINE, permission));
}
public static void validateQualifier(@Nullable String qualifier, ResourceTypes resourceTypes) {
if (qualifier == null) {
return;
}
Set<String> rootQualifiers = resourceTypes.getRoots().stream()
.map(ResourceType::getQualifier)
.collect(Collectors.toSet());
checkRequest(rootQualifiers.contains(qualifier),
format("The '%s' parameter must be one of %s. '%s' was passed.", PARAM_QUALIFIER, rootQualifiers, qualifier));
}
public static void validateProjectPattern(@Nullable String projectPattern) {
if (isNullOrEmpty(projectPattern)) {
return;
}
try {
Pattern.compile(projectPattern);
} catch (PatternSyntaxException e) {
throw BadRequestException.create(format("The '%s' parameter must be a valid Java regular expression. '%s' was passed", PARAM_PROJECT_KEY_PATTERN, projectPattern));
}
}
}
| 3,772 | 43.388235 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChange.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.permission;
import javax.annotation.Nullable;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.user.UserId;
import static java.util.Objects.requireNonNull;
public class UserPermissionChange extends PermissionChange {
private final UserId userId;
public UserPermissionChange(Operation operation, String permission, @Nullable EntityDto entity, UserId userId,
PermissionService permissionService) {
super(operation, permission, entity, permissionService);
this.userId = requireNonNull(userId);
}
public UserId getUserId() {
return userId;
}
}
| 1,449 | 33.52381 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/UserPermissionChanger.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.permission;
import java.util.List;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.UserPermissionDto;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionChange.Operation.ADD;
import static org.sonar.server.permission.PermissionChange.Operation.REMOVE;
/**
* Adds and removes user permissions. Both global and project scopes are supported.
*/
public class UserPermissionChanger {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
public UserPermissionChanger(DbClient dbClient, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
}
public boolean apply(DbSession dbSession, UserPermissionChange change) {
ensureConsistencyWithVisibility(change);
if (isImplicitlyAlreadyDone(change)) {
return false;
}
switch (change.getOperation()) {
case ADD:
return addPermission(dbSession, change);
case REMOVE:
return removePermission(dbSession, change);
default:
throw new UnsupportedOperationException("Unsupported permission change: " + change.getOperation());
}
}
private static boolean isImplicitlyAlreadyDone(UserPermissionChange change) {
EntityDto project = change.getEntity();
if (project != null) {
return isImplicitlyAlreadyDone(project, change);
}
return false;
}
private static boolean isImplicitlyAlreadyDone(EntityDto project, UserPermissionChange change) {
return isAttemptToAddPublicPermissionToPublicComponent(change, project);
}
private static boolean isAttemptToAddPublicPermissionToPublicComponent(UserPermissionChange change, EntityDto project) {
return !project.isPrivate()
&& change.getOperation() == ADD
&& UserRole.PUBLIC_PERMISSIONS.contains(change.getPermission());
}
private static void ensureConsistencyWithVisibility(UserPermissionChange change) {
EntityDto project = change.getEntity();
if (project != null) {
checkRequest(!isAttemptToRemovePublicPermissionFromPublicComponent(change, project),
"Permission %s can't be removed from a public component", change.getPermission());
}
}
private static boolean isAttemptToRemovePublicPermissionFromPublicComponent(UserPermissionChange change, EntityDto entity) {
return !entity.isPrivate()
&& change.getOperation() == REMOVE
&& UserRole.PUBLIC_PERMISSIONS.contains(change.getPermission());
}
private boolean addPermission(DbSession dbSession, UserPermissionChange change) {
if (loadExistingPermissions(dbSession, change).contains(change.getPermission())) {
return false;
}
UserPermissionDto dto = new UserPermissionDto(uuidFactory.create(), change.getPermission(), change.getUserId().getUuid(),
change.getProjectUuid());
dbClient.userPermissionDao().insert(dbSession, dto, change.getEntity(), change.getUserId(), null);
return true;
}
private boolean removePermission(DbSession dbSession, UserPermissionChange change) {
if (!loadExistingPermissions(dbSession, change).contains(change.getPermission())) {
return false;
}
checkOtherAdminsExist(dbSession, change);
EntityDto entity = change.getEntity();
if (entity != null) {
dbClient.userPermissionDao().deleteEntityPermission(dbSession, change.getUserId(), change.getPermission(), entity);
} else {
dbClient.userPermissionDao().deleteGlobalPermission(dbSession, change.getUserId(), change.getPermission());
}
return true;
}
private List<String> loadExistingPermissions(DbSession dbSession, UserPermissionChange change) {
String projectUuid = change.getProjectUuid();
if (projectUuid != null) {
return dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, change.getUserId().getUuid(), projectUuid);
}
return dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, change.getUserId().getUuid());
}
private void checkOtherAdminsExist(DbSession dbSession, UserPermissionChange change) {
if (GlobalPermission.ADMINISTER.getKey().equals(change.getPermission()) && change.getProjectUuid() == null) {
int remaining = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingUserPermission(dbSession, change.getPermission(), change.getUserId().getUuid());
checkRequest(remaining > 0, "Last user with permission '%s'. Permission cannot be removed.", GlobalPermission.ADMINISTER.getKey());
}
}
}
| 5,592 | 40.738806 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission.ws;
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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.server.permission.GroupPermissionChange;
import org.sonar.server.permission.GroupUuidOrAnyone;
import org.sonar.server.permission.PermissionChange;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionUpdater;
import org.sonar.server.user.UserSession;
import static org.sonar.server.permission.ws.WsParameters.createGroupNameParameter;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class AddGroupAction implements PermissionsWsAction {
public static final String ACTION = "add_group";
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionUpdater permissionUpdater;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final PermissionService permissionService;
public AddGroupAction(DbClient dbClient, UserSession userSession, PermissionUpdater permissionUpdater, PermissionWsSupport wsSupport,
WsParameters wsParameters, PermissionService permissionService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionUpdater = permissionUpdater;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.permissionService = permissionService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION)
.setDescription("Add a permission to a group.<br /> " +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br /> " +
"The group name must be provided. <br />" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.setSince("5.2")
.setChangelog(
new Change("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."),
new Change("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead."))
.setPost(true)
.setHandler(this);
wsParameters.createPermissionParameter(action, "The permission you would like to grant to the group.");
createGroupNameParameter(action);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
GroupUuidOrAnyone group = wsSupport.findGroup(dbSession, request);
EntityDto project = wsSupport.findEntity(dbSession, request);
wsSupport.checkPermissionManagementAccess(userSession, project);
PermissionChange change = new GroupPermissionChange(
PermissionChange.Operation.ADD,
request.mandatoryParam(PARAM_PERMISSION),
project,
group, permissionService);
permissionUpdater.apply(dbSession, List.of(change));
}
response.noContent();
}
}
| 4,337 | 42.38 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission.ws;
import org.sonar.api.config.Configuration;
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.entity.EntityDto;
import org.sonar.db.user.UserId;
import org.sonar.server.permission.PermissionChange;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionUpdater;
import org.sonar.server.permission.UserPermissionChange;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singletonList;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonar.server.permission.ws.WsParameters.createUserLoginParameter;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN;
public class AddUserAction implements PermissionsWsAction {
public static final String ACTION = "add_user";
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionUpdater permissionUpdater;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final PermissionService permissionService;
private final Configuration configuration;
public AddUserAction(DbClient dbClient, UserSession userSession, PermissionUpdater permissionUpdater, PermissionWsSupport wsSupport,
WsParameters wsParameters, PermissionService permissionService, Configuration configuration) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionUpdater = permissionUpdater;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.permissionService = permissionService;
this.configuration = configuration;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION)
.setDescription("Add permission to a user.<br /> " +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br />" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.setSince("5.2")
.setPost(true)
.setHandler(this);
wsParameters.createPermissionParameter(action, "The permission you would like to grant to the user");
createUserLoginParameter(action);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
String userLogin = request.mandatoryParam(PARAM_USER_LOGIN);
EntityDto entity = wsSupport.findEntity(dbSession, request);
checkProjectAdmin(userSession, configuration, entity);
UserId user = wsSupport.findUser(dbSession, userLogin);
PermissionChange change = new UserPermissionChange(
PermissionChange.Operation.ADD,
request.mandatoryParam(PARAM_PERMISSION),
entity,
user, permissionService);
permissionUpdater.apply(dbSession, singletonList(change));
}
response.noContent();
}
}
| 4,371 | 41.446602 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/GroupsAction.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.permission.ws;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.Resources;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.security.DefaultGroups;
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.Param;
import org.sonar.api.utils.Paging;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.user.GroupDto;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions.Group;
import org.sonarqube.ws.Permissions.WsGroupsResponse;
import static java.util.Collections.emptyList;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toSet;
import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class GroupsAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final ManagedInstanceService managedInstanceService;
public GroupsAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, WsParameters wsParameters,
ManagedInstanceService managedInstanceService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.managedInstanceService = managedInstanceService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("groups")
.setSince("5.2")
.setInternal(true)
.setDescription("Lists the groups with their permissions.<br>" +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br> " +
"This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
.setChangelog(
new Change("10.0", "Response includes 'managed' field."),
new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."),
new Change("7.4", "The response list is returning all groups even those without permissions, the groups with permission are at the top of the list."))
.setResponseExample(Resources.getResource(getClass(), "groups-example.json"))
.setHandler(this);
action.createSearchQuery("sonar", "names")
.setDescription("Limit search to group names that contain the supplied string.")
.setMinimumLength(SEARCH_QUERY_MIN_LENGTH);
wsParameters.createPermissionParameter(action).setRequired(false);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
EntityDto project = wsSupport.findEntity(dbSession, request);
wsSupport.checkPermissionManagementAccess(userSession, project);
PermissionQuery query = buildPermissionQuery(request, project);
List<GroupDto> groups = findGroups(dbSession, query);
int total = dbClient.groupPermissionDao().countGroupsByQuery(dbSession, query);
List<GroupPermissionDto> groupsWithPermission = findGroupPermissions(dbSession, groups, project);
Map<String, Boolean> groupUuidToIsManaged = managedInstanceService.getGroupUuidToManaged(dbSession, getUserUuids(groups));
Paging paging = Paging.forPageIndex(request.mandatoryParamAsInt(Param.PAGE)).withPageSize(query.getPageSize()).andTotal(total);
WsGroupsResponse groupsResponse = buildResponse(groups, groupsWithPermission, groupUuidToIsManaged, paging);
writeProtobuf(groupsResponse, request, response);
}
}
private static Set<String> getUserUuids(List<GroupDto> groups) {
return groups.stream().map(GroupDto::getUuid).collect(toSet());
}
private static PermissionQuery buildPermissionQuery(Request request, @Nullable EntityDto entity) {
String textQuery = request.param(Param.TEXT_QUERY);
PermissionQuery.Builder permissionQuery = PermissionQuery.builder()
.setPermission(request.param(PARAM_PERMISSION))
.setPageIndex(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setSearchQuery(textQuery);
if (entity != null) {
permissionQuery.setEntityUuid(entity.getUuid());
}
return permissionQuery.build();
}
private static WsGroupsResponse buildResponse(List<GroupDto> groups, List<GroupPermissionDto> groupPermissions,
Map<String, Boolean> groupUuidToIsManaged, Paging paging) {
Multimap<String, String> permissionsByGroupUuid = TreeMultimap.create();
groupPermissions.forEach(groupPermission -> permissionsByGroupUuid.put(groupPermission.getGroupUuid(), groupPermission.getRole()));
WsGroupsResponse.Builder response = WsGroupsResponse.newBuilder();
groups.forEach(group -> {
Group.Builder wsGroup = response.addGroupsBuilder()
.setName(group.getName());
if (group.getUuid() != null) {
wsGroup.setId(String.valueOf(group.getUuid()));
}
ofNullable(group.getDescription()).ifPresent(wsGroup::setDescription);
wsGroup.addAllPermissions(permissionsByGroupUuid.get(group.getUuid()));
wsGroup.setManaged(groupUuidToIsManaged.getOrDefault(group.getUuid(), false));
});
response.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total());
return response.build();
}
private List<GroupDto> findGroups(DbSession dbSession, PermissionQuery dbQuery) {
List<String> orderedNames = dbClient.groupPermissionDao().selectGroupNamesByQuery(dbSession, dbQuery);
List<GroupDto> groups = dbClient.groupDao().selectByNames(dbSession, orderedNames);
if (orderedNames.contains(DefaultGroups.ANYONE)) {
groups.add(0, new GroupDto().setUuid(DefaultGroups.ANYONE).setName(DefaultGroups.ANYONE));
}
return Ordering.explicit(orderedNames).onResultOf(GroupDto::getName).immutableSortedCopy(groups);
}
private List<GroupPermissionDto> findGroupPermissions(DbSession dbSession, List<GroupDto> groups, @Nullable EntityDto entity) {
if (groups.isEmpty()) {
return emptyList();
}
List<String> uuids = groups.stream().map(GroupDto::getUuid).toList();
return dbClient.groupPermissionDao().selectByGroupUuids(dbSession, uuids, entity != null ? entity.getUuid() : null);
}
}
| 8,522 | 46.614525 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.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.permission.ws;
import java.util.Optional;
import javax.annotation.CheckForNull;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.Request;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserId;
import org.sonar.db.user.UserIdDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.permission.GroupUuidOrAnyone;
import org.sonar.server.permission.ws.template.WsTemplateRef;
import org.sonar.server.user.UserSession;
import org.sonar.server.usergroups.ws.GroupWsSupport;
import org.sonarqube.ws.client.permission.PermissionsWsParameters;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.util.Optional.ofNullable;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
public class PermissionWsSupport {
private static final String ERROR_REMOVING_OWN_BROWSE_PERMISSION = "Permission 'Browse' cannot be removed from a private project for a project administrator.";
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final GroupWsSupport groupWsSupport;
private final Configuration configuration;
public PermissionWsSupport(DbClient dbClient, Configuration configuration, ComponentFinder componentFinder, GroupWsSupport groupWsSupport) {
this.dbClient = dbClient;
this.configuration = configuration;
this.componentFinder = componentFinder;
this.groupWsSupport = groupWsSupport;
}
public void checkPermissionManagementAccess(UserSession userSession, @Nullable EntityDto entity) {
checkProjectAdmin(userSession, configuration, entity);
}
@CheckForNull
public EntityDto findEntity(DbSession dbSession, Request request) {
String uuid = request.param(PermissionsWsParameters.PARAM_PROJECT_ID);
String key = request.param(PermissionsWsParameters.PARAM_PROJECT_KEY);
if (uuid != null || key != null) {
ProjectWsRef.validateUuidAndKeyPair(uuid, key);
Optional<EntityDto> entityDto = uuid != null ? dbClient.entityDao().selectByUuid(dbSession, uuid) : dbClient.entityDao().selectByKey(dbSession, key);
if (entityDto.isPresent() && !Qualifiers.SUBVIEW.equals(entityDto.get().getQualifier())) {
return entityDto.get();
} else {
throw new NotFoundException("Entity not found");
}
}
return null;
}
public GroupUuidOrAnyone findGroup(DbSession dbSession, Request request) {
String groupName = request.mandatoryParam(PARAM_GROUP_NAME);
return groupWsSupport.findGroupOrAnyone(dbSession, groupName);
}
public UserId findUser(DbSession dbSession, String login) {
UserDto dto = ofNullable(dbClient.userDao().selectActiveUserByLogin(dbSession, login))
.orElseThrow(() -> new NotFoundException(format("User with login '%s' is not found'", login)));
return new UserIdDto(dto.getUuid(), dto.getLogin());
}
public PermissionTemplateDto findTemplate(DbSession dbSession, WsTemplateRef ref) {
String uuid = ref.uuid();
String name = ref.name();
if (uuid != null) {
return checkFound(
dbClient.permissionTemplateDao().selectByUuid(dbSession, uuid),
"Permission template with id '%s' is not found", uuid);
} else {
checkNotNull(name);
return checkFound(
dbClient.permissionTemplateDao().selectByName(dbSession, name),
"Permission template with name '%s' is not found (case insensitive)", name);
}
}
public void checkRemovingOwnAdminRight(UserSession userSession, UserId user, String permission) {
if (ADMINISTER.getKey().equals(permission) && isRemovingOwnPermission(userSession, user)) {
throw BadRequestException.create("As an admin, you can't remove your own admin right");
}
}
private static boolean isRemovingOwnPermission(UserSession userSession, UserId user) {
return user.getLogin().equals(userSession.getLogin());
}
public void checkRemovingOwnBrowsePermissionOnPrivateProject(DbSession dbSession, UserSession userSession, @Nullable EntityDto entityDto, String permission,
GroupUuidOrAnyone group) {
if (userSession.isSystemAdministrator() || group.isAnyone() || !isUpdatingBrowsePermissionOnPrivateProject(permission, entityDto)) {
return;
}
Set<String> groupUuidsWithPermission = dbClient.groupPermissionDao().selectGroupUuidsWithPermissionOnEntity(dbSession, entityDto.getUuid(), UserRole.USER);
boolean isUserInAnotherGroupWithPermissionForThisProject = userSession.getGroups().stream()
.map(GroupDto::getUuid)
.anyMatch(groupDtoUuid -> groupUuidsWithPermission.contains(groupDtoUuid) && !groupDtoUuid.equals(group.getUuid()));
if (!isUserInAnotherGroupWithPermissionForThisProject) {
throw BadRequestException.create(ERROR_REMOVING_OWN_BROWSE_PERMISSION);
}
}
public void checkRemovingOwnBrowsePermissionOnPrivateProject(UserSession userSession, @Nullable EntityDto entityDto, String permission, UserId user) {
if (isUpdatingBrowsePermissionOnPrivateProject(permission, entityDto) && user.getLogin().equals(userSession.getLogin())) {
throw BadRequestException.create(ERROR_REMOVING_OWN_BROWSE_PERMISSION);
}
}
public static boolean isUpdatingBrowsePermissionOnPrivateProject(String permission, @Nullable EntityDto entityDto) {
return entityDto != null && entityDto.isPrivate() && permission.equals(UserRole.USER) ;
}
}
| 6,987 | 43.794872 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionsWs.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.permission.ws;
import org.sonar.api.server.ws.WebService;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.CONTROLLER;
public class PermissionsWs implements WebService {
private final PermissionsWsAction[] actions;
public PermissionsWs(PermissionsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER);
controller.setDescription("Manage permission templates, and the granting and revoking of permissions at the global and project levels.");
controller.setSince("3.7");
for (PermissionsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,617 | 34.173913 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionsWsAction.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.permission.ws;
import org.sonar.server.ws.WsAction;
public interface PermissionsWsAction extends WsAction {
// marker interface
}
| 1,002 | 36.148148 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/PermissionsWsModule.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.permission.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.permission.PermissionServiceImpl;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.template.AddGroupToTemplateAction;
import org.sonar.server.permission.ws.template.AddProjectCreatorToTemplateAction;
import org.sonar.server.permission.ws.template.AddUserToTemplateAction;
import org.sonar.server.permission.ws.template.ApplyTemplateAction;
import org.sonar.server.permission.ws.template.BulkApplyTemplateAction;
import org.sonar.server.permission.ws.template.CreateTemplateAction;
import org.sonar.server.permission.ws.template.DeleteTemplateAction;
import org.sonar.server.permission.ws.template.RemoveGroupFromTemplateAction;
import org.sonar.server.permission.ws.template.RemoveProjectCreatorFromTemplateAction;
import org.sonar.server.permission.ws.template.RemoveUserFromTemplateAction;
import org.sonar.server.permission.ws.template.SearchTemplatesAction;
import org.sonar.server.permission.ws.template.SetDefaultTemplateAction;
import org.sonar.server.permission.ws.template.TemplateGroupsAction;
import org.sonar.server.permission.ws.template.TemplateUsersAction;
import org.sonar.server.permission.ws.template.UpdateTemplateAction;
public class PermissionsWsModule extends Module {
@Override
protected void configureModule() {
add(
PermissionsWs.class,
// actions
AddGroupAction.class,
AddUserAction.class,
RemoveGroupAction.class,
RemoveUserAction.class,
UsersAction.class,
GroupsAction.class,
RemoveUserFromTemplateAction.class,
AddUserToTemplateAction.class,
AddGroupToTemplateAction.class,
AddProjectCreatorToTemplateAction.class,
RemoveProjectCreatorFromTemplateAction.class,
RemoveGroupFromTemplateAction.class,
CreateTemplateAction.class,
UpdateTemplateAction.class,
DeleteTemplateAction.class,
ApplyTemplateAction.class,
SetDefaultTemplateAction.class,
SearchTemplatesAction.class,
TemplateUsersAction.class,
TemplateGroupsAction.class,
BulkApplyTemplateAction.class,
// utility classes
PermissionWsSupport.class,
PermissionServiceImpl.class,
RequestValidator.class,
WsParameters.class);
}
}
| 3,177 | 41.373333 | 86 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/ProjectWsRef.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.permission.ws;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
/**
* Reference to a project <b>as defined by web service callers</b>. It allows to reference a project
* by its (functional) key or by its (technical) uuid.
*
* <p>Factory methods guarantee that the project id and project key are not provided at the same time.</p>
*/
public class ProjectWsRef {
private static final String MSG_ID_OR_KEY_MUST_BE_PROVIDED = "Project id or project key can be provided, not both.";
private final String uuid;
private final String key;
private ProjectWsRef(@Nullable String uuid, @Nullable String key) {
validateUuidAndKeyPair(uuid, key);
this.uuid = uuid;
this.key = key;
}
public static void validateUuidAndKeyPair(@Nullable String uuid, @Nullable String key) {
checkRequest(uuid != null ^ key != null, MSG_ID_OR_KEY_MUST_BE_PROVIDED);
}
public static ProjectWsRef newWsProjectRef(@Nullable String uuid, @Nullable String key) {
return new ProjectWsRef(uuid, key);
}
@CheckForNull
public String uuid() {
return this.uuid;
}
@CheckForNull
public String key() {
return this.key;
}
}
| 2,115 | 33.129032 | 118 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission.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.entity.EntityDto;
import org.sonar.server.permission.GroupPermissionChange;
import org.sonar.server.permission.GroupUuidOrAnyone;
import org.sonar.server.permission.PermissionChange;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionUpdater;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singletonList;
import static org.sonar.server.permission.ws.WsParameters.createGroupNameParameter;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class RemoveGroupAction implements PermissionsWsAction {
public static final String ACTION = "remove_group";
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionUpdater permissionUpdater;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final PermissionService permissionService;
public RemoveGroupAction(DbClient dbClient, UserSession userSession, PermissionUpdater permissionUpdater, PermissionWsSupport wsSupport,
WsParameters wsParameters, PermissionService permissionService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionUpdater = permissionUpdater;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.permissionService = permissionService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION)
.setDescription("Remove a permission from a group.<br /> " +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br /> " +
"The group name must be provided.<br />" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.setSince("5.2")
.setPost(true)
.setChangelog(
new Change("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."),
new Change("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead."))
.setHandler(this);
wsParameters.createPermissionParameter(action, "The permission you would like to revoke from the group.");
createGroupNameParameter(action);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
GroupUuidOrAnyone group = wsSupport.findGroup(dbSession, request);
EntityDto entity = wsSupport.findEntity(dbSession, request);
wsSupport.checkPermissionManagementAccess(userSession, entity);
String permission = request.mandatoryParam(PARAM_PERMISSION);
wsSupport.checkRemovingOwnBrowsePermissionOnPrivateProject(dbSession, userSession, entity, permission, group);
PermissionChange change = new GroupPermissionChange(
PermissionChange.Operation.REMOVE,
permission,
entity,
group,
permissionService);
permissionUpdater.apply(dbSession, singletonList(change));
}
response.noContent();
}
}
| 4,558 | 41.212963 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission.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.entity.EntityDto;
import org.sonar.db.user.UserId;
import org.sonar.server.permission.PermissionChange;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionUpdater;
import org.sonar.server.permission.UserPermissionChange;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singletonList;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonar.server.permission.ws.WsParameters.createUserLoginParameter;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN;
public class RemoveUserAction implements PermissionsWsAction {
public static final String ACTION = "remove_user";
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionUpdater permissionUpdater;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final PermissionService permissionService;
public RemoveUserAction(DbClient dbClient, UserSession userSession, PermissionUpdater permissionUpdater, PermissionWsSupport wsSupport,
WsParameters wsParameters, PermissionService permissionService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionUpdater = permissionUpdater;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.permissionService = permissionService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION)
.setDescription("Remove permission from a user.<br /> " +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br /> " +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.setSince("5.2")
.setPost(true)
.setHandler(this);
wsParameters.createPermissionParameter(action, "The permission you would like to revoke from the user.");
createUserLoginParameter(action);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
UserId user = wsSupport.findUser(dbSession, request.mandatoryParam(PARAM_USER_LOGIN));
String permission = request.mandatoryParam(PARAM_PERMISSION);
wsSupport.checkRemovingOwnAdminRight(userSession, user, permission);
EntityDto entity = wsSupport.findEntity(dbSession, request);
wsSupport.checkRemovingOwnBrowsePermissionOnPrivateProject(userSession, entity, permission, user);
wsSupport.checkPermissionManagementAccess(userSession, entity);
PermissionChange change = new UserPermissionChange(
PermissionChange.Operation.REMOVE,
permission,
entity,
user, permissionService);
permissionUpdater.apply(dbSession, singletonList(change));
response.noContent();
}
}
}
| 4,340 | 42.41 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/UsersAction.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.permission.ws;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.TreeMultimap;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.UserPermissionDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolver;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions;
import org.sonarqube.ws.Permissions.UsersWsResponse;
import static com.google.common.base.Strings.emptyToNull;
import static java.util.Collections.emptyList;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toSet;
import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
import static org.sonar.server.permission.RequestValidator.validateGlobalPermission;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class UsersAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionWsSupport wsSupport;
private final AvatarResolver avatarResolver;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
private final ManagedInstanceService managedInstanceService;
public UsersAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, AvatarResolver avatarResolver, WsParameters wsParameters,
RequestValidator requestValidator, ManagedInstanceService managedInstanceService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
this.avatarResolver = avatarResolver;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
this.managedInstanceService = managedInstanceService;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("users")
.setSince("5.2")
.setDescription("Lists the users with their permissions as individual users rather than through group affiliation.<br>" +
"This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br> " +
"This service defaults to all users, but can be limited to users with a specific permission by providing the desired permission.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
.setChangelog(
new Change("10.0", "Response includes 'managed' field."),
new Change("7.4", "The response list is returning all users even those without permissions, the users with permission are at the top of the list."))
.setInternal(true)
.setResponseExample(getClass().getResource("users-example.json"))
.setHandler(this);
action.createParam(Param.TEXT_QUERY)
.setMinimumLength(SEARCH_QUERY_MIN_LENGTH)
.setDescription("Limit search to user names that contain the supplied string. <br/>")
.setExampleValue("eri");
wsParameters.createPermissionParameter(action).setRequired(false);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
EntityDto entity = wsSupport.findEntity(dbSession, request);
wsSupport.checkPermissionManagementAccess(userSession, entity);
PermissionQuery query = buildPermissionQuery(request, entity);
List<UserDto> users = findUsers(dbSession, query);
int total = dbClient.userPermissionDao().countUsersByQuery(dbSession, query);
List<UserPermissionDto> userPermissions = findUserPermissions(dbSession, users, entity);
Paging paging = Paging.forPageIndex(request.mandatoryParamAsInt(Param.PAGE)).withPageSize(query.getPageSize()).andTotal(total);
Map<String, Boolean> userUuidToIsManaged = managedInstanceService.getUserUuidToManaged(dbSession, getUserUuids(users));
UsersWsResponse usersWsResponse = buildResponse(users, userPermissions, userUuidToIsManaged, paging);
writeProtobuf(usersWsResponse, request, response);
}
}
private static Set<String> getUserUuids(List<UserDto> users) {
return users.stream().map(UserDto::getUuid).collect(toSet());
}
private PermissionQuery buildPermissionQuery(Request request, @Nullable EntityDto entity) {
String textQuery = request.param(Param.TEXT_QUERY);
String permission = request.param(PARAM_PERMISSION);
PermissionQuery.Builder permissionQuery = PermissionQuery.builder()
.setPermission(permission)
.setPageIndex(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setSearchQuery(textQuery);
if (entity != null) {
permissionQuery.setEntityUuid(entity.getUuid());
}
if (permission != null) {
if (entity != null) {
requestValidator.validateProjectPermission(permission);
} else {
validateGlobalPermission(permission);
}
}
return permissionQuery.build();
}
private UsersWsResponse buildResponse(List<UserDto> users, List<UserPermissionDto> userPermissions, Map<String, Boolean> userUuidToIsManaged,
Paging paging) {
Multimap<String, String> permissionsByUserUuid = TreeMultimap.create();
userPermissions.forEach(userPermission -> permissionsByUserUuid.put(userPermission.getUserUuid(), userPermission.getPermission()));
UsersWsResponse.Builder response = UsersWsResponse.newBuilder();
users.forEach(user -> {
Permissions.User.Builder userResponse = response.addUsersBuilder()
.setLogin(user.getLogin())
.addAllPermissions(permissionsByUserUuid.get(user.getUuid()));
ofNullable(user.getEmail()).ifPresent(userResponse::setEmail);
ofNullable(emptyToNull(user.getEmail())).ifPresent(u -> userResponse.setAvatar(avatarResolver.create(user)));
ofNullable(user.getName()).ifPresent(userResponse::setName);
ofNullable(userUuidToIsManaged.get(user.getUuid())).ifPresent(userResponse::setManaged);
});
response.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total())
.build();
return response.build();
}
private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query) {
List<String> orderedUuids = dbClient.userPermissionDao().selectUserUuidsByQueryAndScope(dbSession, query);
return Ordering.explicit(orderedUuids).onResultOf(UserDto::getUuid).immutableSortedCopy(dbClient.userDao().selectByUuids(dbSession, orderedUuids));
}
private List<UserPermissionDto> findUserPermissions(DbSession dbSession, List<UserDto> users, @Nullable EntityDto entity) {
if (users.isEmpty()) {
return emptyList();
}
List<String> userUuids = users.stream().map(UserDto::getUuid).toList();
PermissionQuery.Builder queryBuilder = PermissionQuery.builder()
.withAtLeastOnePermission();
if (entity != null) {
queryBuilder.setEntityUuid(entity.getUuid());
}
return dbClient.userPermissionDao().selectUserPermissionsByQuery(dbSession, queryBuilder.build(), userUuids);
}
}
| 9,150 | 45.217172 | 156 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/WsParameters.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.permission.ws;
import com.google.common.base.Joiner;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.permission.PermissionService;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN;
public class WsParameters {
private final String permissionParamDescription;
private final String projectPermissionParamDescription;
private final PermissionService permissionService;
public WsParameters(PermissionService permissionService) {
this.permissionService = permissionService;
String allProjectsPermissionsOnOneLine = Joiner.on(", ").join(permissionService.getAllProjectPermissions());
permissionParamDescription = String.format("<ul>" +
"<li>Possible values for global permissions: %s</li>" +
"<li>Possible values for project permissions %s</li>" +
"</ul>",
GlobalPermission.ALL_ON_ONE_LINE,
allProjectsPermissionsOnOneLine);
projectPermissionParamDescription = String.format("Permission" +
"<ul>" +
"<li>Possible values for project permissions %s</li>" +
"</ul>",
allProjectsPermissionsOnOneLine);
}
public WebService.NewParam createPermissionParameter(WebService.NewAction action) {
return createPermissionParameter(action, "Permission.");
}
public WebService.NewParam createPermissionParameter(WebService.NewAction action, String descriptionHeader) {
return action.createParam(PARAM_PERMISSION)
.setDescription(descriptionHeader + permissionParamDescription)
.setRequired(true);
}
public WebService.NewParam createProjectPermissionParameter(WebService.NewAction action, boolean required) {
return action.createParam(PARAM_PERMISSION)
.setDescription(projectPermissionParamDescription)
.setPossibleValues(permissionService.getAllProjectPermissions())
.setRequired(required);
}
public WebService.NewParam createProjectPermissionParameter(WebService.NewAction action) {
return createProjectPermissionParameter(action, true);
}
public static void createGroupNameParameter(WebService.NewAction action) {
action.createParam(PARAM_GROUP_NAME)
.setRequired(true)
.setDescription("Group name or 'anyone' (case insensitive)")
.setExampleValue("sonar-administrators");
}
public static void createProjectParameters(WebService.NewAction action) {
action.createParam(PARAM_PROJECT_ID)
.setDescription("Project id")
.setExampleValue("ce4c03d6-430f-40a9-b777-ad877c00aa4d");
createProjectKeyParameter(action);
}
private static void createProjectKeyParameter(WebService.NewAction action) {
action.createParam(PARAM_PROJECT_KEY)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
}
public static void createUserLoginParameter(WebService.NewAction action) {
action.createParam(PARAM_USER_LOGIN)
.setRequired(true)
.setDescription("User login")
.setExampleValue("g.hopper");
}
public static void createTemplateParameters(WebService.NewAction action) {
action.createParam(PARAM_TEMPLATE_ID)
.setDescription("Template id")
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_TEMPLATE_NAME)
.setDescription("Template name")
.setExampleValue("Default Permission Template for Projects");
}
public static void createTemplateProjectKeyPatternParameter(WebService.NewAction action) {
action.createParam(PARAM_PROJECT_KEY_PATTERN)
.setDescription("Project key pattern. Must be a valid Java regular expression")
.setExampleValue(".*\\.finance\\..*");
}
public static void createTemplateDescriptionParameter(WebService.NewAction action) {
action.createParam(PARAM_DESCRIPTION)
.setDescription("Description")
.setExampleValue("Permissions for all projects related to the financial service");
}
public static void createIdParameter(WebService.NewAction action) {
action.createParam(PARAM_ID)
.setRequired(true)
.setDescription("Id")
.setExampleValue("af8cb8cc-1e78-4c4e-8c00-ee8e814009a5");
}
}
| 5,976 | 42.311594 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/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.permission.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 970 | 39.458333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/AddGroupToTemplateAction.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.permission.ws.template;
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.template.PermissionTemplateDto;
import org.sonar.server.permission.GroupUuidOrAnyone;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createGroupNameParameter;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.permission.ws.template.WsTemplateRef.fromRequest;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class AddGroupToTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport support;
private final UserSession userSession;
private final WsParameters wsParameters;
public AddGroupToTemplateAction(DbClient dbClient, PermissionWsSupport support, UserSession userSession, WsParameters wsParameters) {
this.dbClient = dbClient;
this.support = support;
this.userSession = userSession;
this.wsParameters = wsParameters;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction("add_group_to_template")
.setPost(true)
.setSince("5.2")
.setDescription("Add a group to a permission template.<br /> " +
"The group name must be provided. <br />" +
"Requires the following permission: 'Administer System'.")
.setChangelog(
new Change("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."),
new Change("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead."))
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
createGroupNameParameter(action);
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
String permission = request.mandatoryParam(PARAM_PERMISSION);
GroupUuidOrAnyone group = support.findGroup(dbSession, request);
checkRequest(!ADMINISTER.getKey().equals(permission) || !group.isAnyone(),
format("It is not possible to add the '%s' permission to the group 'Anyone'.", permission));
PermissionTemplateDto template = support.findTemplate(dbSession, fromRequest(request));
checkGlobalAdmin(userSession);
if (!groupAlreadyAdded(dbSession, template.getUuid(), permission, group)) {
dbClient.permissionTemplateDao().insertGroupPermission(dbSession, template.getUuid(), group.getUuid(), permission,
template.getName(), request.param(PARAM_GROUP_NAME));
dbSession.commit();
}
}
response.noContent();
}
private boolean groupAlreadyAdded(DbSession dbSession, String templateUuid, String permission, GroupUuidOrAnyone group) {
return dbClient.permissionTemplateDao().hasGroupsWithPermission(dbSession, templateUuid, permission, group.getUuid());
}
}
| 4,633 | 44.881188 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateAction.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.permission.ws.template;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class AddProjectCreatorToTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final UserSession userSession;
private final System2 system;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
public AddProjectCreatorToTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, UserSession userSession, System2 system,
WsParameters wsParameters, RequestValidator requestValidator) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.userSession = userSession;
this.system = system;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
}
private AddProjectCreatorToTemplateRequest toWsRequest(Request request) {
AddProjectCreatorToTemplateRequest wsRequest = AddProjectCreatorToTemplateRequest.builder()
.setPermission(request.mandatoryParam(PARAM_PERMISSION))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME))
.build();
requestValidator.validateProjectPermission(wsRequest.getPermission());
return wsRequest;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("add_project_creator_to_template")
.setDescription("Add a project creator to a permission template.<br>" +
"Requires the following permission: 'Administer System'.")
.setSince("6.0")
.setPost(true)
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toWsRequest(request));
response.noContent();
}
private void doHandle(AddProjectCreatorToTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, WsTemplateRef.newTemplateRef(request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
Optional<PermissionTemplateCharacteristicDto> templatePermission = dbClient.permissionTemplateCharacteristicDao()
.selectByPermissionAndTemplateId(dbSession, request.getPermission(), template.getUuid());
if (templatePermission.isPresent()) {
updateTemplatePermission(dbSession, templatePermission.get(), template.getName());
} else {
addTemplatePermission(dbSession, request, template);
}
}
}
private void addTemplatePermission(DbSession dbSession, AddProjectCreatorToTemplateRequest request, PermissionTemplateDto template) {
long now = system.now();
dbClient.permissionTemplateCharacteristicDao().insert(dbSession, new PermissionTemplateCharacteristicDto()
.setUuid(Uuids.create())
.setPermission(request.getPermission())
.setTemplateUuid(template.getUuid())
.setWithProjectCreator(true)
.setCreatedAt(now)
.setUpdatedAt(now),
template.getName());
dbSession.commit();
}
private void updateTemplatePermission(DbSession dbSession, PermissionTemplateCharacteristicDto templatePermission, String templateName) {
PermissionTemplateCharacteristicDto targetTemplatePermission = templatePermission
.setUpdatedAt(system.now())
.setWithProjectCreator(true);
dbClient.permissionTemplateCharacteristicDao().update(dbSession, targetTemplatePermission, templateName);
dbSession.commit();
}
private static class AddProjectCreatorToTemplateRequest {
private final String templateId;
private final String templateName;
private final String permission;
private AddProjectCreatorToTemplateRequest(Builder builder) {
this.templateId = builder.templateId;
this.templateName = builder.templateName;
this.permission = requireNonNull(builder.permission);
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public String getPermission() {
return permission;
}
public static Builder builder() {
return new Builder();
}
}
private static class Builder {
private String templateId;
private String templateName;
private String permission;
private Builder() {
// enforce method constructor
}
public Builder setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
public Builder setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
public Builder setPermission(@Nullable String permission) {
this.permission = permission;
return this;
}
public AddProjectCreatorToTemplateRequest build() {
return new AddProjectCreatorToTemplateRequest(this);
}
}
}
| 7,181 | 37 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/AddUserToTemplateAction.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.permission.ws.template;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.PermissionQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.UserId;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.permission.ws.WsParameters.createUserLoginParameter;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN;
public class AddUserToTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final UserSession userSession;
private final WsParameters wsParameters;
public AddUserToTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, UserSession userSession, WsParameters wsParameters) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.userSession = userSession;
this.wsParameters = wsParameters;
}
private static AddUserToTemplateRequest toAddUserToTemplateWsRequest(Request request) {
return new AddUserToTemplateRequest()
.setLogin(request.mandatoryParam(PARAM_USER_LOGIN))
.setPermission(request.mandatoryParam(PARAM_PERMISSION))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME));
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction("add_user_to_template")
.setPost(true)
.setSince("5.2")
.setDescription("Add a user to a permission template.<br /> " +
"Requires the following permission: 'Administer System'.")
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
createUserLoginParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toAddUserToTemplateWsRequest(request));
response.noContent();
}
private void doHandle(AddUserToTemplateRequest request) {
String permission = request.getPermission();
String userLogin = request.getLogin();
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
UserId user = wsSupport.findUser(dbSession, userLogin);
if (!isUserAlreadyAdded(dbSession, template.getUuid(), userLogin, permission)) {
dbClient.permissionTemplateDao().insertUserPermission(dbSession, template.getUuid(), user.getUuid(), permission,
template.getName(), user.getLogin());
dbSession.commit();
}
}
}
private boolean isUserAlreadyAdded(DbSession dbSession, String templateUuid, String userLogin, String permission) {
PermissionQuery permissionQuery = PermissionQuery.builder().setPermission(permission).build();
List<String> usersWithPermission = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, permissionQuery, templateUuid);
return usersWithPermission.stream().anyMatch(s -> s.equals(userLogin));
}
private static class AddUserToTemplateRequest {
private String login;
private String permission;
private String templateId;
private String templateName;
public String getLogin() {
return login;
}
public AddUserToTemplateRequest setLogin(String login) {
this.login = requireNonNull(login);
return this;
}
public String getPermission() {
return permission;
}
public AddUserToTemplateRequest setPermission(String permission) {
this.permission = requireNonNull(permission);
return this;
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
public AddUserToTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public AddUserToTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
}
| 6,116 | 37.471698 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/ApplyTemplateAction.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.permission.ws.template;
import java.util.Collections;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
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.entity.EntityDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.permission.PermissionTemplateService;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.ProjectWsRef;
import org.sonar.server.user.UserSession;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class ApplyTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionTemplateService permissionTemplateService;
private final PermissionWsSupport wsSupport;
public ApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService,
PermissionWsSupport wsSupport) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionTemplateService = permissionTemplateService;
this.wsSupport = wsSupport;
}
private static ApplyTemplateRequest toApplyTemplateWsRequest(Request request) {
return new ApplyTemplateRequest()
.setProjectId(request.param(PARAM_PROJECT_ID))
.setProjectKey(request.param(PARAM_PROJECT_KEY))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME));
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("apply_template")
.setDescription("Apply a permission template to one project.<br>" +
"The project id or project key must be provided.<br>" +
"The template id or name must be provided.<br>" +
"Requires the following permission: 'Administer System'.")
.setPost(true)
.setSince("5.2")
.setHandler(this);
createTemplateParameters(action);
createProjectParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toApplyTemplateWsRequest(request));
response.noContent();
}
private void doHandle(ApplyTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
request.getTemplateId(), request.getTemplateName()));
ProjectWsRef.validateUuidAndKeyPair(request.getProjectId(), request.getProjectKey());
EntityDto entityDto = getEntityByKeyOrUuid(request.getProjectId(), request.getProjectKey(), dbSession);
checkGlobalAdmin(userSession);
permissionTemplateService.applyAndCommit(dbSession, template, Collections.singletonList(entityDto));
}
}
private EntityDto getEntityByKeyOrUuid(@Nullable String uuid, @Nullable String key, DbSession dbSession) {
Optional<EntityDto> entityDto = uuid != null ? dbClient.entityDao().selectByUuid(dbSession, uuid) : dbClient.entityDao().selectByKey(dbSession, key);
if (entityDto.isPresent() && !Qualifiers.SUBVIEW.equals(entityDto.get().getQualifier())) {
return entityDto.get();
} else {
throw new NotFoundException("Entity not found");
}
}
private static class ApplyTemplateRequest {
private String projectId;
private String projectKey;
private String templateId;
private String templateName;
@CheckForNull
public String getProjectId() {
return projectId;
}
public ApplyTemplateRequest setProjectId(@Nullable String projectId) {
this.projectId = projectId;
return this;
}
@CheckForNull
public String getProjectKey() {
return projectKey;
}
public ApplyTemplateRequest setProjectKey(@Nullable String projectKey) {
this.projectKey = projectKey;
return this;
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
public ApplyTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public ApplyTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
}
| 6,226 | 37.438272 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/BulkApplyTemplateAction.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.permission.ws.template;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
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.Param;
import org.sonar.core.i18n.I18n;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentQuery;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.PermissionTemplateService;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static java.util.Collections.singleton;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
import static org.sonar.server.ws.WsParameterBuilder.createRootQualifiersParameter;
import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
public class BulkApplyTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionTemplateService permissionTemplateService;
private final PermissionWsSupport wsSupport;
private final I18n i18n;
private final ResourceTypes resourceTypes;
public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService, PermissionWsSupport wsSupport, I18n i18n,
ResourceTypes resourceTypes) {
this.dbClient = dbClient;
this.userSession = userSession;
this.permissionTemplateService = permissionTemplateService;
this.wsSupport = wsSupport;
this.i18n = i18n;
this.resourceTypes = resourceTypes;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("bulk_apply_template")
.setDescription("Apply a permission template to several projects.<br />" +
"The template id or name must be provided.<br />" +
"Requires the following permission: 'Administer System'.")
.setPost(true)
.setSince("5.5")
.setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
.setHandler(this);
action.createParam(Param.TEXT_QUERY)
.setDescription("Limit search to: <ul>" +
"<li>project names that contain the supplied string</li>" +
"<li>project keys that are exactly the same as the supplied string</li>" +
"</ul>")
.setExampleValue("apac");
createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
.setDefaultValue(Qualifiers.PROJECT);
WsParameters.createTemplateParameters(action);
action
.createParam(PARAM_PROJECTS)
.setDescription("Comma-separated list of project keys")
.setSince("6.6")
// Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
// Restricting size of HTTP parameter allows to not fail with SQL error
.setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
.setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
action.createParam(PARAM_VISIBILITY)
.setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
"If no visibility is specified, the default project visibility will be used.",
Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
.setRequired(false)
.setInternal(true)
.setSince("6.6")
.setPossibleValues(Visibility.getLabels());
action.createParam(PARAM_ANALYZED_BEFORE)
.setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
"Either a date (server timezone) or datetime can be provided.")
.setSince("6.6")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_ON_PROVISIONED_ONLY)
.setDescription("Filter the projects that are provisioned")
.setBooleanPossibleValues()
.setDefaultValue("false")
.setSince("6.6");
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toBulkApplyTemplateWsRequest(request));
response.noContent();
}
private void doHandle(BulkApplyTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
ComponentQuery componentQuery = buildDbQuery(request);
List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
List<EntityDto> entities = dbClient.entityDao().selectByKeys(dbSession, components.stream()
.map(ComponentDto::getKey)
.collect(Collectors.toSet()));
permissionTemplateService.applyAndCommit(dbSession, template, entities);
}
}
private static BulkApplyTemplateRequest toBulkApplyTemplateWsRequest(Request request) {
return new BulkApplyTemplateRequest()
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME))
.setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
.setQuery(request.param(Param.TEXT_QUERY))
.setVisibility(request.param(PARAM_VISIBILITY))
.setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
.setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
.setProjects(request.paramAsStrings(PARAM_PROJECTS));
}
private static ComponentQuery buildDbQuery(BulkApplyTemplateRequest request) {
Collection<String> qualifiers = request.getQualifiers();
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
ofNullable(request.getQuery()).ifPresent(q -> {
query.setNameOrKeyQuery(q);
query.setPartialMatchOnKey(true);
});
ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
query.setOnProvisionedOnly(request.isOnProvisionedOnly());
ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
return query.build();
}
private static class BulkApplyTemplateRequest {
private String templateId;
private String templateName;
private String query;
private Collection<String> qualifiers = singleton(Qualifiers.PROJECT);
private String visibility;
private String analyzedBefore;
private boolean onProvisionedOnly = false;
private Collection<String> projects;
@CheckForNull
public String getTemplateId() {
return templateId;
}
public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
@CheckForNull
public String getQuery() {
return query;
}
public BulkApplyTemplateRequest setQuery(@Nullable String query) {
this.query = query;
return this;
}
public Collection<String> getQualifiers() {
return qualifiers;
}
public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
this.qualifiers = requireNonNull(qualifiers);
return this;
}
@CheckForNull
public String getVisibility() {
return visibility;
}
public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
this.visibility = visibility;
return this;
}
@CheckForNull
public String getAnalyzedBefore() {
return analyzedBefore;
}
public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
this.analyzedBefore = analyzedBefore;
return this;
}
public boolean isOnProvisionedOnly() {
return onProvisionedOnly;
}
public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
this.onProvisionedOnly = onProvisionedOnly;
return this;
}
@CheckForNull
public Collection<String> getProjects() {
return projects;
}
public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
this.projects = projects;
return this;
}
}
}
| 11,304 | 38.946996 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/CreateTemplateAction.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.permission.ws.template;
import java.util.Date;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions.CreateTemplateWsResponse;
import org.sonarqube.ws.Permissions.PermissionTemplate;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.RequestValidator.MSG_TEMPLATE_WITH_SAME_NAME;
import static org.sonar.server.permission.ws.template.PermissionTemplateDtoToPermissionTemplateResponse.toPermissionTemplateResponse;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN;
public class CreateTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final System2 system;
public CreateTemplateAction(DbClient dbClient, UserSession userSession, System2 system) {
this.dbClient = dbClient;
this.userSession = userSession;
this.system = system;
}
private static CreateTemplateRequest toCreateTemplateWsRequest(Request request) {
return new CreateTemplateRequest()
.setName(request.mandatoryParam(PARAM_NAME))
.setDescription(request.param(PARAM_DESCRIPTION))
.setProjectKeyPattern(request.param(PARAM_PROJECT_KEY_PATTERN));
}
private static CreateTemplateWsResponse buildResponse(PermissionTemplateDto permissionTemplateDto) {
PermissionTemplate permissionTemplateBuilder = toPermissionTemplateResponse(permissionTemplateDto);
return CreateTemplateWsResponse.newBuilder().setPermissionTemplate(permissionTemplateBuilder).build();
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("create_template")
.setDescription("Create a permission template.<br />" +
"Requires the following permission: 'Administer System'.")
.setResponseExample(getClass().getResource("create_template-example.json"))
.setSince("5.2")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_NAME)
.setRequired(true)
.setDescription("Name")
.setExampleValue("Financial Service Permissions");
WsParameters.createTemplateProjectKeyPatternParameter(action);
WsParameters.createTemplateDescriptionParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
CreateTemplateWsResponse createTemplateWsResponse = doHandle(toCreateTemplateWsRequest(request));
writeProtobuf(createTemplateWsResponse, request, response);
}
private CreateTemplateWsResponse doHandle(CreateTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
checkGlobalAdmin(userSession);
validateTemplateNameForCreation(dbSession, request.getName());
RequestValidator.validateProjectPattern(request.getProjectKeyPattern());
PermissionTemplateDto permissionTemplate = insertTemplate(dbSession, request);
return buildResponse(permissionTemplate);
}
}
private void validateTemplateNameForCreation(DbSession dbSession, String name) {
PermissionTemplateDto permissionTemplateWithSameName = dbClient.permissionTemplateDao()
.selectByName(dbSession, name);
checkRequest(permissionTemplateWithSameName == null, format(MSG_TEMPLATE_WITH_SAME_NAME, name));
}
private PermissionTemplateDto insertTemplate(DbSession dbSession, CreateTemplateRequest request) {
Date now = new Date(system.now());
PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, new PermissionTemplateDto()
.setUuid(Uuids.create())
.setName(request.getName())
.setDescription(request.getDescription())
.setKeyPattern(request.getProjectKeyPattern())
.setCreatedAt(now)
.setUpdatedAt(now));
dbSession.commit();
return template;
}
private static class CreateTemplateRequest {
private String description;
private String name;
private String projectKeyPattern;
@CheckForNull
public String getDescription() {
return description;
}
public CreateTemplateRequest setDescription(@Nullable String description) {
this.description = description;
return this;
}
public String getName() {
return name;
}
public CreateTemplateRequest setName(String name) {
this.name = requireNonNull(name);
return this;
}
@CheckForNull
public String getProjectKeyPattern() {
return projectKeyPattern;
}
public CreateTemplateRequest setProjectKeyPattern(@Nullable String projectKeyPattern) {
this.projectKeyPattern = projectKeyPattern;
return this;
}
}
}
| 6,532 | 38.355422 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/DeleteTemplateAction.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.permission.ws.template;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.template.PermissionTemplateDto;
import org.sonar.server.permission.DefaultTemplatesResolver;
import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class DeleteTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionWsSupport wsSupport;
private final DefaultTemplatesResolver defaultTemplatesResolver;
public DeleteTemplateAction(DbClient dbClient, UserSession userSession, PermissionWsSupport support,
DefaultTemplatesResolver defaultTemplatesResolver) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = support;
this.defaultTemplatesResolver = defaultTemplatesResolver;
}
private static DeleteTemplateRequest toDeleteTemplateWsRequest(Request request) {
return new DeleteTemplateRequest()
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME));
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("delete_template")
.setDescription("Delete a permission template.<br />" +
"Requires the following permission: 'Administer System'.")
.setSince("5.2")
.setPost(true)
.setHandler(this);
WsParameters.createTemplateParameters(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
doHandle(toDeleteTemplateWsRequest(request));
response.noContent();
}
private void doHandle(DeleteTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
checkTemplateUuidIsNotDefault(dbSession, template);
dbClient.permissionTemplateDao().deleteByUuid(dbSession, template.getUuid(), template.getName());
dbSession.commit();
}
}
private void checkTemplateUuidIsNotDefault(DbSession dbSession, PermissionTemplateDto template) {
ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession);
checkRequest(!resolvedDefaultTemplates.getProject().equals(template.getUuid()),
"It is not possible to delete the default permission template for projects");
resolvedDefaultTemplates.getApplication()
.ifPresent(defaultApplicationTemplate -> checkRequest(
!defaultApplicationTemplate.equals(template.getUuid()),
"It is not possible to delete the default permission template for applications"));
resolvedDefaultTemplates.getPortfolio()
.ifPresent(defaultPortfolioTemplate -> checkRequest(
!defaultPortfolioTemplate.equals(template.getUuid()),
"It is not possible to delete the default permission template for portfolios"));
}
private static class DeleteTemplateRequest {
private String templateId;
private String templateName;
@CheckForNull
public String getTemplateId() {
return templateId;
}
public DeleteTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public DeleteTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
}
| 5,400 | 39.916667 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/PermissionTemplateDtoToPermissionTemplateResponse.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.permission.ws.template;
import java.util.function.Function;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonarqube.ws.Permissions.PermissionTemplate;
import static java.util.Optional.ofNullable;
public class PermissionTemplateDtoToPermissionTemplateResponse {
private PermissionTemplateDtoToPermissionTemplateResponse() {
// prevent instantiation
}
public static PermissionTemplate toPermissionTemplateResponse(PermissionTemplateDto dto) {
return Singleton.INSTANCE.apply(dto);
}
private enum Singleton implements Function<PermissionTemplateDto, PermissionTemplate> {
INSTANCE;
@Override
public PermissionTemplate apply(PermissionTemplateDto permissionTemplate) {
PermissionTemplate.Builder permissionTemplateBuilder = PermissionTemplate.newBuilder()
.setId(permissionTemplate.getUuid())
.setName(permissionTemplate.getName())
.setCreatedAt(DateUtils.formatDateTime(permissionTemplate.getCreatedAt()))
.setUpdatedAt(DateUtils.formatDateTime(permissionTemplate.getUpdatedAt()));
ofNullable(permissionTemplate.getDescription()).ifPresent(permissionTemplateBuilder::setDescription);
ofNullable(permissionTemplate.getKeyPattern()).ifPresent(permissionTemplateBuilder::setProjectKeyPattern);
return permissionTemplateBuilder.build();
}
}
}
| 2,268 | 41.018519 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateAction.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.permission.ws.template;
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.template.PermissionTemplateDto;
import org.sonar.server.permission.GroupUuidOrAnyone;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createGroupNameParameter;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class RemoveGroupFromTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final UserSession userSession;
private final WsParameters wsParameters;
public RemoveGroupFromTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, UserSession userSession, WsParameters wsParameters) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.userSession = userSession;
this.wsParameters = wsParameters;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction("remove_group_from_template")
.setPost(true)
.setSince("5.2")
.setDescription("Remove a group from a permission template.<br /> " +
"The group name must be provided. <br />" +
"Requires the following permission: 'Administer System'.")
.setChangelog(
new Change("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."),
new Change("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead."))
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
createGroupNameParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
String permission = request.mandatoryParam(PARAM_PERMISSION);
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, WsTemplateRef.fromRequest(request));
checkGlobalAdmin(userSession);
GroupUuidOrAnyone group = wsSupport.findGroup(dbSession, request);
dbClient.permissionTemplateDao().deleteGroupPermission(dbSession, template.getUuid(), group.getUuid(), permission,
template.getName(), request.param(PARAM_GROUP_NAME));
dbSession.commit();
}
response.noContent();
}
}
| 3,902 | 43.352273 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateAction.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.permission.ws.template;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDao;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class RemoveProjectCreatorFromTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final UserSession userSession;
private final System2 system;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
public RemoveProjectCreatorFromTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, UserSession userSession, System2 system,
WsParameters wsParameters, RequestValidator requestValidator) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.userSession = userSession;
this.system = system;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
}
private RemoveProjectCreatorFromTemplateRequest toWsRequest(Request request) {
RemoveProjectCreatorFromTemplateRequest wsRequest = RemoveProjectCreatorFromTemplateRequest.builder()
.setPermission(request.mandatoryParam(PARAM_PERMISSION))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME))
.build();
requestValidator.validateProjectPermission(wsRequest.getPermission());
return wsRequest;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("remove_project_creator_from_template")
.setDescription("Remove a project creator from a permission template.<br>" +
"Requires the following permission: 'Administer System'.")
.setSince("6.0")
.setPost(true)
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toWsRequest(request));
response.noContent();
}
private void doHandle(RemoveProjectCreatorFromTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, WsTemplateRef.newTemplateRef(request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
PermissionTemplateCharacteristicDao dao = dbClient.permissionTemplateCharacteristicDao();
dao.selectByPermissionAndTemplateId(dbSession, request.getPermission(), template.getUuid())
.ifPresent(permissionTemplateCharacteristicDto -> updateTemplateCharacteristic(dbSession, permissionTemplateCharacteristicDto,
template.getName()));
}
}
private void updateTemplateCharacteristic(DbSession dbSession, PermissionTemplateCharacteristicDto templatePermission, String templateName) {
PermissionTemplateCharacteristicDto targetTemplatePermission = templatePermission
.setUpdatedAt(system.now())
.setWithProjectCreator(false);
dbClient.permissionTemplateCharacteristicDao().update(dbSession, targetTemplatePermission, templateName);
dbSession.commit();
}
private static class RemoveProjectCreatorFromTemplateRequest {
private final String templateId;
private final String templateName;
private final String permission;
private RemoveProjectCreatorFromTemplateRequest(Builder builder) {
this.templateId = builder.templateId;
this.templateName = builder.templateName;
this.permission = requireNonNull(builder.permission);
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public String getPermission() {
return permission;
}
public static Builder builder() {
return new Builder();
}
}
public static class Builder {
private String templateId;
private String templateName;
private String permission;
private Builder() {
// enforce method constructor
}
public Builder setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
public Builder setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
public Builder setPermission(@Nullable String permission) {
this.permission = permission;
return this;
}
public RemoveProjectCreatorFromTemplateRequest build() {
return new RemoveProjectCreatorFromTemplateRequest(this);
}
}
}
| 6,635 | 37.581395 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateAction.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.permission.ws.template;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.template.PermissionTemplateDto;
import org.sonar.db.user.UserId;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.permission.ws.WsParameters.createUserLoginParameter;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN;
public class RemoveUserFromTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final UserSession userSession;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
public RemoveUserFromTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, UserSession userSession, WsParameters wsParameters, RequestValidator requestValidator) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.userSession = userSession;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
}
private static RemoveUserFromTemplateRequest toRemoveUserFromTemplateWsRequest(Request request) {
return new RemoveUserFromTemplateRequest()
.setPermission(request.mandatoryParam(PARAM_PERMISSION))
.setLogin(request.mandatoryParam(PARAM_USER_LOGIN))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME));
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction("remove_user_from_template")
.setPost(true)
.setSince("5.2")
.setDescription("Remove a user from a permission template.<br /> " +
"Requires the following permission: 'Administer System'.")
.setHandler(this);
createTemplateParameters(action);
wsParameters.createProjectPermissionParameter(action);
createUserLoginParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toRemoveUserFromTemplateWsRequest(request));
response.noContent();
}
private void doHandle(RemoveUserFromTemplateRequest request) {
String permission = request.getPermission();
String userLogin = request.getLogin();
try (DbSession dbSession = dbClient.openSession(false)) {
requestValidator.validateProjectPermission(permission);
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, WsTemplateRef.newTemplateRef(request.getTemplateId(), request.getTemplateName()));
checkGlobalAdmin(userSession);
UserId user = wsSupport.findUser(dbSession, userLogin);
dbClient.permissionTemplateDao().deleteUserPermission(dbSession, template.getUuid(), user.getUuid(), permission, template.getName(), user.getLogin());
dbSession.commit();
}
}
private static class RemoveUserFromTemplateRequest {
private String login;
private String permission;
private String templateId;
private String templateName;
public String getLogin() {
return login;
}
public RemoveUserFromTemplateRequest setLogin(String login) {
this.login = requireNonNull(login);
return this;
}
public String getPermission() {
return permission;
}
public RemoveUserFromTemplateRequest setPermission(String permission) {
this.permission = requireNonNull(permission);
return this;
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
public RemoveUserFromTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public RemoveUserFromTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
}
| 5,727 | 36.933775 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesAction.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.permission.ws.template;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import java.util.List;
import java.util.Locale;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
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.Param;
import org.sonar.core.i18n.I18n;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.CountByTemplateAndPermissionDto;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.DefaultTemplatesResolver;
import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions;
import org.sonarqube.ws.Permissions.Permission;
import org.sonarqube.ws.Permissions.PermissionTemplate;
import org.sonarqube.ws.Permissions.SearchTemplatesWsResponse;
import org.sonarqube.ws.Permissions.SearchTemplatesWsResponse.TemplateIdQualifier;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.template.SearchTemplatesData.builder;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchTemplatesAction implements PermissionsWsAction {
private static final String PROPERTY_PREFIX = "projects_role.";
private static final String DESCRIPTION_SUFFIX = ".desc";
private final DbClient dbClient;
private final UserSession userSession;
private final I18n i18n;
private final DefaultTemplatesResolver defaultTemplatesResolver;
private final PermissionService permissionService;
public SearchTemplatesAction(DbClient dbClient, UserSession userSession, I18n i18n, DefaultTemplatesResolver defaultTemplatesResolver,
PermissionService permissionService) {
this.dbClient = dbClient;
this.userSession = userSession;
this.i18n = i18n;
this.defaultTemplatesResolver = defaultTemplatesResolver;
this.permissionService = permissionService;
}
@Override
public void define(WebService.NewController context) {
context.createAction("search_templates")
.setDescription("List permission templates.<br />" +
"Requires the following permission: 'Administer System'.")
.setResponseExample(getClass().getResource("search_templates-example-without-views.json"))
.setSince("5.2")
.addSearchQuery("defau", "permission template names")
.setHandler(this);
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
SearchTemplatesRequest request = new SearchTemplatesRequest().setQuery(wsRequest.param(Param.TEXT_QUERY));
checkGlobalAdmin(userSession);
SearchTemplatesWsResponse searchTemplatesWsResponse = buildResponse(load(dbSession, request));
writeProtobuf(searchTemplatesWsResponse, wsRequest, wsResponse);
}
}
private static void buildDefaultTemplatesResponse(SearchTemplatesWsResponse.Builder response, SearchTemplatesData data) {
TemplateIdQualifier.Builder templateUuidQualifierBuilder = TemplateIdQualifier.newBuilder();
ResolvedDefaultTemplates resolvedDefaultTemplates = data.defaultTemplates();
response.addDefaultTemplates(templateUuidQualifierBuilder
.setQualifier(Qualifiers.PROJECT)
.setTemplateId(resolvedDefaultTemplates.getProject()));
resolvedDefaultTemplates.getApplication()
.ifPresent(viewDefaultTemplate -> response.addDefaultTemplates(
templateUuidQualifierBuilder
.clear()
.setQualifier(Qualifiers.APP)
.setTemplateId(viewDefaultTemplate)));
resolvedDefaultTemplates.getPortfolio()
.ifPresent(viewDefaultTemplate -> response.addDefaultTemplates(
templateUuidQualifierBuilder
.clear()
.setQualifier(Qualifiers.VIEW)
.setTemplateId(viewDefaultTemplate)));
}
private void buildTemplatesResponse(Permissions.SearchTemplatesWsResponse.Builder response, SearchTemplatesData data) {
Permission.Builder permissionResponse = Permission.newBuilder();
PermissionTemplate.Builder templateBuilder = PermissionTemplate.newBuilder();
for (PermissionTemplateDto templateDto : data.templates()) {
templateBuilder
.clear()
.setId(templateDto.getUuid())
.setName(templateDto.getName())
.setCreatedAt(formatDateTime(templateDto.getCreatedAt()))
.setUpdatedAt(formatDateTime(templateDto.getUpdatedAt()));
ofNullable(templateDto.getKeyPattern()).ifPresent(templateBuilder::setProjectKeyPattern);
ofNullable(templateDto.getDescription()).ifPresent(templateBuilder::setDescription);
for (String permission : permissionService.getAllProjectPermissions()) {
templateBuilder.addPermissions(
permissionResponse
.clear()
.setKey(permission)
.setUsersCount(data.userCount(templateDto.getUuid(), permission))
.setGroupsCount(data.groupCount(templateDto.getUuid(), permission))
.setWithProjectCreator(data.withProjectCreator(templateDto.getUuid(), permission)));
}
response.addPermissionTemplates(templateBuilder);
}
}
private Permissions.SearchTemplatesWsResponse buildResponse(SearchTemplatesData data) {
SearchTemplatesWsResponse.Builder response = SearchTemplatesWsResponse.newBuilder();
buildTemplatesResponse(response, data);
buildDefaultTemplatesResponse(response, data);
buildPermissionsResponse(response);
return response.build();
}
private void buildPermissionsResponse(SearchTemplatesWsResponse.Builder response) {
Permission.Builder permissionResponse = Permission.newBuilder();
for (String permissionKey : permissionService.getAllProjectPermissions()) {
response.addPermissions(
permissionResponse
.clear()
.setKey(permissionKey)
.setName(i18nName(permissionKey))
.setDescription(i18nDescriptionMessage(permissionKey)));
}
}
private String i18nDescriptionMessage(String permissionKey) {
return i18n.message(Locale.ENGLISH, PROPERTY_PREFIX + permissionKey + DESCRIPTION_SUFFIX, "");
}
private String i18nName(String permissionKey) {
return i18n.message(Locale.ENGLISH, PROPERTY_PREFIX + permissionKey, permissionKey);
}
private SearchTemplatesData load(DbSession dbSession, SearchTemplatesRequest request) {
SearchTemplatesData.Builder data = builder();
List<PermissionTemplateDto> templates = searchTemplates(dbSession, request);
List<String> templateUuids = templates.stream().map(PermissionTemplateDto::getUuid).toList();
ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession);
data.templates(templates)
.defaultTemplates(resolvedDefaultTemplates)
.userCountByTemplateUuidAndPermission(userCountByTemplateUuidAndPermission(dbSession, templateUuids))
.groupCountByTemplateUuidAndPermission(groupCountByTemplateUuidAndPermission(dbSession, templateUuids))
.withProjectCreatorByTemplateUuidAndPermission(withProjectCreatorsByTemplateUuidAndPermission(dbSession, templateUuids));
return data.build();
}
private List<PermissionTemplateDto> searchTemplates(DbSession dbSession, SearchTemplatesRequest request) {
return dbClient.permissionTemplateDao().selectAll(dbSession, request.getQuery());
}
private Table<String, String, Integer> userCountByTemplateUuidAndPermission(DbSession dbSession, List<String> templateUuids) {
final Table<String, String, Integer> userCountByTemplateUuidAndPermission = TreeBasedTable.create();
dbClient.permissionTemplateDao().usersCountByTemplateUuidAndPermission(dbSession, templateUuids, context -> {
CountByTemplateAndPermissionDto row = context.getResultObject();
userCountByTemplateUuidAndPermission.put(row.getTemplateUuid(), row.getPermission(), row.getCount());
});
return userCountByTemplateUuidAndPermission;
}
private Table<String, String, Integer> groupCountByTemplateUuidAndPermission(DbSession dbSession, List<String> templateUuids) {
final Table<String, String, Integer> userCountByTemplateUuidAndPermission = TreeBasedTable.create();
dbClient.permissionTemplateDao().groupsCountByTemplateUuidAndPermission(dbSession, templateUuids, context -> {
CountByTemplateAndPermissionDto row = context.getResultObject();
userCountByTemplateUuidAndPermission.put(row.getTemplateUuid(), row.getPermission(), row.getCount());
});
return userCountByTemplateUuidAndPermission;
}
private Table<String, String, Boolean> withProjectCreatorsByTemplateUuidAndPermission(DbSession dbSession, List<String> templateUuids) {
final Table<String, String, Boolean> templatePermissionsByTemplateUuidAndPermission = TreeBasedTable.create();
List<PermissionTemplateCharacteristicDto> templatePermissions = dbClient.permissionTemplateCharacteristicDao().selectByTemplateUuids(dbSession, templateUuids);
templatePermissions.stream()
.forEach(templatePermission -> templatePermissionsByTemplateUuidAndPermission.put(templatePermission.getTemplateUuid(), templatePermission.getPermission(),
templatePermission.getWithProjectCreator()));
return templatePermissionsByTemplateUuidAndPermission;
}
private static class SearchTemplatesRequest {
private String query;
@CheckForNull
public String getQuery() {
return query;
}
public SearchTemplatesRequest setQuery(@Nullable String query) {
this.query = query;
return this;
}
}
}
| 10,991 | 44.421488 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SearchTemplatesData.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.permission.ws.template;
import com.google.common.collect.Table;
import java.util.List;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.ImmutableTable.copyOf;
class SearchTemplatesData {
private final List<PermissionTemplateDto> templates;
private final ResolvedDefaultTemplates defaultTemplates;
private final Table<String, String, Integer> userCountByTemplateUuidAndPermission;
private final Table<String, String, Integer> groupCountByTemplateUuidAndPermission;
private final Table<String, String, Boolean> withProjectCreatorByTemplateUuidAndPermission;
private SearchTemplatesData(Builder builder) {
this.templates = copyOf(builder.templates);
this.defaultTemplates = builder.defaultTemplates;
this.userCountByTemplateUuidAndPermission = copyOf(builder.userCountByTemplateUuidAndPermission);
this.groupCountByTemplateUuidAndPermission = copyOf(builder.groupCountByTemplateUuidAndPermission);
this.withProjectCreatorByTemplateUuidAndPermission = copyOf(builder.withProjectCreatorByTemplateUuidAndPermission);
}
public static Builder builder() {
return new Builder();
}
public List<PermissionTemplateDto> templates() {
return templates;
}
public ResolvedDefaultTemplates defaultTemplates() {
return defaultTemplates;
}
public int userCount(String templateUuid, String permission) {
return firstNonNull(userCountByTemplateUuidAndPermission.get(templateUuid, permission), 0);
}
public int groupCount(String templateUuid, String permission) {
return firstNonNull(groupCountByTemplateUuidAndPermission.get(templateUuid, permission), 0);
}
public boolean withProjectCreator(String templateUuid, String permission) {
return firstNonNull(withProjectCreatorByTemplateUuidAndPermission.get(templateUuid, permission), false);
}
public static class Builder {
private List<PermissionTemplateDto> templates;
private ResolvedDefaultTemplates defaultTemplates;
private Table<String, String, Integer> userCountByTemplateUuidAndPermission;
private Table<String, String, Integer> groupCountByTemplateUuidAndPermission;
private Table<String, String, Boolean> withProjectCreatorByTemplateUuidAndPermission;
private Builder() {
// prevents instantiation outside main class
}
public SearchTemplatesData build() {
checkState(templates != null);
checkState(defaultTemplates != null);
checkState(userCountByTemplateUuidAndPermission != null);
checkState(groupCountByTemplateUuidAndPermission != null);
checkState(withProjectCreatorByTemplateUuidAndPermission != null);
return new SearchTemplatesData(this);
}
public Builder templates(List<PermissionTemplateDto> templates) {
this.templates = templates;
return this;
}
public Builder defaultTemplates(ResolvedDefaultTemplates defaultTemplates) {
this.defaultTemplates = defaultTemplates;
return this;
}
public Builder userCountByTemplateUuidAndPermission(Table<String, String, Integer> userCountByTemplateUuidAndPermission) {
this.userCountByTemplateUuidAndPermission = userCountByTemplateUuidAndPermission;
return this;
}
public Builder groupCountByTemplateUuidAndPermission(Table<String, String, Integer> groupCountByTemplateUuidAndPermission) {
this.groupCountByTemplateUuidAndPermission = groupCountByTemplateUuidAndPermission;
return this;
}
public Builder withProjectCreatorByTemplateUuidAndPermission(Table<String, String, Boolean> withProjectCreatorByTemplateUuidAndPermission) {
this.withProjectCreatorByTemplateUuidAndPermission = withProjectCreatorByTemplateUuidAndPermission;
return this;
}
}
}
| 4,911 | 40.627119 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/SetDefaultTemplateAction.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.permission.ws.template;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
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.i18n.I18n;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.property.InternalProperties;
import org.sonar.server.user.UserSession;
import static java.lang.String.format;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
import static org.sonar.server.ws.WsParameterBuilder.createDefaultTemplateQualifierParameter;
import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class SetDefaultTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionWsSupport wsSupport;
private final ResourceTypes resourceTypes;
private final UserSession userSession;
private final I18n i18n;
public SetDefaultTemplateAction(DbClient dbClient, PermissionWsSupport wsSupport, ResourceTypes resourceTypes,
UserSession userSession, I18n i18n) {
this.dbClient = dbClient;
this.wsSupport = wsSupport;
this.resourceTypes = resourceTypes;
this.userSession = userSession;
this.i18n = i18n;
}
private static SetDefaultTemplateRequest toSetDefaultTemplateWsRequest(Request request) {
return new SetDefaultTemplateRequest()
.setQualifier(request.mandatoryParam(PARAM_QUALIFIER))
.setTemplateId(request.param(PARAM_TEMPLATE_ID))
.setTemplateName(request.param(PARAM_TEMPLATE_NAME));
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("set_default_template")
.setDescription("Set a permission template as default.<br />" +
"Requires the following permission: 'Administer System'.")
.setPost(true)
.setSince("5.2")
.setHandler(this);
WsParameters.createTemplateParameters(action);
createDefaultTemplateQualifierParameter(action, newQualifierParameterContext(i18n, resourceTypes))
.setDefaultValue(Qualifiers.PROJECT);
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(toSetDefaultTemplateWsRequest(request));
response.noContent();
}
private void doHandle(SetDefaultTemplateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
String qualifier = request.getQualifier();
PermissionTemplateDto template = findTemplate(dbSession, request);
checkGlobalAdmin(userSession);
RequestValidator.validateQualifier(qualifier, resourceTypes);
setDefaultTemplateUuid(dbSession, template, qualifier);
dbSession.commit();
}
}
private PermissionTemplateDto findTemplate(DbSession dbSession, SetDefaultTemplateRequest request) {
return wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
}
private void setDefaultTemplateUuid(DbSession dbSession, PermissionTemplateDto permissionTemplateDto, String qualifier) {
switch (qualifier) {
case Qualifiers.PROJECT:
dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE, permissionTemplateDto.getUuid());
break;
case Qualifiers.VIEW:
dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE, permissionTemplateDto.getUuid());
break;
case Qualifiers.APP:
dbClient.internalPropertiesDao().save(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE, permissionTemplateDto.getUuid());
break;
default:
throw new IllegalStateException(format("Unsupported qualifier : %s", qualifier));
}
}
private static class SetDefaultTemplateRequest {
private String qualifier;
private String templateId;
private String templateName;
public String getQualifier() {
return qualifier;
}
public SetDefaultTemplateRequest setQualifier(String qualifier) {
this.qualifier = qualifier;
return this;
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
public SetDefaultTemplateRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public SetDefaultTemplateRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
}
| 6,278 | 38.740506 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/TemplateGroupsAction.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.permission.ws.template;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.TreeMultimap;
import java.util.List;
import org.sonar.api.security.DefaultGroups;
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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateGroupDto;
import org.sonar.db.user.GroupDto;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions;
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.TEXT_QUERY;
import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class TemplateGroupsAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionWsSupport wsSupport;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
public TemplateGroupsAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, WsParameters wsParameters, RequestValidator requestValidator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("template_groups")
.setSince("5.2")
.setInternal(true)
.setDescription("Lists the groups with their permission as individual groups rather than through user affiliation on the chosen template.<br />" +
"This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" +
"Requires the following permission: 'Administer System'.")
.addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
.setResponseExample(getClass().getResource("template_groups-example.json"))
.setHandler(this);
action.createParam(TEXT_QUERY)
.setMinimumLength(SEARCH_QUERY_MIN_LENGTH)
.setDescription("Limit search to group names that contain the supplied string. <br/>" +
"When this parameter is not set, only group having at least one permission are returned.")
.setExampleValue("eri");
wsParameters.createProjectPermissionParameter(action, false);
createTemplateParameters(action);
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
WsTemplateRef templateRef = WsTemplateRef.fromRequest(wsRequest);
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, templateRef);
checkGlobalAdmin(userSession);
PermissionQuery query = buildPermissionQuery(wsRequest);
int total = dbClient.permissionTemplateDao().countGroupNamesByQueryAndTemplate(dbSession, query, template.getUuid());
Paging paging = Paging.forPageIndex(wsRequest.mandatoryParamAsInt(PAGE)).withPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE)).andTotal(total);
List<GroupDto> groups = findGroups(dbSession, query, template);
List<PermissionTemplateGroupDto> groupPermissions = findGroupPermissions(dbSession, groups, template);
Permissions.WsGroupsResponse groupsResponse = buildResponse(groups, groupPermissions, paging);
writeProtobuf(groupsResponse, wsRequest, wsResponse);
}
}
private PermissionQuery buildPermissionQuery(Request request) {
String textQuery = request.param(TEXT_QUERY);
String permission = request.param(PARAM_PERMISSION);
PermissionQuery.Builder permissionQuery = PermissionQuery.builder()
.setPermission(permission != null ? requestValidator.validateProjectPermission(permission) : null)
.setPageIndex(request.mandatoryParamAsInt(PAGE))
.setPageSize(request.mandatoryParamAsInt(PAGE_SIZE))
.setSearchQuery(textQuery);
return permissionQuery.build();
}
private static Permissions.WsGroupsResponse buildResponse(List<GroupDto> groups, List<PermissionTemplateGroupDto> groupPermissions, Paging paging) {
Multimap<String, String> permissionsByGroupUuid = TreeMultimap.create();
groupPermissions.forEach(groupPermission -> permissionsByGroupUuid.put(groupPermission.getGroupUuid(), groupPermission.getPermission()));
Permissions.WsGroupsResponse.Builder response = Permissions.WsGroupsResponse.newBuilder();
groups.forEach(group -> {
Permissions.Group.Builder wsGroup = response.addGroupsBuilder()
.setName(group.getName());
if (group.getUuid() != null) {
wsGroup.setId(String.valueOf(group.getUuid()));
}
ofNullable(group.getDescription()).ifPresent(wsGroup::setDescription);
wsGroup.addAllPermissions(permissionsByGroupUuid.get(group.getUuid()));
});
response.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total());
return response.build();
}
private List<GroupDto> findGroups(DbSession dbSession, PermissionQuery dbQuery, PermissionTemplateDto template) {
List<String> orderedNames = dbClient.permissionTemplateDao().selectGroupNamesByQueryAndTemplate(dbSession, dbQuery, template.getUuid());
List<GroupDto> groups = dbClient.groupDao().selectByNames(dbSession, orderedNames);
if (orderedNames.contains(DefaultGroups.ANYONE)) {
groups.add(0, new GroupDto().setUuid(DefaultGroups.ANYONE).setName(DefaultGroups.ANYONE));
}
return Ordering.explicit(orderedNames).onResultOf(GroupDto::getName).immutableSortedCopy(groups);
}
private List<PermissionTemplateGroupDto> findGroupPermissions(DbSession dbSession, List<GroupDto> groups, PermissionTemplateDto template) {
List<String> names = groups.stream().map(GroupDto::getName).toList();
return dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateIdAndGroupNames(dbSession, template.getUuid(), names);
}
}
| 7,983 | 49.853503 | 168 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/TemplateUsersAction.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.permission.ws.template;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.TreeMultimap;
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.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateUserDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolver;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions;
import org.sonarqube.ws.Permissions.UsersWsResponse;
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.TEXT_QUERY;
import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class TemplateUsersAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final PermissionWsSupport wsSupport;
private final AvatarResolver avatarResolver;
private final WsParameters wsParameters;
private final RequestValidator requestValidator;
public TemplateUsersAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, AvatarResolver avatarResolver,
WsParameters wsParameters, RequestValidator requestValidator) {
this.dbClient = dbClient;
this.userSession = userSession;
this.wsSupport = wsSupport;
this.avatarResolver = avatarResolver;
this.wsParameters = wsParameters;
this.requestValidator = requestValidator;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction("template_users")
.setSince("5.2")
.setDescription("Lists the users with their permission as individual users rather than through group affiliation on the chosen template. <br />" +
"This service defaults to all users, but can be limited to users with a specific permission by providing the desired permission.<br>" +
"Requires the following permission: 'Administer System'.")
.addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
.setInternal(true)
.setResponseExample(getClass().getResource("template_users-example.json"))
.setHandler(this);
action.createParam(Param.TEXT_QUERY)
.setMinimumLength(SEARCH_QUERY_MIN_LENGTH)
.setDescription("Limit search to user names that contain the supplied string. <br/>" +
"When this parameter is not set, only users having at least one permission are returned.")
.setExampleValue("eri");
wsParameters.createProjectPermissionParameter(action).setRequired(false);
createTemplateParameters(action);
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
try (DbSession dbSession = dbClient.openSession(false)) {
WsTemplateRef templateRef = WsTemplateRef.fromRequest(wsRequest);
PermissionTemplateDto template = wsSupport.findTemplate(dbSession, templateRef);
checkGlobalAdmin(userSession);
PermissionQuery query = buildQuery(wsRequest);
int total = dbClient.permissionTemplateDao().countUserLoginsByQueryAndTemplate(dbSession, query, template.getUuid());
Paging paging = Paging.forPageIndex(wsRequest.mandatoryParamAsInt(PAGE)).withPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE)).andTotal(total);
List<UserDto> users = findUsers(dbSession, query, template);
List<PermissionTemplateUserDto> permissionTemplateUsers = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateIdAndUserLogins(dbSession, template.getUuid(),
users.stream().map(UserDto::getLogin).toList());
Permissions.UsersWsResponse templateUsersResponse = buildResponse(users, permissionTemplateUsers, paging);
writeProtobuf(templateUsersResponse, wsRequest, wsResponse);
}
}
private PermissionQuery buildQuery(Request wsRequest) {
String textQuery = wsRequest.param(TEXT_QUERY);
String permission = wsRequest.param(PARAM_PERMISSION);
PermissionQuery.Builder query = PermissionQuery.builder()
.setPermission(permission != null ? requestValidator.validateProjectPermission(permission) : null)
.setPageIndex(wsRequest.mandatoryParamAsInt(PAGE))
.setPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE))
.setSearchQuery(textQuery);
return query.build();
}
private Permissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
Multimap<String, String> permissionsByUserUuid = TreeMultimap.create();
permissionTemplateUsers.forEach(userPermission -> permissionsByUserUuid.put(userPermission.getUserUuid(), userPermission.getPermission()));
UsersWsResponse.Builder responseBuilder = UsersWsResponse.newBuilder();
users.forEach(user -> {
Permissions.User.Builder userResponse = responseBuilder.addUsersBuilder()
.setLogin(user.getLogin())
.addAllPermissions(permissionsByUserUuid.get(user.getUuid()));
ofNullable(user.getEmail()).ifPresent(userResponse::setEmail);
ofNullable(user.getName()).ifPresent(userResponse::setName);
ofNullable(emptyToNull(user.getEmail())).ifPresent(u -> userResponse.setAvatar(avatarResolver.create(user)));
});
responseBuilder.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total())
.build();
return responseBuilder.build();
}
private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
List<String> orderedLogins = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, query, template.getUuid());
return Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin).immutableSortedCopy(dbClient.userDao().selectByLogins(dbSession, orderedLogins));
}
}
| 7,926 | 49.814103 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/UpdateTemplateAction.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.permission.ws.template;
import java.util.Date;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.permission.RequestValidator;
import org.sonar.server.permission.ws.PermissionWsSupport;
import org.sonar.server.permission.ws.PermissionsWsAction;
import org.sonar.server.permission.ws.WsParameters;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Permissions.PermissionTemplate;
import org.sonarqube.ws.Permissions.UpdateTemplateWsResponse;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
import static org.sonar.server.permission.RequestValidator.MSG_TEMPLATE_WITH_SAME_NAME;
import static org.sonar.server.permission.ws.template.PermissionTemplateDtoToPermissionTemplateResponse.toPermissionTemplateResponse;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN;
public class UpdateTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final System2 system;
private final PermissionWsSupport wsSupport;
public UpdateTemplateAction(DbClient dbClient, UserSession userSession, System2 system, PermissionWsSupport wsSupport) {
this.dbClient = dbClient;
this.userSession = userSession;
this.system = system;
this.wsSupport = wsSupport;
}
private static UpdateTemplateRequest toUpdateTemplateWsRequest(Request request) {
return new UpdateTemplateRequest()
.setId(request.mandatoryParam(PARAM_ID))
.setName(request.param(PARAM_NAME))
.setDescription(request.param(PARAM_DESCRIPTION))
.setProjectKeyPattern(request.param(PARAM_PROJECT_KEY_PATTERN));
}
private static UpdateTemplateWsResponse buildResponse(PermissionTemplateDto permissionTemplate) {
PermissionTemplate permissionTemplateBuilder = toPermissionTemplateResponse(permissionTemplate);
return UpdateTemplateWsResponse.newBuilder().setPermissionTemplate(permissionTemplateBuilder).build();
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("update_template")
.setDescription("Update a permission template.<br />" +
"Requires the following permission: 'Administer System'.")
.setResponseExample(getClass().getResource("update_template-example.json"))
.setSince("5.2")
.setPost(true)
.setHandler(this);
WsParameters.createIdParameter(action);
action.createParam(PARAM_NAME)
.setDescription("Name")
.setExampleValue("Financial Service Permissions");
WsParameters.createTemplateProjectKeyPatternParameter(action);
WsParameters.createTemplateDescriptionParameter(action);
}
@Override
public void handle(Request request, Response response) throws Exception {
UpdateTemplateWsResponse updateTemplateWsResponse = doHandle(toUpdateTemplateWsRequest(request));
writeProtobuf(updateTemplateWsResponse, request, response);
}
private UpdateTemplateWsResponse doHandle(UpdateTemplateRequest request) {
String uuid = request.getId();
String nameParam = request.getName();
String descriptionParam = request.getDescription();
String projectPatternParam = request.getProjectKeyPattern();
try (DbSession dbSession = dbClient.openSession(false)) {
PermissionTemplateDto templateToUpdate = getAndBuildTemplateToUpdate(dbSession, uuid, nameParam, descriptionParam, projectPatternParam);
checkGlobalAdmin(userSession);
validateTemplate(dbSession, templateToUpdate);
PermissionTemplateDto updatedTemplate = updateTemplate(dbSession, templateToUpdate);
dbSession.commit();
return buildResponse(updatedTemplate);
}
}
private void validateTemplate(DbSession dbSession, PermissionTemplateDto templateToUpdate) {
validateTemplateNameForUpdate(dbSession, templateToUpdate.getName(), templateToUpdate.getUuid());
RequestValidator.validateProjectPattern(templateToUpdate.getKeyPattern());
}
private PermissionTemplateDto getAndBuildTemplateToUpdate(DbSession dbSession, String uuid, @Nullable String newName, @Nullable String newDescription,
@Nullable String newProjectKeyPattern) {
PermissionTemplateDto templateToUpdate = wsSupport.findTemplate(dbSession, WsTemplateRef.newTemplateRef(uuid, null));
templateToUpdate.setName(coalesce(newName, templateToUpdate.getName()));
templateToUpdate.setDescription(coalesce(newDescription, templateToUpdate.getDescription()));
templateToUpdate.setKeyPattern(coalesce(newProjectKeyPattern, templateToUpdate.getKeyPattern()));
templateToUpdate.setUpdatedAt(new Date(system.now()));
return templateToUpdate;
}
@CheckForNull
private static String coalesce(@Nullable String s1, @Nullable String s2) {
return s1 != null ? s1 : s2;
}
private PermissionTemplateDto updateTemplate(DbSession dbSession, PermissionTemplateDto templateToUpdate) {
return dbClient.permissionTemplateDao().update(dbSession, templateToUpdate);
}
private void validateTemplateNameForUpdate(DbSession dbSession, String name, String uuid) {
BadRequestException.checkRequest(!isBlank(name), "The template name must not be blank");
PermissionTemplateDto permissionTemplateWithSameName = dbClient.permissionTemplateDao().selectByName(dbSession, name);
checkRequest(permissionTemplateWithSameName == null || Objects.equals(permissionTemplateWithSameName.getUuid(), uuid),
format(MSG_TEMPLATE_WITH_SAME_NAME, name));
}
private static class UpdateTemplateRequest {
private String id;
private String description;
private String name;
private String projectKeyPattern;
public String getId() {
return id;
}
public UpdateTemplateRequest setId(String id) {
this.id = requireNonNull(id);
return this;
}
@CheckForNull
public String getDescription() {
return description;
}
public UpdateTemplateRequest setDescription(@Nullable String description) {
this.description = description;
return this;
}
@CheckForNull
public String getName() {
return name;
}
public UpdateTemplateRequest setName(@Nullable String name) {
this.name = name;
return this;
}
@CheckForNull
public String getProjectKeyPattern() {
return projectKeyPattern;
}
public UpdateTemplateRequest setProjectKeyPattern(@Nullable String projectKeyPattern) {
this.projectKeyPattern = projectKeyPattern;
return this;
}
}
}
| 8,364 | 40.004902 | 152 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/ws/template/WsTemplateRef.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.permission.ws.template;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Request;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
/**
* Reference to a template as defined by WS request. Guaranties one of template id or
* template name is provided, not both.
*/
public class WsTemplateRef {
private final String uuid;
private final String name;
private WsTemplateRef(@Nullable String uuid, @Nullable String name) {
checkRequest(uuid != null ^ name != null, "Template name or template id must be provided, not both.");
this.uuid = uuid;
this.name = name;
}
public static WsTemplateRef fromRequest(Request wsRequest) {
String uuid = wsRequest.param(PARAM_TEMPLATE_ID);
String name = wsRequest.param(PARAM_TEMPLATE_NAME);
return new WsTemplateRef(uuid, name);
}
public static WsTemplateRef newTemplateRef(@Nullable String uuid, @Nullable String name) {
return new WsTemplateRef(uuid, name);
}
@CheckForNull
public String uuid() {
return this.uuid;
}
@CheckForNull
public String name() {
return this.name;
}
}
| 2,218 | 32.621212 | 106 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.