import org.sonar.server.l18n.ServerI18n;
import org.sonar.server.log.ServerLogging;
import org.sonar.server.measure.index.ProjectMeasuresIndexer;
-import org.sonar.server.metric.CoreCustomMetrics;
import org.sonar.server.metric.MetricFinder;
import org.sonar.server.metric.UnanalyzedLanguageMetrics;
import org.sonar.server.notification.DefaultNotificationManager;
Languages.class, // used by CommonRuleDefinitionsImpl
// measure
- CoreCustomMetrics.class,
MetricFinder.class,
UnanalyzedLanguageMetrics.class,
<include refid="metricColumns"/>
FROM metrics m
<where>
- AND m.enabled=${_true}
+ m.enabled=${_true}
<if test="isCustom!=null">
<if test="isCustom.equals(true)">
AND m.user_managed=${_true}
SELECT COUNT(1)
FROM metrics m
<where>
- AND m.enabled=${_true}
+ m.enabled=${_true}
<if test="isCustom!=null">
<if test="isCustom.equals(true)">
AND m.user_managed=${_true}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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;
-
-import com.google.common.collect.ImmutableList;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.Metrics;
-
-import java.util.List;
-
-public final class CoreCustomMetrics implements Metrics {
- private static final String DOMAIN = "Management";
-
- @Override
- public List<Metric> getMetrics() {
- return ImmutableList.of(
- new Metric.Builder("burned_budget", "Burned budget", Metric.ValueType.FLOAT)
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN)
- .setUserManaged(true)
- .create(),
- new Metric.Builder("business_value", "Business value", Metric.ValueType.FLOAT)
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN)
- .setUserManaged(true)
- .create(),
- new Metric.Builder("team_size", "Team size", Metric.ValueType.INT)
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN)
- .setUserManaged(true)
- .create());
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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;
-
-import org.junit.Test;
-import org.sonar.api.measures.Metric;
-
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class CoreCustomMetricsTest {
-
- @Test
- public void checkDefinitions() {
- CoreCustomMetrics coreCustomMetrics = new CoreCustomMetrics();
- List<Metric> metrics = coreCustomMetrics.getMetrics();
- assertThat(metrics.size()).isGreaterThan(2);
- for (Metric metric : metrics) {
- assertThat(metric.getUserManaged()).isTrue();
- assertThat(metric.getDomain()).isEqualTo("Management");
- }
- }
-}
private static final int TIMEOUT = 30;
private static final String CSRF_STATE = "STATE";
- private static final String JAVA_WS_URL = "/api/metrics/create";
+ private static final String JAVA_WS_URL = "/api/projects/create";
private static final String LOGIN = "foo login";
private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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 javax.annotation.Nullable;
-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;
-import org.sonar.core.util.UuidFactory;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.server.user.UserSession;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.db.metric.MetricValidator.MAX_DESCRIPTION_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_DOMAIN_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_KEY_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_NAME_LENGTH;
-import static org.sonar.server.exceptions.BadRequestException.checkRequest;
-import static org.sonar.server.metric.ws.MetricKeyValidator.checkMetricKeyFormat;
-
-public class CreateAction implements MetricsWsAction {
- private static final String ACTION = "create";
- public static final String PARAM_NAME = "name";
- public static final String PARAM_KEY = "key";
- public static final String PARAM_TYPE = "type";
- public static final String PARAM_DESCRIPTION = "description";
- public static final String PARAM_DOMAIN = "domain";
-
- private static final String FIELD_ID = "id";
- private static final String FIELD_NAME = PARAM_NAME;
- private static final String FIELD_KEY = PARAM_KEY;
- private static final String FIELD_TYPE = PARAM_TYPE;
- private static final String FIELD_DESCRIPTION = PARAM_DESCRIPTION;
- private static final String FIELD_DOMAIN = PARAM_DOMAIN;
-
- private final DbClient dbClient;
- private final UserSession userSession;
- private final UuidFactory uuidFactory;
-
- public CreateAction(DbClient dbClient, UserSession userSession, UuidFactory uuidFactory) {
- this.dbClient = dbClient;
- this.userSession = userSession;
- this.uuidFactory = uuidFactory;
- }
-
- @Override
- public void define(WebService.NewController context) {
- WebService.NewAction action = context.createAction(ACTION)
- .setPost(true)
- .setDescription("Create custom metric.<br/>" +
- "Requires 'Administer System' permission.")
- .setDeprecatedSince("7.7")
- .setSince("5.2")
- .setHandler(this);
-
- action.createParam(PARAM_KEY)
- .setRequired(true)
- .setMaximumLength(MAX_KEY_LENGTH)
- .setDescription("Key")
- .setExampleValue("team_size");
-
- action.createParam(PARAM_NAME)
- .setRequired(true)
- .setMaximumLength(MAX_NAME_LENGTH)
- .setDescription("Name")
- .setExampleValue("Team Size");
-
- action.createParam(PARAM_TYPE)
- .setRequired(true)
- .setDescription("Metric type key")
- .setPossibleValues(Metric.ValueType.names())
- .setExampleValue(Metric.ValueType.INT.name());
-
- action.createParam(PARAM_DESCRIPTION)
- .setDescription("Description")
- .setMaximumLength(MAX_DESCRIPTION_LENGTH)
- .setExampleValue("Size of the team");
-
- action.createParam(PARAM_DOMAIN)
- .setMaximumLength(MAX_DOMAIN_LENGTH)
- .setDescription("Domain")
- .setExampleValue("Tests");
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsSystemAdministrator();
- String key = request.mandatoryParam(PARAM_KEY);
-
- try (DbSession dbSession = dbClient.openSession(false)) {
- MetricDto metricTemplate = newMetricTemplate(request);
- MetricDto metricInDb = dbClient.metricDao().selectByKey(dbSession, key);
- checkMetricInDbAndTemplate(dbSession, metricInDb, metricTemplate);
-
- if (metricIsNotInDb(metricInDb)) {
- metricInDb = insertNewMetric(dbSession, metricTemplate);
- } else {
- updateMetric(dbSession, metricInDb, metricTemplate);
- }
-
- JsonWriter json = response.newJsonWriter();
- writeMetric(json, metricInDb);
- json.close();
- }
- }
-
- private static MetricDto newMetricTemplate(Request request) {
- String key = checkMetricKeyFormat(request.mandatoryParam(PARAM_KEY));
- String name = request.mandatoryParam(PARAM_NAME);
- String type = Metric.ValueType.valueOf(request.mandatoryParam(PARAM_TYPE)).name();
- String domain = request.param(PARAM_DOMAIN);
- String description = request.param(PARAM_DESCRIPTION);
-
- MetricDto metricTemplate = new MetricDto()
- .setKey(key)
- .setShortName(name)
- .setValueType(type);
- if (domain != null) {
- metricTemplate.setDomain(domain);
- }
- if (description != null) {
- metricTemplate.setDescription(description);
- }
- return metricTemplate;
- }
-
- private void updateMetric(DbSession dbSession, MetricDto metricInDb, MetricDto metricTemplate) {
- metricInDb
- .setShortName(metricTemplate.getShortName())
- .setValueType(metricTemplate.getValueType())
- .setDomain(metricTemplate.getDomain())
- .setDescription(metricTemplate.getDescription())
- .setEnabled(true);
- dbClient.metricDao().update(dbSession, metricInDb);
- dbSession.commit();
- }
-
- private MetricDto insertNewMetric(DbSession dbSession, MetricDto metricTemplate) {
- MetricDto metric = new MetricDto()
- .setUuid(uuidFactory.create())
- .setKey(metricTemplate.getKey())
- .setShortName(metricTemplate.getShortName())
- .setValueType(metricTemplate.getValueType())
- .setDomain(metricTemplate.getDomain())
- .setDescription(metricTemplate.getDescription())
- .setEnabled(true)
- .setUserManaged(true)
- .setDirection(0)
- .setQualitative(false)
- .setHidden(false)
- .setOptimizedBestValue(false)
- .setDeleteHistoricalData(false);
-
- dbClient.metricDao().insert(dbSession, metric);
- dbSession.commit();
- return metric;
- }
-
- private void checkMetricInDbAndTemplate(DbSession dbSession, @Nullable MetricDto metricInDb, MetricDto template) {
- checkArgument(!areOneOfTheMandatoryArgumentsEmpty(template), "The mandatory arguments '%s','%s' and '%s' must not be empty", PARAM_KEY, PARAM_NAME, PARAM_TYPE);
- if (metricIsNotInDb(metricInDb)) {
- return;
- }
- checkRequest(!isMetricEnabled(metricInDb), "An active metric already exist with key: " + metricInDb.getKey());
- checkRequest(!isMetricNonCustom(metricInDb), "An non custom metric already exist with key: %s", metricInDb.getKey());
- }
-
- private static boolean isMetricNonCustom(MetricDto metricInDb) {
- return !metricInDb.isUserManaged();
- }
-
- private static boolean isMetricEnabled(MetricDto metricInDb) {
- return metricInDb.isEnabled();
- }
-
- private static boolean metricIsNotInDb(@Nullable MetricDto metricInDb) {
- return metricInDb == null;
- }
-
- private static boolean areOneOfTheMandatoryArgumentsEmpty(MetricDto template) {
- return template.getValueType().isEmpty() || template.getShortName().isEmpty() || template.getKey().isEmpty();
- }
-
- private static void writeMetric(JsonWriter json, MetricDto metric) {
- json.beginObject();
- json.prop(FIELD_ID, metric.getUuid());
- json.prop(FIELD_KEY, metric.getKey());
- json.prop(FIELD_NAME, metric.getShortName());
- json.prop(FIELD_TYPE, metric.getValueType());
- json.prop(FIELD_DOMAIN, metric.getDomain());
- json.prop(FIELD_DESCRIPTION, metric.getDescription());
- json.endObject();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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 com.google.common.collect.Lists;
-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.metric.MetricDto;
-import org.sonar.server.user.UserSession;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.lang.String.join;
-import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
-import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
-import static org.sonar.core.util.Uuids.UUID_EXAMPLE_03;
-
-public class DeleteAction implements MetricsWsAction {
- private static final String PARAM_IDS = "ids";
- private static final String PARAM_KEYS = "keys";
-
- private final DbClient dbClient;
- private final UserSession userSession;
-
- public DeleteAction(DbClient dbClient, UserSession userSession) {
- this.dbClient = dbClient;
- this.userSession = userSession;
- }
-
- @Override
- public void define(WebService.NewController context) {
- WebService.NewAction action = context.createAction("delete")
- .setDescription("Delete metrics and associated measures. Delete only custom metrics.<br/>" +
- "Ids or keys must be provided.<br/>" +
- "Requires 'Administer System' permission.")
- .setHandler(this)
- .setSince("5.2")
- .setDeprecatedSince("7.7")
- .setPost(true)
- .setChangelog(
- new Change("8.4", "Parameter 'ids' format changes from integer to string."));
-
- action.createParam(PARAM_IDS)
- .setDescription("Metrics uuids to delete.")
- .setExampleValue(join(", ", UUID_EXAMPLE_01, UUID_EXAMPLE_02, UUID_EXAMPLE_03));
-
- action.createParam(PARAM_KEYS)
- .setDescription("Metrics keys to delete")
- .setExampleValue("team_size, business_value");
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsSystemAdministrator();
-
- try (DbSession dbSession = dbClient.openSession(false)) {
- List<String> uuids = loadUuids(dbSession, request);
- dbClient.metricDao().disableCustomByUuids(dbSession, uuids);
- dbClient.gateConditionDao().deleteConditionsWithInvalidMetrics(dbSession);
- dbSession.commit();
- }
-
- response.noContent();
- }
-
- private List<String> loadUuids(DbSession dbSession, Request request) {
- List<String> uuids = request.paramAsStrings(PARAM_IDS);
- List<String> keys = request.paramAsStrings(PARAM_KEYS);
- checkArgument(uuids != null || keys != null, "Uuids or keys must be provided.");
- if (uuids == null) {
- uuids = Lists.transform(dbClient.metricDao().selectByKeys(dbSession, keys), MetricDto::getUuid);
- }
-
- return uuids;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-
-public class DomainsAction implements MetricsWsAction {
-
- private final DbClient dbClient;
-
- public DomainsAction(DbClient dbClient) {
- this.dbClient = dbClient;
- }
-
- @Override
- public void define(WebService.NewController context) {
- context.createAction("domains")
- .setDescription("List all custom metric domains.")
- .setSince("5.2")
- .setDeprecatedSince("7.7")
- .setResponseExample(getClass().getResource("example-domains.json"))
- .setHandler(this);
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- try (DbSession dbSession = dbClient.openSession(false)) {
- List<String> domains = dbClient.metricDao().selectEnabledDomains(dbSession);
- JsonWriter json = response.newJsonWriter();
- json.beginObject();
- writeDomains(json, domains);
- json.endObject();
- json.close();
- }
- }
-
- private static void writeDomains(JsonWriter json, List<String> domains) {
- json.name("domains");
- json.beginArray();
- json.values(domains);
- json.endArray();
- }
-}
*/
package org.sonar.server.metric.ws;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
import java.util.List;
-import java.util.Set;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.metric.MetricDto;
-import static org.sonar.server.ws.JsonWriterUtils.writeIfNeeded;
-
public class MetricJsonWriter {
public static final String FIELD_ID = "id";
public static final String FIELD_KEY = "key";
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_CUSTOM = "custom";
public static final String FIELD_DECIMAL_SCALE = "decimalScale";
- public static final Set<String> OPTIONAL_FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_DESCRIPTION, FIELD_DOMAIN,
- FIELD_DIRECTION, FIELD_QUALITATIVE, FIELD_HIDDEN, FIELD_CUSTOM, FIELD_DECIMAL_SCALE);
- public static final Set<String> MANDATORY_FIELDS = ImmutableSet.of(FIELD_ID, FIELD_KEY, FIELD_NAME, FIELD_DOMAIN, FIELD_TYPE);
- public static final Set<String> ALL_FIELDS = ImmutableSet.copyOf(Sets.union(MANDATORY_FIELDS, OPTIONAL_FIELDS));
private MetricJsonWriter() {
// static stuff only for the time being
}
- public static void write(JsonWriter json, List<MetricDto> metrics, Set<String> fieldsToReturn) {
+ public static void write(JsonWriter json, List<MetricDto> metrics) {
json.name("metrics");
json.beginArray();
for (MetricDto metric : metrics) {
- write(json, metric, fieldsToReturn);
+ write(json, metric);
}
json.endArray();
}
- public static void write(JsonWriter json, MetricDto metric, Set<String> fieldsToReturn) {
+ 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());
- writeIfNeeded(json, metric.getShortName(), FIELD_NAME, fieldsToReturn);
- writeIfNeeded(json, metric.getDescription(), FIELD_DESCRIPTION, fieldsToReturn);
- writeIfNeeded(json, metric.getDomain(), FIELD_DOMAIN, fieldsToReturn);
- writeIfNeeded(json, metric.getDirection(), FIELD_DIRECTION, fieldsToReturn);
- writeIfNeeded(json, metric.isQualitative(), FIELD_QUALITATIVE, fieldsToReturn);
- writeIfNeeded(json, metric.isHidden(), FIELD_HIDDEN, fieldsToReturn);
- writeIfNeeded(json, metric.isUserManaged(), FIELD_CUSTOM, fieldsToReturn);
- writeIfNeeded(json, metric.getDecimalScale(), FIELD_DECIMAL_SCALE, fieldsToReturn);
+ 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();
}
}
@Override
public void define(Context context) {
NewController controller = context.createController(ENDPOINT);
- controller.setDescription("Get information on automatic metrics, and manage custom metrics. See also api/custom_measures.");
+ controller.setDescription("Get information on automatic metrics");
controller.setSince("2.6");
for (MetricsWsAction action : actions) {
protected void configureModule() {
add(
MetricsWs.class,
- CreateAction.class,
- DeleteAction.class,
- DomainsAction.class,
SearchAction.class,
- UpdateAction.class,
- UserMetricsAction.class,
TypesAction.class);
}
}
package org.sonar.server.metric.ws;
import java.util.List;
-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.db.metric.MetricDto;
import org.sonar.server.es.SearchOptions;
-import static com.google.common.collect.Sets.newHashSet;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
-import static org.sonar.server.metric.ws.MetricJsonWriter.FIELD_ID;
-import static org.sonar.server.metric.ws.MetricJsonWriter.FIELD_KEY;
public class SearchAction implements MetricsWsAction {
private static final String ACTION = "search";
- public static final String PARAM_IS_CUSTOM = "isCustom";
-
- private final Set<String> allPossibleFields;
-
private final DbClient dbClient;
public SearchAction(DbClient dbClient) {
this.dbClient = dbClient;
- Set<String> possibleFields = newHashSet(FIELD_ID, FIELD_KEY);
- possibleFields.addAll(MetricJsonWriter.OPTIONAL_FIELDS);
- allPossibleFields = possibleFields;
}
@Override
public void define(WebService.NewController context) {
- WebService.NewAction action = context.createAction(ACTION)
+ 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"),
- new Change("7.7", "Field 'custom' in the response is deprecated"))
+ new Change("8.4", "Field 'id' in the response is deprecated"))
.setHandler(this);
-
- action.createFieldsParam(MetricJsonWriter.OPTIONAL_FIELDS)
- .setDeprecatedSince("7.7");
-
- action.createParam(PARAM_IS_CUSTOM)
- .setDeprecatedSince("7.7")
- .setExampleValue("true")
- .setDescription("Choose custom metrics following 3 cases:" +
- "<ul>" +
- "<li>true: only custom metrics are returned</li>" +
- "<li>false: only non custom metrics are returned</li>" +
- "<li>not specified: all metrics are returned</li>" +
- "</ul>");
}
@Override
SearchOptions searchOptions = new SearchOptions()
.setPage(request.mandatoryParamAsInt(Param.PAGE),
request.mandatoryParamAsInt(Param.PAGE_SIZE));
- Boolean isCustom = request.paramAsBoolean(PARAM_IS_CUSTOM);
try (DbSession dbSession = dbClient.openSession(false)) {
- List<MetricDto> metrics = dbClient.metricDao().selectEnabled(dbSession, isCustom, searchOptions.getOffset(), searchOptions.getLimit());
- int nbMetrics = dbClient.metricDao().countEnabled(dbSession, isCustom);
+ List<MetricDto> metrics = dbClient.metricDao().selectEnabled(dbSession, false, searchOptions.getOffset(), searchOptions.getLimit());
+ int nbMetrics = dbClient.metricDao().countEnabled(dbSession, false);
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
- Set<String> desiredFields = desiredFields(request.paramAsStrings(Param.FIELDS));
- writeMetrics(json, metrics, desiredFields);
+ writeMetrics(json, metrics);
searchOptions.writeJson(json, nbMetrics);
json.endObject();
}
}
}
- private Set<String> desiredFields(@Nullable List<String> fields) {
- if (fields == null || fields.isEmpty()) {
- return allPossibleFields;
- }
-
- return newHashSet(fields);
- }
-
- public static void writeMetrics(JsonWriter json, List<MetricDto> metrics, Set<String> desiredFields) {
- MetricJsonWriter.write(json, metrics, desiredFields);
+ public static void writeMetrics(JsonWriter json, List<MetricDto> metrics) {
+ MetricJsonWriter.write(json, metrics);
}
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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 javax.annotation.Nullable;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.server.ws.Change;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.core.util.Uuids;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.server.user.UserSession;
-
-import static org.sonar.db.metric.MetricValidator.MAX_DESCRIPTION_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_DOMAIN_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_KEY_LENGTH;
-import static org.sonar.db.metric.MetricValidator.MAX_NAME_LENGTH;
-import static org.sonar.server.exceptions.BadRequestException.checkRequest;
-
-public class UpdateAction implements MetricsWsAction {
- private static final String ACTION = "update";
-
- public static final String PARAM_ID = "id";
- public static final String PARAM_NAME = "name";
- public static final String PARAM_KEY = "key";
- public static final String PARAM_TYPE = "type";
- public static final String PARAM_DESCRIPTION = "description";
- public static final String PARAM_DOMAIN = "domain";
-
- private static final String FIELD_ID = PARAM_ID;
- private static final String FIELD_NAME = PARAM_NAME;
- private static final String FIELD_KEY = PARAM_KEY;
- private static final String FIELD_TYPE = PARAM_TYPE;
- private static final String FIELD_DESCRIPTION = PARAM_DESCRIPTION;
- private static final String FIELD_DOMAIN = PARAM_DOMAIN;
-
- private final DbClient dbClient;
- private final UserSession userSession;
-
- public UpdateAction(DbClient dbClient, UserSession userSession) {
- this.dbClient = dbClient;
- this.userSession = userSession;
- }
-
- @Override
- public void define(WebService.NewController context) {
- WebService.NewAction action = context.createAction(ACTION)
- .setPost(true)
- .setDescription("Update a custom metric.<br/>" +
- "Requires 'Administer System' permission.")
- .setSince("5.2")
- .setDeprecatedSince("7.7")
- .setHandler(this)
- .setChangelog(
- new Change("8.4", "Parameter 'id' format changes from integer to string."));
-
- action.createParam(PARAM_ID)
- .setRequired(true)
- .setDescription("UUID of the custom metric to update")
- .setExampleValue(Uuids.UUID_EXAMPLE_01);
-
- action.createParam(PARAM_KEY)
- .setDescription("Key")
- .setMaximumLength(MAX_KEY_LENGTH)
- .setDescription("Key")
- .setExampleValue("team_size");
-
- action.createParam(PARAM_NAME)
- .setMaximumLength(MAX_NAME_LENGTH)
- .setDescription("Name");
-
- action.createParam(PARAM_TYPE)
- .setDescription("Metric type key")
- .setPossibleValues(Metric.ValueType.names())
- .setExampleValue(Metric.ValueType.INT.name());
-
- action.createParam(PARAM_DESCRIPTION)
- .setDescription("Description")
- .setMaximumLength(MAX_DESCRIPTION_LENGTH)
- .setExampleValue("Size of the team");
-
- action.createParam(PARAM_DOMAIN)
- .setMaximumLength(MAX_DOMAIN_LENGTH)
- .setDescription("Domain")
- .setExampleValue("Tests");
- }
-
- @Override
- public void handle(Request request, Response response) throws Exception {
- userSession.checkLoggedIn().checkIsSystemAdministrator();
- String uuid = request.mandatoryParam(PARAM_ID);
-
- try (DbSession dbSession = dbClient.openSession(false)) {
- MetricDto metricTemplate = newMetricTemplate(request);
- MetricDto metricInDb = dbClient.metricDao().selectByUuid(dbSession, uuid);
- checkMetricInDbAndTemplate(dbSession, metricInDb, metricTemplate);
-
- updateMetricInDb(dbSession, metricInDb, metricTemplate);
- JsonWriter json = response.newJsonWriter();
- writeMetric(json, metricInDb);
- json.close();
- }
- }
-
- private static MetricDto newMetricTemplate(Request request) {
- String uuid = request.mandatoryParam(PARAM_ID);
- String key = request.param(PARAM_KEY);
- if (key != null) {
- MetricKeyValidator.checkMetricKeyFormat(key);
- }
- String type = request.param(PARAM_TYPE);
- String name = request.param(PARAM_NAME);
- String domain = request.param(PARAM_DOMAIN);
- String description = request.param(PARAM_DESCRIPTION);
-
- MetricDto metricTemplate = new MetricDto().setUuid(uuid);
- if (key != null) {
- metricTemplate.setKey(key);
- }
- if (type != null) {
- metricTemplate.setValueType(type);
- }
- if (name != null) {
- metricTemplate.setShortName(name);
- }
- if (domain != null) {
- metricTemplate.setDomain(domain);
- }
- if (description != null) {
- metricTemplate.setDescription(description);
- }
- return metricTemplate;
- }
-
- private void updateMetricInDb(DbSession dbSession, MetricDto metricInDb, MetricDto metricTemplate) {
- String key = metricTemplate.getKey();
- String name = metricTemplate.getShortName();
- String type = metricTemplate.getValueType();
- String domain = metricTemplate.getDomain();
- String description = metricTemplate.getDescription();
- if (key != null) {
- metricInDb.setKey(key);
- }
- if (name != null) {
- metricInDb.setShortName(name);
- }
- if (type != null) {
- metricInDb.setValueType(type);
- }
- if (domain != null) {
- metricInDb.setDomain(domain);
- }
- if (description != null) {
- metricInDb.setDescription(description);
- }
- dbClient.metricDao().update(dbSession, metricInDb);
- dbSession.commit();
- }
-
- private void checkMetricInDbAndTemplate(DbSession dbSession, @Nullable MetricDto metricInDb, MetricDto template) {
- checkRequest(isMetricFoundInDb(metricInDb) && !isMetricDisabled(metricInDb) && isMetricCustom(metricInDb),
- "No active custom metric has been found for uuid '%s'.", template.getUuid());
- checkNoOtherMetricWithTargetKey(dbSession, metricInDb, template);
- }
-
- private void checkNoOtherMetricWithTargetKey(DbSession dbSession, MetricDto metricInDb, MetricDto template) {
- String targetKey = template.getKey();
- MetricDto metricWithTargetKey = dbClient.metricDao().selectByKey(dbSession, targetKey);
- checkRequest(!isMetricFoundInDb(metricWithTargetKey) || metricInDb.getUuid().equals(metricWithTargetKey.getUuid()),
- "The key '%s' is already used by an existing metric.", targetKey);
- }
-
- private static void writeMetric(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_DOMAIN, metric.getDomain());
- json.prop(FIELD_DESCRIPTION, metric.getDescription());
- json.endObject();
- }
-
- private static boolean isMetricCustom(MetricDto metricInDb) {
- return metricInDb.isUserManaged();
- }
-
- private static boolean isMetricDisabled(MetricDto metricInDb) {
- return !metricInDb.isEnabled();
- }
-
- private static boolean isMetricFoundInDb(@Nullable MetricDto metricInDb) {
- return metricInDb != null;
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.Collection;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.Metric.ValueType;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.Response;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.server.metric.MetricFinder;
-
-public class UserMetricsAction implements MetricsWsAction {
-
- private final MetricFinder metricFinder;
-
- public UserMetricsAction(MetricFinder metricFinder) {
- this.metricFinder = metricFinder;
- }
-
- @Override
- public void handle(Request request, Response response) {
- Collection<Metric> metrics = metricFinder.findAll();
- try (JsonWriter json = response.newJsonWriter()) {
- json.beginObject()
- .name("manual_metrics")
- .beginObject();
- metrics.stream()
- .filter(metric -> metric.getUserManaged() && ValueType.STRING == metric.getType())
- .forEach(metric -> json.prop(metric.getKey(), metric.getName()));
- json.endObject();
- json.name("remote_servers").beginArray().endArray().endObject();
- }
- }
-
- @Override
- public void define(WebService.NewController controller) {
- controller.createAction("user_metrics")
- .setDescription("Metrics managed by users")
- .setSince("1.0")
- .setDeprecatedSince("7.4")
- .setInternal(true)
- .setResponseExample(getClass().getResource("example-user-metrics.json"))
- .setHandler(this);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.measures.Metric.ValueType;
-import org.sonar.api.utils.System2;
-import org.sonar.core.util.SequenceUuidFactory;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.db.metric.MetricTesting;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.ServerException;
-import org.sonar.server.exceptions.UnauthorizedException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestResponse;
-import org.sonar.server.ws.WsActionTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.server.metric.ws.CreateAction.PARAM_DESCRIPTION;
-import static org.sonar.server.metric.ws.CreateAction.PARAM_DOMAIN;
-import static org.sonar.server.metric.ws.CreateAction.PARAM_KEY;
-import static org.sonar.server.metric.ws.CreateAction.PARAM_NAME;
-import static org.sonar.server.metric.ws.CreateAction.PARAM_TYPE;
-
-public class CreateActionTest {
-
- private static final String DEFAULT_KEY = "custom-metric-key";
- private static final String DEFAULT_NAME = "custom-metric-name";
- private static final String DEFAULT_DOMAIN = "custom-metric-domain";
- private static final String DEFAULT_DESCRIPTION = "custom-metric-description";
- private static final String DEFAULT_TYPE = ValueType.INT.name();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- private DbClient dbClient = db.getDbClient();
- private final DbSession dbSession = db.getSession();
- private CreateAction underTest = new CreateAction(dbClient, userSessionRule, new SequenceUuidFactory());
- private WsActionTester tester = new WsActionTester(underTest);
-
- @Before
- public void setUp() {
- userSessionRule.logIn().setSystemAdministrator();
- }
-
- @Test
- public void insert_new_minimalist_metric() {
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .execute();
-
- MetricDto metric = dbClient.metricDao().selectByKey(dbSession, DEFAULT_KEY);
-
- assertThat(metric.getKey()).isEqualTo(DEFAULT_KEY);
- assertThat(metric.getShortName()).isEqualTo(DEFAULT_NAME);
- assertThat(metric.getValueType()).isEqualTo(DEFAULT_TYPE);
- assertThat(metric.getDescription()).isNull();
- assertThat(metric.getDomain()).isNull();
- assertThat(metric.isUserManaged()).isTrue();
- assertThat(metric.isEnabled()).isTrue();
- assertThat(metric.getDirection()).isZero();
- assertThat(metric.isQualitative()).isFalse();
- }
-
- @Test
- public void insert_new_full_metric() {
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .setParam(PARAM_DOMAIN, DEFAULT_DOMAIN)
- .setParam(PARAM_DESCRIPTION, DEFAULT_DESCRIPTION)
- .execute();
-
- MetricDto metric = dbClient.metricDao().selectByKey(dbSession, DEFAULT_KEY);
-
- assertThat(metric.getKey()).isEqualTo(DEFAULT_KEY);
- assertThat(metric.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
- assertThat(metric.getDomain()).isEqualTo(DEFAULT_DOMAIN);
- }
-
- @Test
- public void return_metric_with_uuid() {
- TestResponse result = tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .setParam(PARAM_DOMAIN, DEFAULT_DOMAIN)
- .setParam(PARAM_DESCRIPTION, DEFAULT_DESCRIPTION)
- .execute();
-
- result.assertJson(getClass(), "metric.json");
- assertThat(result.getInput()).matches(".*\"id\"\\s*:\\s*\"\\w+\".*");
- }
-
- @Test
- public void update_existing_metric_when_custom_and_disabled() {
- MetricDto metricInDb = MetricTesting.newMetricDto()
- .setKey(DEFAULT_KEY)
- .setValueType(ValueType.BOOL.name())
- .setUserManaged(true)
- .setEnabled(false);
- dbClient.metricDao().insert(dbSession, metricInDb);
- dbSession.commit();
-
- TestResponse result = tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .setParam(PARAM_DESCRIPTION, DEFAULT_DESCRIPTION)
- .setParam(PARAM_DOMAIN, DEFAULT_DOMAIN)
- .execute();
-
- result.assertJson(getClass(), "metric.json");
- result.getInput().matches("\"id\"\\s*:\\s*\"" + metricInDb.getUuid() + "\"");
- MetricDto metricAfterWs = dbClient.metricDao().selectByKey(dbSession, DEFAULT_KEY);
- assertThat(metricAfterWs.getUuid()).isEqualTo(metricInDb.getUuid());
- assertThat(metricAfterWs.getDomain()).isEqualTo(DEFAULT_DOMAIN);
- assertThat(metricAfterWs.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
- assertThat(metricAfterWs.getValueType()).isEqualTo(DEFAULT_TYPE);
- assertThat(metricAfterWs.getShortName()).isEqualTo(DEFAULT_NAME);
- }
-
- @Test
- public void fail_when_existing_activated_metric_with_same_key() {
- expectedException.expect(ServerException.class);
- dbClient.metricDao().insert(dbSession, MetricTesting.newMetricDto()
- .setKey(DEFAULT_KEY)
- .setValueType(DEFAULT_TYPE)
- .setUserManaged(true)
- .setEnabled(true));
- dbSession.commit();
-
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, "any-name")
- .setParam(PARAM_TYPE, DEFAULT_TYPE).execute();
- }
-
- @Test
- public void fail_when_existing_non_custom_metric_with_same_key() {
- expectedException.expect(ServerException.class);
- dbClient.metricDao().insert(dbSession, MetricTesting.newMetricDto()
- .setKey(DEFAULT_KEY)
- .setValueType(DEFAULT_TYPE)
- .setUserManaged(false)
- .setEnabled(false));
- dbSession.commit();
-
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, "any-name")
- .setParam(PARAM_TYPE, DEFAULT_TYPE).execute();
- }
-
- @Test
- public void fail_when_missing_key() {
- expectedException.expect(IllegalArgumentException.class);
-
- tester.newRequest()
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE).execute();
- }
-
- @Test
- public void fail_when_missing_name() {
- expectedException.expect(IllegalArgumentException.class);
-
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_TYPE, DEFAULT_TYPE).execute();
- }
-
- @Test
- public void fail_when_missing_type() {
- expectedException.expect(IllegalArgumentException.class);
-
- tester.newRequest()
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_KEY, DEFAULT_KEY).execute();
- }
-
- @Test
- public void throw_ForbiddenException_if_not_system_administrator() {
- userSessionRule.logIn().setNonSystemAdministrator();
-
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- tester.newRequest()
- .setParam(PARAM_KEY, "any-key")
- .setParam(PARAM_NAME, "any-name")
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .execute();
- }
-
- @Test
- public void throw_UnauthorizedException_if_not_logged_in() {
- userSessionRule.anonymous();
-
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- tester.newRequest()
- .setParam(PARAM_KEY, "any-key")
- .setParam(PARAM_NAME, "any-name")
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .execute();
- }
-
- @Test
- public void fail_when_ill_formatted_key() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Malformed metric key '123:456'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit.");
-
- tester.newRequest()
- .setParam(PARAM_KEY, "123:456")
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .execute();
- }
-
- @Test
- public void fail_when_empty_name() {
- expectedException.expect(IllegalArgumentException.class);
-
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, "")
- .setParam(PARAM_TYPE, DEFAULT_TYPE)
- .execute();
- }
-
- @Test
- public void fail_when_empty_type() {
- expectedException.expect(IllegalArgumentException.class);
-
- tester.newRequest()
- .setParam(PARAM_KEY, DEFAULT_KEY)
- .setParam(PARAM_NAME, DEFAULT_NAME)
- .setParam(PARAM_TYPE, "")
- .execute();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.server.ws.Change;
-import org.sonar.api.server.ws.WebService.Action;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbTester;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.db.qualitygate.QualityGateConditionDto;
-import org.sonar.db.qualitygate.QualityGateDto;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.UnauthorizedException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestRequest;
-import org.sonar.server.ws.TestResponse;
-import org.sonar.server.ws.WsActionTester;
-
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.tuple;
-import static org.sonar.db.metric.MetricTesting.newMetricDto;
-
-public class DeleteActionTest {
-
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- private final DbClient dbClient = db.getDbClient();
- private final WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSessionRule));
-
- @Test
- public void verify_definition() {
- Action wsDef = ws.getDef();
-
- assertThat(wsDef.deprecatedSince()).isEqualTo("7.7");
- assertThat(wsDef.isInternal()).isFalse();
- assertThat(wsDef.since()).isEqualTo("5.2");
- assertThat(wsDef.isPost()).isTrue();
- assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription)
- .containsExactly(
- tuple("8.4", "Parameter 'ids' format changes from integer to string."));
- }
-
- @Test
- public void delete_by_keys() {
- loggedAsSystemAdministrator();
- insertCustomEnabledMetrics("key-1", "key-2", "key-3");
-
- newRequest().setParam("keys", "key-1, key-3").execute();
-
- List<MetricDto> disabledMetrics = db.getDbClient().metricDao().selectByKeys(db.getSession(), asList("key-1", "key-3"));
- assertThat(disabledMetrics).extracting("enabled").containsOnly(false);
- assertThat(db.getDbClient().metricDao().selectByKey(db.getSession(), "key-2").isEnabled()).isTrue();
- }
-
- @Test
- public void delete_by_id() {
- loggedAsSystemAdministrator();
- MetricDto metric = insertCustomMetric("custom-key");
-
- TestResponse response = newRequest().setParam("ids", String.valueOf(metric.getUuid())).execute();
-
- assertThat(db.getDbClient().metricDao().selectEnabled(db.getSession())).isEmpty();
- assertThat(response.getStatus()).isEqualTo(204);
- }
-
- @Test
- public void does_not_delete_non_custom_metric() {
- loggedAsSystemAdministrator();
- db.getDbClient().metricDao().insert(db.getSession(), newCustomEnabledMetric("custom-key").setUserManaged(false));
- db.getSession().commit();
-
- newRequest().setParam("keys", "custom-key").execute();
-
- MetricDto metric = db.getDbClient().metricDao().selectByKey(db.getSession(), "custom-key");
- assertThat(metric.isEnabled()).isTrue();
- }
-
- @Test
- public void delete_associated_quality_gate_conditions() {
- loggedAsSystemAdministrator();
- MetricDto customMetric = insertCustomMetric("custom-key");
- MetricDto nonCustomMetric = insertMetric(newMetricDto().setEnabled(true).setUserManaged(false).setKey("non-custom"));
- QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate();
- db.qualityGates().addCondition(qualityGate1, customMetric);
- QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate();
- db.qualityGates().addCondition(qualityGate2, customMetric);
- db.qualityGates().addCondition(qualityGate2, nonCustomMetric);
-
- newRequest().setParam("keys", "custom-key").execute();
-
- assertThat(dbClient.gateConditionDao().selectForQualityGate(db.getSession(), qualityGate1.getUuid())).isEmpty();
- assertThat(dbClient.gateConditionDao().selectForQualityGate(db.getSession(), qualityGate2.getUuid()))
- .extracting(QualityGateConditionDto::getMetricUuid).containsOnly(nonCustomMetric.getUuid());
- }
-
- @Test
- public void fail_when_no_argument() {
- loggedAsSystemAdministrator();
- expectedException.expect(IllegalArgumentException.class);
-
- newRequest().execute();
- }
-
- @Test
- public void throw_ForbiddenException_if_not_system_administrator() {
- userSessionRule.logIn().setNonSystemAdministrator();
- insertCustomEnabledMetrics("custom-key");
-
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- newRequest().setParam("keys", "key-1").execute();
- }
-
- @Test
- public void throw_UnauthorizedException_if_not_logged_in() {
- userSessionRule.anonymous();
- insertCustomEnabledMetrics("custom-key");
-
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- newRequest().setParam("keys", "key-1").execute();
- }
-
- private MetricDto newCustomEnabledMetric(String key) {
- return newMetricDto().setEnabled(true).setUserManaged(true).setKey(key);
- }
-
- private void insertCustomEnabledMetrics(String... keys) {
- for (String key : keys) {
- db.getDbClient().metricDao().insert(db.getSession(), newCustomEnabledMetric(key));
- }
- db.getSession().commit();
- }
-
- private MetricDto insertCustomMetric(String key) {
- return insertMetric(newCustomEnabledMetric(key));
- }
-
- private MetricDto insertMetric(MetricDto metric) {
- db.getDbClient().metricDao().insert(db.getSession(), metric);
- db.getSession().commit();
- return metric;
- }
-
- private void loggedAsSystemAdministrator() {
- userSessionRule.logIn().setSystemAdministrator();
- }
-
- private TestRequest newRequest() {
- return ws.newRequest();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.junit.After;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.TestDBSessions;
-import org.sonar.db.metric.MetricDao;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.server.ws.TestRequest;
-import org.sonar.server.ws.WsActionTester;
-import org.sonar.test.JsonAssert;
-
-import static org.sonar.db.metric.MetricTesting.newMetricDto;
-
-
-public class DomainsActionTest {
-
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- private DbClient dbClient = new DbClient(db.database(), db.myBatis(), new TestDBSessions(db.myBatis()), new MetricDao());
- private DbSession dbSession = dbClient.openSession(false);
- private DomainsAction underTest = new DomainsAction(dbClient);
- private WsActionTester tester = new WsActionTester(underTest);
-
- @After
- public void tearDown() {
- dbSession.close();
- }
-
- @Test
- public void json_example_validated() {
- insertNewMetricDto(newEnabledMetric("API Compatibility"));
- insertNewMetricDto(newEnabledMetric("Issues"));
- insertNewMetricDto(newEnabledMetric("Rules"));
- insertNewMetricDto(newEnabledMetric("Tests"));
- insertNewMetricDto(newEnabledMetric("Documentation"));
- insertNewMetricDto(newEnabledMetric(null));
- insertNewMetricDto(newEnabledMetric(""));
- insertNewMetricDto(newMetricDto().setDomain("Domain of Deactivated Metric").setEnabled(false));
-
- TestRequest result = tester.newRequest();
-
- JsonAssert.assertJson(result.execute().getInput()).isSimilarTo(getClass().getResource("example-domains.json"));
- }
-
- private void insertNewMetricDto(MetricDto metric) {
- dbClient.metricDao().insert(dbSession, metric);
- dbSession.commit();
- }
-
- private MetricDto newEnabledMetric(String domain) {
- return newMetricDto().setDomain(domain).setEnabled(true);
- }
-}
public void verify_count_of_added_components() {
ComponentContainer container = new ComponentContainer();
new MetricsWsModule().configure(container);
- assertThat(container.size()).isEqualTo(10);
+ assertThat(container.size()).isEqualTo(5);
}
}
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.SequenceUuidFactory;
-import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
-import org.sonar.server.user.UserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class MetricsWsTest {
- private DbClient dbClient = mock(DbClient.class);
- private UserSession userSession = mock(UserSession.class);
- private UuidFactory uuidFactory = new SequenceUuidFactory();
- private MetricsWs underTest = new MetricsWs(
- new SearchAction(dbClient),
- new CreateAction(dbClient, userSession, uuidFactory),
- new UpdateAction(dbClient, userSession),
- new DeleteAction(dbClient, userSession),
- new TypesAction(),
- new DomainsAction(dbClient));
+ private final DbClient dbClient = mock(DbClient.class);
+ private final MetricsWs underTest = new MetricsWs(
+ new SearchAction(dbClient),
+ new TypesAction());
@Test
public void define_ws() {
WebService.Controller controller = context.controller("api/metrics");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
- assertThat(controller.actions()).hasSize(6);
+ assertThat(controller.actions()).hasSize(2);
}
}
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.metric.MetricDto;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
-import static org.sonar.db.metric.MetricTesting.newMetricDto;
-import static org.sonar.server.metric.ws.SearchAction.PARAM_IS_CUSTOM;
public class SearchActionTest {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
- private DbClient dbClient = db.getDbClient();
+ private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
- private SearchAction underTest = new SearchAction(dbClient);
- private WsActionTester ws = new WsActionTester(underTest);
+ private final SearchAction underTest = new SearchAction(dbClient);
+ private final WsActionTester ws = new WsActionTester(underTest);
@Test
public void verify_definition() {
assertThat(wsDef.isPost()).isFalse();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription)
.containsExactlyInAnyOrder(
- tuple("8.4", "Field 'id' in the response is deprecated"),
- tuple("7.7", "Field 'custom' in the response is deprecated"));
+ tuple("8.4", "Field 'id' in the response is deprecated"));
}
@Test
public void search_metrics_in_database() {
- insertNewCustomMetric("1", "2", "3");
+ db.measures().insertMetric(metricDto -> metricDto
+ .setKey("custom-key-1")
+ .setShortName("custom-name-1")
+ .setValueType("INT")
+ .setDomain("custom-domain-1")
+ .setDescription("custom-description-1")
+ .setDirection(0)
+ .setQualitative(true)
+ .setHidden(false)
+ .setEnabled(true)
+ .setUserManaged(false));
+ db.measures().insertMetric(metricDto -> metricDto
+ .setKey("custom-key-2")
+ .setShortName("custom-name-2")
+ .setValueType("INT")
+ .setDomain("custom-domain-2")
+ .setDescription("custom-description-2")
+ .setDirection(0)
+ .setQualitative(true)
+ .setHidden(false)
+ .setEnabled(true)
+ .setUserManaged(false));
+ db.measures().insertMetric(metricDto -> metricDto
+ .setKey("custom-key-3")
+ .setShortName("custom-name-3")
+ .setValueType("INT")
+ .setDomain("custom-domain-3")
+ .setDescription("custom-description-3")
+ .setDirection(0)
+ .setQualitative(true)
+ .setHidden(false)
+ .setEnabled(true)
+ .setUserManaged(false));
TestResponse result = ws.newRequest().execute();
@Test
public void search_metrics_ordered_by_name_case_insensitive() {
- insertNewCustomMetric("3", "1", "2");
+ insertMetrics("uuid-3", "uuid-1", "uuid-2");
String firstResult = ws.newRequest().setParam(Param.PAGE, "1").setParam(Param.PAGE_SIZE, "1").execute().getInput();
String secondResult = ws.newRequest().setParam(Param.PAGE, "2").setParam(Param.PAGE_SIZE, "1").execute().getInput();
String thirdResult = ws.newRequest().setParam(Param.PAGE, "3").setParam(Param.PAGE_SIZE, "1").execute().getInput();
- assertThat(firstResult).contains("custom-key-1").doesNotContain("custom-key-2").doesNotContain("custom-key-3");
- assertThat(secondResult).contains("custom-key-2").doesNotContain("custom-key-1").doesNotContain("custom-key-3");
- assertThat(thirdResult).contains("custom-key-3").doesNotContain("custom-key-1").doesNotContain("custom-key-2");
+ assertThat(firstResult).contains("uuid-1").doesNotContain("uuid-2").doesNotContain("uuid-3");
+ assertThat(secondResult).contains("uuid-2").doesNotContain("uuid-1").doesNotContain("uuid-3");
+ assertThat(thirdResult).contains("uuid-3").doesNotContain("uuid-1").doesNotContain("uuid-2");
}
@Test
public void search_metrics_with_pagination() {
- insertNewCustomMetric("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
+ insertMetrics("uuid-1", "uuid-2", "uuid-3", "uuid-4", "uuid-5", "uuid-6", "uuid-7", "uuid-8", "uuid-9", "uuid-10");
TestResponse result = ws.newRequest()
.setParam(Param.PAGE, "3")
.setParam(Param.PAGE_SIZE, "4")
.execute();
- assertThat(StringUtils.countMatches(result.getInput(), "custom-key")).isEqualTo(2);
- }
-
- @Test
- public void list_metric_with_is_custom_true() {
- insertNewCustomMetric("1", "2");
- insertNewNonCustomMetric("3");
-
- String result = ws.newRequest()
- .setParam(PARAM_IS_CUSTOM, "true").execute().getInput();
-
- assertThat(result).contains("custom-key-1", "custom-key-2")
- .doesNotContain("non-custom-key-3");
- }
-
- @Test
- public void list_metric_with_is_custom_false() {
- insertNewCustomMetric("1", "2");
- insertNewNonCustomMetric("3");
-
- String result = ws.newRequest()
- .setParam(PARAM_IS_CUSTOM, "false").execute().getInput();
-
- assertThat(result).doesNotContain("custom-key-1")
- .doesNotContain("custom-key-2")
- .contains("non-custom-key-3");
- }
-
- @Test
- public void list_metric_with_chosen_fields() {
- insertNewCustomMetric("1");
-
- String result = ws.newRequest().setParam(Param.FIELDS, "name").execute().getInput();
-
- assertThat(result).contains("id", "key", "name", "type")
- .doesNotContain("domain")
- .doesNotContain("description");
+ assertThat(StringUtils.countMatches(result.getInput(), "name-uuid-")).isEqualTo(2);
}
- private void insertNewNonCustomMetric(String... ids) {
+ private void insertMetrics(String... ids) {
for (String id : ids) {
- dbClient.metricDao().insert(dbSession, newMetricDto()
- .setKey("non-custom-key-" + id)
- .setEnabled(true)
- .setUserManaged(false));
+ db.measures().insertMetric(metricDto -> metricDto.setUuid(id).setShortName("name-" + id).setEnabled(true).setUserManaged(false));
}
dbSession.commit();
}
- private void insertNewCustomMetric(String... ids) {
- for (String id : ids) {
- dbClient.metricDao().insert(dbSession, newCustomMetric(id));
- }
- dbSession.commit();
- }
-
- private MetricDto newCustomMetric(String id) {
- return newMetricDto()
- .setKey("custom-key-" + id)
- .setShortName("custom-name-" + id)
- .setDomain("custom-domain-" + id)
- .setDescription("custom-description-" + id)
- .setValueType("INT")
- .setUserManaged(true)
- .setDirection(0)
- .setHidden(false)
- .setQualitative(true)
- .setEnabled(true);
- }
-
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.measures.Metric.ValueType;
-import org.sonar.api.server.ws.Change;
-import org.sonar.api.server.ws.WebService.Action;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.metric.MetricDto;
-import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.ServerException;
-import org.sonar.server.exceptions.UnauthorizedException;
-import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.ws.TestResponse;
-import org.sonar.server.ws.WsActionTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.tuple;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_DESCRIPTION;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_DOMAIN;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_ID;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_KEY;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_NAME;
-import static org.sonar.server.metric.ws.UpdateAction.PARAM_TYPE;
-
-public class UpdateActionTest {
-
- private static final String DEFAULT_UUID = "custom-metric-uuid";
- private static final String DEFAULT_KEY = "custom-metric-key";
- private static final String DEFAULT_NAME = "custom-metric-name";
- private static final String DEFAULT_DOMAIN = "custom-metric-domain";
- private static final String DEFAULT_DESCRIPTION = "custom-metric-description";
- private static final String DEFAULT_TYPE = ValueType.INT.name();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- private DbClient dbClient = db.getDbClient();
- private final DbSession dbSession = db.getSession();
- private UpdateAction underTest = new UpdateAction(dbClient, userSessionRule);
- private WsActionTester ws = new WsActionTester(underTest);
-
- @Before
- public void setUp() {
- userSessionRule.logIn().setSystemAdministrator();
- }
-
- @Test
- public void verify_definition() {
- Action wsDef = ws.getDef();
-
- assertThat(wsDef.deprecatedSince()).isEqualTo("7.7");
- assertThat(wsDef.isInternal()).isFalse();
- assertThat(wsDef.since()).isEqualTo("5.2");
- assertThat(wsDef.isPost()).isTrue();
- assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription)
- .containsExactly(
- tuple("8.4", "Parameter 'id' format changes from integer to string."));
- }
-
- @Test
- public void update_all_fields() {
- String uuid = insertMetric(newDefaultMetric());
-
- ws.newRequest()
- .setParam(PARAM_ID, uuid)
- .setParam(PARAM_KEY, "another-key")
- .setParam(PARAM_NAME, "another-name")
- .setParam(PARAM_TYPE, ValueType.BOOL.name())
- .setParam(PARAM_DOMAIN, "another-domain")
- .setParam(PARAM_DESCRIPTION, "another-description")
- .execute();
- dbSession.commit();
-
- MetricDto result = dbClient.metricDao().selectByUuid(dbSession, uuid);
- assertThat(result.getKey()).isEqualTo("another-key");
- assertThat(result.getShortName()).isEqualTo("another-name");
- assertThat(result.getValueType()).isEqualTo(ValueType.BOOL.name());
- assertThat(result.getDomain()).isEqualTo("another-domain");
- assertThat(result.getDescription()).isEqualTo("another-description");
- }
-
- @Test
- public void update_one_field() {
- String uuid = insertMetric(newDefaultMetric());
- dbSession.commit();
-
- ws.newRequest()
- .setParam(PARAM_ID, uuid)
- .setParam(PARAM_DESCRIPTION, "another-description")
- .execute();
- dbSession.commit();
-
- MetricDto result = dbClient.metricDao().selectByUuid(dbSession, uuid);
- assertThat(result.getKey()).isEqualTo(DEFAULT_KEY);
- assertThat(result.getShortName()).isEqualTo(DEFAULT_NAME);
- assertThat(result.getValueType()).isEqualTo(DEFAULT_TYPE);
- assertThat(result.getDomain()).isEqualTo(DEFAULT_DOMAIN);
- assertThat(result.getDescription()).isEqualTo("another-description");
- }
-
- @Test
- public void update_return_the_full_object_with_id() {
- String uuid = insertMetric(newDefaultMetric().setDescription("another-description"));
-
- TestResponse requestResult = ws.newRequest()
- .setParam(PARAM_ID, uuid)
- .setParam(PARAM_DESCRIPTION, DEFAULT_DESCRIPTION)
- .execute();
- dbSession.commit();
-
- requestResult.assertJson(getClass(), "metric.json");
- assertThat(requestResult.getInput()).matches(".*\"id\"\\s*:\\s*\"" + uuid + "\".*");
- }
-
- @Test
- public void fail_when_changing_key_for_an_existing_one() {
- expectedException.expect(ServerException.class);
- expectedException.expectMessage("The key 'metric-key' is already used by an existing metric.");
- insertMetric(newDefaultMetric().setKey("metric-key"));
- String uuid = insertMetric(newDefaultMetric().setUuid("another-uuid").setKey("another-key"));
-
- ws.newRequest()
- .setParam(PARAM_ID, uuid)
- .setParam(PARAM_KEY, "metric-key")
- .execute();
- }
-
- @Test
- public void fail_when_metric_not_in_db() {
- expectedException.expect(ServerException.class);
-
- ws.newRequest().setParam(PARAM_ID, "42").execute();
- }
-
- @Test
- public void fail_when_metric_is_deactivated() {
- expectedException.expect(ServerException.class);
- String uuid = insertMetric(newDefaultMetric().setEnabled(false));
-
- ws.newRequest().setParam(PARAM_ID, uuid).execute();
- }
-
- @Test
- public void fail_when_metric_is_not_custom() {
- expectedException.expect(ServerException.class);
- String uuid = insertMetric(newDefaultMetric().setUserManaged(false));
-
- ws.newRequest().setParam(PARAM_ID, uuid).execute();
- }
-
- @Test
- public void fail_when_no_id() {
- expectedException.expect(IllegalArgumentException.class);
-
- ws.newRequest().execute();
- }
-
- @Test
- public void throw_ForbiddenException_if_not_system_administrator() {
- userSessionRule.logIn().setNonSystemAdministrator();
-
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- ws.newRequest().execute();
- }
-
- @Test
- public void throw_UnauthorizedException_if_not_logged_in() {
- userSessionRule.anonymous();
-
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- ws.newRequest().execute();
- }
-
- @Test
- public void fail_when_metric_key_is_not_well_formatted() {
- String uuid = insertMetric(newDefaultMetric());
- dbSession.commit();
-
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Malformed metric key 'not well formatted key'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit.");
-
- ws.newRequest()
- .setParam(PARAM_ID, uuid)
- .setParam(PARAM_KEY, "not well formatted key")
- .execute();
- }
-
- private MetricDto newDefaultMetric() {
- return new MetricDto()
- .setUuid(DEFAULT_UUID)
- .setKey(DEFAULT_KEY)
- .setShortName(DEFAULT_NAME)
- .setValueType(DEFAULT_TYPE)
- .setDomain(DEFAULT_DOMAIN)
- .setDescription(DEFAULT_DESCRIPTION)
- .setUserManaged(true)
- .setEnabled(true);
- }
-
- private String insertMetric(MetricDto metricDto) {
- dbClient.metricDao().insert(dbSession, metricDto);
- dbSession.commit();
- return metricDto.getUuid();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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 com.google.common.collect.Lists;
-import org.junit.Test;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.Metric.ValueType;
-import org.sonar.server.metric.MetricFinder;
-import org.sonar.server.ws.WsActionTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.sonar.test.JsonAssert.assertJson;
-
-public class UserMetricsActionTest {
-
- MetricFinder metrics = mock(MetricFinder.class);
-
- WsActionTester ws = new WsActionTester(new UserMetricsAction(metrics));
-
- @Test
- public void test_definition() {
- assertThat(ws.getDef().key()).isEqualTo("user_metrics");
- assertThat(ws.getDef().isInternal()).isTrue();
- assertThat(ws.getDef().responseExampleAsString()).isNotEmpty();
- assertThat(ws.getDef().params()).isEmpty();
- }
-
- @Test
- public void should_list_manual_metrics() {
- Metric m1 = mock(Metric.class);
- when(m1.getUserManaged()).thenReturn(true);
- when(m1.getKey()).thenReturn("m1");
- when(m1.getName()).thenReturn("Metric 1");
- when(m1.getType()).thenReturn(ValueType.STRING);
- Metric m2 = mock(Metric.class);
- when(m2.getUserManaged()).thenReturn(false);
- Metric m3 = mock(Metric.class);
- when(m3.getUserManaged()).thenReturn(true);
- when(m3.getKey()).thenReturn("m3");
- when(m3.getName()).thenReturn("Metric 3");
- when(m3.getType()).thenReturn(ValueType.STRING);
- Metric m4 = mock(Metric.class);
- when(m4.getUserManaged()).thenReturn(true);
- when(m4.getKey()).thenReturn("m3");
- when(m4.getName()).thenReturn("Metric 4");
- when(m4.getType()).thenReturn(ValueType.INT);
- when(metrics.findAll()).thenReturn(Lists.newArrayList(m1, m2, m3, m4));
-
- assertJson(ws.newRequest().execute().getInput()).isSimilarTo(getClass().getResource("UserMetricsActionTest/app.json"));
- }
-}
"description": "custom-description-1",
"direction": 0,
"qualitative": true,
- "hidden": false,
- "custom": true
+ "hidden": false
},
{
"key": "custom-key-2",
"description": "custom-description-2",
"direction": 0,
"qualitative": true,
- "hidden": false,
- "custom": true
+ "hidden": false
},
{
"key": "custom-key-3",
"description": "custom-description-3",
"direction": 0,
"qualitative": true,
- "hidden": false,
- "custom": true
+ "hidden": false
}
],
"total": 3,
import org.sonar.server.measure.index.ProjectsEsModule;
import org.sonar.server.measure.live.LiveMeasureModule;
import org.sonar.server.measure.ws.MeasuresWsModule;
-import org.sonar.server.metric.CoreCustomMetrics;
import org.sonar.server.metric.MetricFinder;
import org.sonar.server.metric.UnanalyzedLanguageMetrics;
import org.sonar.server.metric.ws.MetricsWsModule;
// measure
MetricsWsModule.class,
MeasuresWsModule.class,
- CoreCustomMetrics.class,
MetricFinder.class,
UnanalyzedLanguageMetrics.class,
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.sonarqube.ws.client.metrics;
-
-import javax.annotation.Generated;
-
-/**
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/create">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
-@Generated("sonar-ws-generator")
-public class CreateRequest {
-
- private String description;
- private String domain;
- private String key;
- private String name;
- private String type;
-
- /**
- * Example value: "Size of the team"
- */
- public CreateRequest setDescription(String description) {
- this.description = description;
- return this;
- }
-
- public String getDescription() {
- return description;
- }
-
- /**
- * Example value: "Tests"
- */
- public CreateRequest setDomain(String domain) {
- this.domain = domain;
- return this;
- }
-
- public String getDomain() {
- return domain;
- }
-
- /**
- * This is a mandatory parameter.
- * Example value: "team_size"
- */
- public CreateRequest setKey(String key) {
- this.key = key;
- return this;
- }
-
- public String getKey() {
- return key;
- }
-
- /**
- * This is a mandatory parameter.
- * Example value: "Team Size"
- */
- public CreateRequest setName(String name) {
- this.name = name;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- /**
- * This is a mandatory parameter.
- * Example value: "INT"
- * Possible values:
- * <ul>
- * <li>"INT"</li>
- * <li>"FLOAT"</li>
- * <li>"PERCENT"</li>
- * <li>"BOOL"</li>
- * <li>"STRING"</li>
- * <li>"MILLISEC"</li>
- * <li>"DATA"</li>
- * <li>"LEVEL"</li>
- * <li>"DISTRIB"</li>
- * <li>"RATING"</li>
- * <li>"WORK_DUR"</li>
- * </ul>
- */
- public CreateRequest setType(String type) {
- this.type = type;
- return this;
- }
-
- public String getType() {
- return type;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.sonarqube.ws.client.metrics;
-
-import java.util.List;
-import javax.annotation.Generated;
-
-/**
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/delete">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
-@Generated("sonar-ws-generator")
-public class DeleteRequest {
-
- private String ids;
- private List<String> keys;
-
- /**
- * Example value: "5, 23, 42"
- */
- public DeleteRequest setIds(String ids) {
- this.ids = ids;
- return this;
- }
-
- public String getIds() {
- return ids;
- }
-
- /**
- * Example value: "team_size, business_value"
- */
- public DeleteRequest setKeys(List<String> keys) {
- this.keys = keys;
- return this;
- }
-
- public List<String> getKeys() {
- return keys;
- }
-}
super(wsConnector, "api/metrics");
}
- /**
- *
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/create">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
- public void create(CreateRequest request) {
- call(
- new PostRequest(path("create"))
- .setParam("description", request.getDescription())
- .setParam("domain", request.getDomain())
- .setParam("key", request.getKey())
- .setParam("name", request.getName())
- .setParam("type", request.getType())
- .setMediaType(MediaTypes.JSON)
- ).content();
- }
-
- /**
- *
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/delete">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
- public void delete(DeleteRequest request) {
- call(
- new PostRequest(path("delete"))
- .setParam("ids", request.getIds())
- .setParam("keys", request.getKeys() == null ? null : request.getKeys().stream().collect(Collectors.joining(",")))
- .setMediaType(MediaTypes.JSON)
- ).content();
- }
-
- /**
- *
- * This is part of the internal API.
- * This is a GET request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/domains">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
- public String domains() {
- return call(
- new GetRequest(path("domains"))
- .setMediaType(MediaTypes.JSON)
- ).content();
- }
-
/**
*
* This is part of the internal API.
).content();
}
- /**
- *
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/update">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
- public void update(UpdateRequest request) {
- call(
- new PostRequest(path("update"))
- .setParam("description", request.getDescription())
- .setParam("domain", request.getDomain())
- .setParam("id", request.getId())
- .setParam("key", request.getKey())
- .setParam("name", request.getName())
- .setParam("type", request.getType())
- .setMediaType(MediaTypes.JSON)
- ).content();
- }
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.sonarqube.ws.client.metrics;
-
-import javax.annotation.Generated;
-
-/**
- * This is part of the internal API.
- * This is a POST request.
- * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/metrics/update">Further information about this action online (including a response example)</a>
- * @since 5.2
- */
-@Generated("sonar-ws-generator")
-public class UpdateRequest {
-
- private String description;
- private String domain;
- private String id;
- private String key;
- private String name;
- private String type;
-
- /**
- * Example value: "Size of the team"
- */
- public UpdateRequest setDescription(String description) {
- this.description = description;
- return this;
- }
-
- public String getDescription() {
- return description;
- }
-
- /**
- * Example value: "Tests"
- */
- public UpdateRequest setDomain(String domain) {
- this.domain = domain;
- return this;
- }
-
- public String getDomain() {
- return domain;
- }
-
- /**
- * This is a mandatory parameter.
- * Example value: "42"
- */
- public UpdateRequest setId(String id) {
- this.id = id;
- return this;
- }
-
- public String getId() {
- return id;
- }
-
- /**
- * Example value: "team_size"
- */
- public UpdateRequest setKey(String key) {
- this.key = key;
- return this;
- }
-
- public String getKey() {
- return key;
- }
-
- /**
- */
- public UpdateRequest setName(String name) {
- this.name = name;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- /**
- * Example value: "INT"
- * Possible values:
- * <ul>
- * <li>"INT"</li>
- * <li>"FLOAT"</li>
- * <li>"PERCENT"</li>
- * <li>"BOOL"</li>
- * <li>"STRING"</li>
- * <li>"MILLISEC"</li>
- * <li>"DATA"</li>
- * <li>"LEVEL"</li>
- * <li>"DISTRIB"</li>
- * <li>"RATING"</li>
- * <li>"WORK_DUR"</li>
- * </ul>
- */
- public UpdateRequest setType(String type) {
- this.type = type;
- return this;
- }
-
- public String getType() {
- return type;
- }
-}