assertThat(picoContainer.getParent().getParent().getParent().getComponentAdapters()).hasSize(
COMPONENTS_IN_LEVEL_1_AT_CONSTRUCTION
+ 24 // level 1
- + 48 // content of DaoModule
+ + 46 // content of DaoModule
+ 2 // content of EsSearchModule
+ 62 // content of CorePropertyDefinitions
+ 1 // content of CePropertyDefinitions
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.sonar.api.measures.Metric;
-
-public class MeasureFilter {
-
- // conditions on resources
- private String baseResourceKey;
-
- // only if baseResourceKey or baseResourceId are set
- private boolean onBaseResourceChildren = false;
-
- private List<String> resourceScopes = Collections.emptyList();
- private List<String> resourceQualifiers = Collections.emptyList();
- private String resourceKey = null;
- private String resourceName = null;
- private Date fromDate = null;
- private Date toDate = null;
- private boolean userFavourites = false;
-
- // conditions on measures
- private List<MeasureFilterCondition> measureConditions = Lists.newArrayList();
-
- // sort
- private MeasureFilterSort sort = new MeasureFilterSort();
-
- public String getBaseResourceKey() {
- return baseResourceKey;
- }
-
- public MeasureFilter setBaseResourceKey(String s) {
- this.baseResourceKey = s;
- return this;
- }
-
- public MeasureFilter setOnBaseResourceChildren(boolean b) {
- this.onBaseResourceChildren = b;
- return this;
- }
-
- public boolean isOnBaseResourceChildren() {
- return onBaseResourceChildren;
- }
-
- public MeasureFilter setResourceScopes(@Nullable List<String> list) {
- this.resourceScopes = sanitize(list);
- return this;
- }
-
- public MeasureFilter setResourceQualifiers(@Nullable List<String> list) {
- this.resourceQualifiers = sanitize(list);
- return this;
- }
-
- public MeasureFilter setUserFavourites(boolean b) {
- this.userFavourites = b;
- return this;
- }
-
- public boolean isOnFavourites() {
- return userFavourites;
- }
-
- @CheckForNull
- public String getResourceName() {
- return resourceName;
- }
-
- public MeasureFilter setResourceName(@Nullable String s) {
- this.resourceName = s;
- return this;
- }
-
- public String getResourceKey() {
- return resourceKey;
- }
-
- public MeasureFilter setResourceKey(String s) {
- this.resourceKey = s;
- return this;
- }
-
- public MeasureFilter addCondition(MeasureFilterCondition condition) {
- this.measureConditions.add(condition);
- return this;
- }
-
- public MeasureFilter setSortOn(MeasureFilterSort.Field sortField) {
- this.sort.setField(sortField);
- return this;
- }
-
- public MeasureFilter setSortAsc(boolean b) {
- this.sort.setAsc(b);
- return this;
- }
-
- public MeasureFilter setSortOnMetric(Metric m) {
- this.sort.setField(MeasureFilterSort.Field.METRIC);
- this.sort.setMetric(m);
- return this;
- }
-
- public MeasureFilter setSortOnPeriod(int period) {
- this.sort.setPeriod(period);
- return this;
- }
-
- public MeasureFilter setFromDate(@Nullable Date d) {
- this.fromDate = d;
- return this;
- }
-
- public MeasureFilter setToDate(@Nullable Date d) {
- this.toDate = d;
- return this;
- }
-
- @CheckForNull
- public Date getFromDate() {
- return fromDate;
- }
-
- @CheckForNull
- public Date getToDate() {
- return toDate;
- }
-
- public List<String> getResourceScopes() {
- return resourceScopes;
- }
-
- public List<String> getResourceQualifiers() {
- return resourceQualifiers;
- }
-
- public List<MeasureFilterCondition> getMeasureConditions() {
- return measureConditions;
- }
-
- MeasureFilterSort sort() {
- return sort;
- }
-
- public boolean isEmpty() {
- return resourceQualifiers.isEmpty() && resourceScopes.isEmpty() && StringUtils.isEmpty(baseResourceKey) && !userFavourites;
- }
-
- @VisibleForTesting
- static List<String> sanitize(@Nullable List<String> list) {
- return isEmptyList(list) ? Collections.emptyList() : Lists.newArrayList(list);
- }
-
- private static boolean isEmptyList(@Nullable List<String> list) {
- boolean blank = false;
- if (list == null || list.isEmpty() || (list.size() == 1 && Strings.isNullOrEmpty(list.get(0)))) {
- blank = true;
- }
- return blank;
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.toString(this);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-import org.sonar.api.measures.Metric;
-
-public class MeasureFilterCondition {
- public enum Operator {
- EQUALS("eq", "="), GREATER("gt", ">"), GREATER_OR_EQUALS("gte", ">="), LESS("lt", "<"), LESS_OR_EQUALS("lte", "<="), IN("in", "IN");
-
- private String code;
- private String sql;
-
- Operator(String code, String sql) {
- this.code = code;
- this.sql = sql;
- }
-
- public String getSql() {
- return sql;
- }
-
- public static Operator fromCode(String code) {
- for (Operator operator : values()) {
- if (operator.code.equals(code)) {
- return operator;
- }
- }
- throw new IllegalArgumentException("Unknown operator code: " + code);
- }
- }
-
- private final Metric metric;
- private final Operator operator;
- private final double value;
- private final String textValue;
- private Integer period = null;
-
- public MeasureFilterCondition(Metric metric, Operator operator, double value) {
- this.metric = metric;
- this.operator = operator;
- this.value = value;
- this.textValue = null;
- }
-
- public MeasureFilterCondition(Metric metric, Operator operator, String textValue) {
- this.metric = metric;
- this.operator = operator;
- this.value = 0;
- this.textValue = textValue;
- }
-
- public MeasureFilterCondition setPeriod(Integer period) {
- this.period = period;
- return this;
- }
-
- public Metric metric() {
- return metric;
- }
-
- public Operator operator() {
- return operator;
- }
-
- public double value() {
- return value;
- }
-
- public String textValue() {
- return textValue;
- }
-
- public Integer period() {
- return period;
- }
-
- StringBuilder appendSqlColumn(StringBuilder sb, int conditionIndex) {
- sb.append("pmcond").append(conditionIndex);
- if (period != null) {
- sb.append(".variation_value_").append(period).toString();
- } else if (textValue == null) {
- sb.append(".value");
- } else {
- sb.append(".text_value");
- }
- return sb;
- }
-
- StringBuilder appendSqlCondition(StringBuilder sql, int conditionIndex) {
- String table = "pmcond" + conditionIndex;
- sql.append(" ").append(table).append(".metric_id=");
- sql.append(metric.getId());
- sql.append(" and ");
- appendSqlColumn(sql, conditionIndex);
- sql.append(" ").append(operator.getSql()).append(" ");
- if (textValue == null) {
- sql.append(value);
- } else {
- sql.append(textValue);
- }
- sql.append(" and ");
- sql.append(table).append(".person_id is null ");
- return sql;
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.toString(this, ToStringStyle.SIMPLE_STYLE);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import javax.annotation.Nullable;
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-import org.sonar.db.component.ComponentDto;
-
-class MeasureFilterContext {
- private Long userId = null;
- private ComponentDto baseComponent = null;
- private String sql;
- private String data;
-
- Long getUserId() {
- return userId;
- }
-
- MeasureFilterContext setUserId(@Nullable Long userId) {
- this.userId = userId;
- return this;
- }
-
- ComponentDto getBaseComponent() {
- return baseComponent;
- }
-
- MeasureFilterContext setBaseComponent(@Nullable ComponentDto baseComponent) {
- this.baseComponent = baseComponent;
- return this;
- }
-
- String getSql() {
- return sql;
- }
-
- MeasureFilterContext setSql(String sql) {
- this.sql = sql;
- return this;
- }
-
- String getData() {
- return data;
- }
-
- MeasureFilterContext setData(String data) {
- this.data = data;
- return this;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
- .append("filter", data)
- .append("sql", sql)
- .append("user", userId)
- .toString();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.base.Joiner;
-import org.sonar.api.server.ServerSide;
-import org.sonar.api.utils.log.Logger;
-import org.sonar.api.utils.log.Loggers;
-import org.sonar.api.utils.log.Profiler;
-
-import javax.annotation.Nullable;
-
-import java.util.List;
-import java.util.Map;
-
-@ServerSide
-public class MeasureFilterEngine {
-
- private static final Logger LOG = Loggers.get("MeasureFilter");
-
- private final MeasureFilterFactory factory;
- private final MeasureFilterExecutor executor;
-
- public MeasureFilterEngine(MeasureFilterFactory factory, MeasureFilterExecutor executor) {
- this.executor = executor;
- this.factory = factory;
- }
-
- public MeasureFilterResult execute(Map<String, Object> filterMap, @Nullable Long userId) {
- Profiler profiler = Profiler.createIfDebug(LOG).start();
- MeasureFilterResult result = new MeasureFilterResult();
- MeasureFilterContext context = new MeasureFilterContext();
- context.setUserId(userId);
- context.setData(String.format("{%s}", Joiner.on('|').withKeyValueSeparator("=").join(filterMap)));
- try {
- profiler.addContext("request", context.getData());
- MeasureFilter filter = factory.create(filterMap);
- List<MeasureFilterRow> rows = executor.execute(filter, context);
- result.setRows(rows);
-
- } catch (NumberFormatException e) {
- result.setError(MeasureFilterResult.Error.VALUE_SHOULD_BE_A_NUMBER);
- LOG.debug("Value selected for the metric should be a number: " + context);
- } catch (Exception e) {
- result.setError(MeasureFilterResult.Error.UNKNOWN);
- LOG.error("Fail to execute measure filter: " + context, e);
- } finally {
- profiler.addContext("result", result.toString());
- profiler.stopDebug("Measure filter executed");
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Strings;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.util.Collections;
-import java.util.List;
-import org.apache.commons.dbutils.DbUtils;
-import org.sonar.api.server.ServerSide;
-import org.sonar.db.Database;
-import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
-import org.sonar.db.component.ComponentDao;
-import org.sonar.db.component.ComponentDto;
-
-@ServerSide
-public class MeasureFilterExecutor {
-
- private MyBatis mybatis;
- private Database database;
- private ComponentDao componentDao;
-
- public MeasureFilterExecutor(MyBatis mybatis, Database database, ComponentDao componentDao) {
- this.mybatis = mybatis;
- this.database = database;
- this.componentDao = componentDao;
- }
-
- public List<MeasureFilterRow> execute(MeasureFilter filter, MeasureFilterContext context) throws SQLException {
- if (filter.isEmpty()) {
- return Collections.emptyList();
- }
-
- List<MeasureFilterRow> rows;
- DbSession session = null;
- Connection connection = null;
- try {
- session = mybatis.openSession(false);
- prepareContext(context, filter, session);
-
- if (isValid(filter, context)) {
- MeasureFilterSql sql = new MeasureFilterSql(database, filter, context);
- context.setSql(sql.sql());
- connection = session.getConnection();
- rows = sql.execute(connection);
- } else {
- rows = Collections.emptyList();
- }
- } finally {
- MyBatis.closeQuietly(session);
- // connection is supposed to be closed by the session
- DbUtils.closeQuietly(connection);
- }
-
- return rows;
- }
-
- private void prepareContext(MeasureFilterContext context, MeasureFilter filter, DbSession session) {
- if (filter.getBaseResourceKey() != null) {
- Optional<ComponentDto> component = componentDao.selectByKey(session, filter.getBaseResourceKey());
- if (component.isPresent()) {
- context.setBaseComponent(component.get());
- }
- }
- }
-
- static boolean isValid(MeasureFilter filter, MeasureFilterContext context) {
- boolean valid = Strings.isNullOrEmpty(filter.getBaseResourceKey()) || context.getBaseComponent() != null;
- valid &= !(filter.isOnBaseResourceChildren() && context.getBaseComponent() == null);
- valid &= !(filter.isOnFavourites() && context.getUserId() == null);
- valid &= validateMeasureConditions(filter);
- valid &= validateSort(filter);
- return valid;
- }
-
- private static boolean validateMeasureConditions(MeasureFilter filter) {
- boolean valid = true;
- for (MeasureFilterCondition condition : filter.getMeasureConditions()) {
- if (condition.period() != null && condition.period() < 1) {
- valid = false;
- }
- if (condition.metric() == null) {
- valid = false;
- }
- }
- return valid;
- }
-
- private static boolean validateSort(MeasureFilter filter) {
- boolean valid = true;
- if (filter.sort().period() != null && filter.sort().period() < 1) {
- valid = false;
- }
- if (filter.sort().onMeasures() && filter.sort().metric() == null) {
- valid = false;
- }
- return valid;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Strings;
-import com.google.common.collect.Iterables;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.server.ServerSide;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.api.utils.System2;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.collect.Lists.transform;
-import static java.util.Collections.singletonList;
-
-@ServerSide
-public class MeasureFilterFactory {
-
- private final MetricFinder metricFinder;
- private final System2 system;
-
- public MeasureFilterFactory(MetricFinder metricFinder, System2 system) {
- this.metricFinder = metricFinder;
- this.system = system;
- }
-
- public MeasureFilter create(Map<String, Object> properties) {
- MeasureFilter filter = new MeasureFilter();
- filter.setBaseResourceKey((String) properties.get("base"));
- filter.setResourceScopes(toList(properties.get("scopes")));
- filter.setResourceQualifiers(toList(properties.get("qualifiers")));
- MeasureFilterCondition condition = alertToCondition(toList(properties.get("alertLevels")));
- if (condition != null) {
- filter.addCondition(condition);
- }
- String onBaseComponents = (String) properties.get("onBaseComponents");
- if (onBaseComponents != null) {
- filter.setOnBaseResourceChildren(Boolean.valueOf(onBaseComponents));
- }
- filter.setResourceName(toString(properties.get("nameSearch")));
- filter.setResourceKey((String) properties.get("keySearch"));
- String onFavourites = (String) properties.get("onFavourites");
- if (onFavourites != null) {
- filter.setUserFavourites(Boolean.valueOf(onFavourites));
- }
- fillDateConditions(filter, properties);
- fillSorting(filter, properties);
- fillMeasureConditions(properties, filter);
- return filter;
- }
-
- private void fillDateConditions(MeasureFilter filter, Map<String, Object> properties) {
- String fromDate = (String) properties.get("fromDate");
- if (fromDate != null) {
- filter.setFromDate(toDate(fromDate));
- } else {
- filter.setFromDate(toDays((String) properties.get("ageMaxDays")));
- }
- String toDate = (String) properties.get("toDate");
- if (toDate != null) {
- filter.setToDate(toDate(toDate));
- } else {
- filter.setToDate(toDays((String) properties.get("ageMinDays")));
- }
- }
-
- private void fillMeasureConditions(Map<String, Object> properties, MeasureFilter filter) {
- for (int index = 1; index <= 3; index++) {
- MeasureFilterCondition condition = toCondition(properties, index);
- if (condition != null) {
- filter.addCondition(condition);
- }
- }
- }
-
- private void fillSorting(MeasureFilter filter, Map<String, Object> properties) {
- String s = (String) properties.get("sort");
- if (s != null) {
- if (StringUtils.startsWith(s, "metric:")) {
- String[] fields = StringUtils.split(s, ':');
- Metric metric = metricFinder.findByKey(fields[1]);
- if (metric != null) {
- filter.setSortOnMetric(metric);
- if (fields.length == 3) {
- filter.setSortOnPeriod(Integer.parseInt(fields[2]));
- }
- }
- } else {
- String sort = s.toUpperCase();
- if (sortFieldLabels().contains(sort)) {
- filter.setSortOn(MeasureFilterSort.Field.valueOf(sort));
- }
- }
- }
-
- if (properties.containsKey("asc")) {
- filter.setSortAsc(Boolean.valueOf((String) properties.get("asc")));
- }
- }
-
- private static List<String> sortFieldLabels() {
- return newArrayList(Iterables.transform(Arrays.asList(MeasureFilterSort.Field.values()), FieldToName.INSTANCE));
- }
-
- @CheckForNull
- private MeasureFilterCondition toCondition(Map<String, Object> props, int index) {
- MeasureFilterCondition condition = null;
- String metricKey = (String) props.get("c" + index + "_metric");
- String op = (String) props.get("c" + index + "_op");
- String val = (String) props.get("c" + index + "_val");
- if (!Strings.isNullOrEmpty(metricKey) && !Strings.isNullOrEmpty(op) && !Strings.isNullOrEmpty(val)) {
- Metric metric = metricFinder.findByKey(metricKey);
- MeasureFilterCondition.Operator operator = MeasureFilterCondition.Operator.fromCode(op);
- condition = new MeasureFilterCondition(metric, operator, Double.parseDouble(val));
- String period = (String) props.get("c" + index + "_period");
- if (period != null) {
- condition.setPeriod(Integer.parseInt(period));
- }
- }
- return condition;
- }
-
- @CheckForNull
- private MeasureFilterCondition alertToCondition(@Nullable List<String> alertLevels) {
- if (alertLevels == null || alertLevels.isEmpty()) {
- return null;
- }
- List<String> availableLevels = transform(Arrays.asList(Metric.Level.values()), MetricLevelToName.INSTANCE);
- List<String> alertLevelsUppercase = transform(alertLevels, new AlertLevelToUppercase(availableLevels));
- String val = "('" + Joiner.on("', '").skipNulls().join(alertLevelsUppercase) + "')";
- Metric metric = metricFinder.findByKey(CoreMetrics.ALERT_STATUS_KEY);
- if (metric != null) {
- MeasureFilterCondition.Operator operator = MeasureFilterCondition.Operator.fromCode("in");
- return new MeasureFilterCondition(metric, operator, val);
- }
- return null;
- }
-
- private static List<String> toList(@Nullable Object obj) {
- List<String> result = null;
- if (obj != null) {
- if (obj instanceof String) {
- result = singletonList((String) obj);
- } else {
- result = (List<String>) obj;
- }
- }
- return result;
- }
-
- @CheckForNull
- private static Date toDate(@Nullable String date) {
- if (date != null) {
- return DateUtils.parseDate(date);
- }
- return null;
- }
-
- @CheckForNull
- private Date toDays(@Nullable String s) {
- if (s != null) {
- int days = Integer.parseInt(s);
- Date date = org.apache.commons.lang.time.DateUtils.truncate(new Date(system.now()), Calendar.DATE);
- date = org.apache.commons.lang.time.DateUtils.addDays(date, -days);
- return date;
- }
- return null;
- }
-
- @CheckForNull
- public static String toString(@Nullable Object o) {
- if (o != null) {
- if (o instanceof List) {
- return Joiner.on(",").join((List) o);
- } else if (o instanceof String[]) {
- // assume that it contains only strings
- return Joiner.on(",").join((String[]) o);
- } else {
- return o.toString();
- }
- }
- return null;
- }
-
- private enum FieldToName implements Function<MeasureFilterSort.Field, String> {
- INSTANCE;
-
- @Override
- public String apply(@Nullable MeasureFilterSort.Field input) {
- return input != null ? input.name() : null;
- }
- }
-
- private enum MetricLevelToName implements Function<Metric.Level, String> {
- INSTANCE;
-
- @Override
- public String apply(@Nullable Metric.Level input) {
- return input != null ? input.name() : null;
- }
- }
-
- private static class AlertLevelToUppercase implements Function<String, String> {
- private final List<String> availableLevels;
-
- public AlertLevelToUppercase(List<String> availableLevels) {
- this.availableLevels = availableLevels;
- }
-
- @Override
- public String apply(@Nullable String input) {
- return input != null && availableLevels.contains(input.toUpperCase()) ? input.toUpperCase() : null;
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import javax.annotation.Nullable;
-
-import java.util.List;
-
-public class MeasureFilterResult {
-
- public enum Error {
- UNKNOWN, VALUE_SHOULD_BE_A_NUMBER
- }
-
- private List<MeasureFilterRow> rows = null;
- private Error error = null;
-
- MeasureFilterResult() {
- }
-
- public List<MeasureFilterRow> getRows() {
- return rows;
- }
-
- public Error getError() {
- return error;
- }
-
- MeasureFilterResult setRows(@Nullable List<MeasureFilterRow> rows) {
- this.rows = rows;
- return this;
- }
-
- MeasureFilterResult setError(@Nullable Error err) {
- this.error = err;
- return this;
- }
-
- public boolean isSuccess() {
- return error == null;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- if (rows != null) {
- sb.append(rows.size()).append(" rows, ");
- }
- if (error != null) {
- sb.append("error=").append(error).append(", ");
- }
- return sb.toString();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import org.apache.commons.lang.StringUtils;
-
-public class MeasureFilterRow {
- private final String componentUuid;
- private final String rootComponentUuid;
- private String sortText = null;
- private Long sortDate = null;
- private Double sortDouble = null;
-
- MeasureFilterRow(String componentUuid, String rootComponentUuid) {
- this.componentUuid = componentUuid;
- this.rootComponentUuid = rootComponentUuid;
- }
-
- public String getComponentUuid() {
- return componentUuid;
- }
-
- public String getRootComponentUuid() {
- return rootComponentUuid;
- }
-
- public String getSortText() {
- return sortText;
- }
-
- void setSortText(String s) {
- this.sortText = StringUtils.defaultString(s);
- }
-
- Long getSortDate() {
- return sortDate;
- }
-
- void setSortDate(Long sortDate) {
- this.sortDate = sortDate;
- }
-
- Double getSortDouble() {
- return sortDouble;
- }
-
- void setSortDouble(Double sortDouble) {
- this.sortDouble = sortDouble;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Metric;
-
-class MeasureFilterSort {
- private Field field = Field.NAME;
- private Metric metric = null;
- private Integer period = null;
- private boolean asc = true;
-
- MeasureFilterSort() {
- }
-
- void setField(Field field) {
- this.field = field;
- }
-
- void setMetric(Metric metric) {
- this.field = Field.METRIC;
- this.metric = metric;
- }
-
- Integer period() {
- return period;
- }
-
- void setPeriod(Integer period) {
- this.period = period;
- }
-
- public Field field() {
- return field;
- }
-
- boolean onMeasures() {
- return field == Field.METRIC;
- }
-
- Metric metric() {
- return metric;
- }
-
- boolean isOnMeasure() {
- return metric != null;
- }
-
- boolean isOnNumericMeasure() {
- return metric != null && metric.isNumericType();
- }
-
- boolean isOnDate() {
- return Field.PROJECT_CREATION_DATE.equals(field);
- }
-
- boolean isOnTime() {
- return Field.DATE.equals(field);
- }
-
- boolean isOnAlert() {
- return metric != null && metric.getKey().equals(CoreMetrics.ALERT_STATUS_KEY);
- }
-
- boolean isAsc() {
- return asc;
- }
-
- void setAsc(boolean asc) {
- this.asc = asc;
- }
-
- String column() {
- // only numeric metrics can be sorted by database, else results are sorted programmatically.
- String column;
- switch (field) {
- case KEY:
- column = "c.kee";
- break;
- case NAME:
- column = "c.long_name";
- break;
- case SHORT_NAME:
- column = "c.name";
- break;
- case DESCRIPTION:
- column = "c.description";
- break;
- case VERSION:
- column = "s.version";
- break;
- case DATE:
- column = "s.created_at";
- break;
- case PROJECT_CREATION_DATE:
- column = "c.created_at";
- break;
- case METRIC:
- column = getMetricColumn();
- break;
- default:
- throw new IllegalArgumentException("Unsupported sorting: " + field);
- }
- return column;
- }
-
- private String getMetricColumn() {
- if (metric.isNumericType()) {
- return period != null ? ("pmsort.variation_value_" + period) : "pmsort.value";
- } else {
- return "pmsort.text_value";
- }
- }
-
- public enum Field {
- KEY, NAME, VERSION, METRIC, SHORT_NAME, DESCRIPTION,
- // Sort by last analysis date
- DATE,
- // Sort by project creation date
- PROJECT_CREATION_DATE
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Ordering;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.List;
-import javax.annotation.Nullable;
-import org.apache.commons.dbutils.DbUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.db.Database;
-import org.sonar.db.DatabaseUtils;
-import org.sonar.db.WildcardPosition;
-import org.sonar.db.component.ComponentDto;
-import org.sonar.db.dialect.MsSql;
-import org.sonar.db.dialect.Oracle;
-
-import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
-
-class MeasureFilterSql {
-
- private final Database database;
- private final MeasureFilter filter;
- private final MeasureFilterContext context;
- private final String sql;
- private final List<Long> dateParameters = Lists.newArrayList();
-
- MeasureFilterSql(Database database, MeasureFilter filter, MeasureFilterContext context) {
- this.database = database;
- this.filter = filter;
- this.context = context;
- this.sql = generateSql();
- }
-
- private static void appendInStatement(List<String> values, StringBuilder to) {
- to.append(" (");
- for (int i = 0; i < values.size(); i++) {
- if (i > 0) {
- to.append(",");
- }
- to.append("'");
- to.append(StringEscapeUtils.escapeSql(values.get(i)));
- to.append("'");
- }
- to.append(") ");
- }
-
- private static Ordering newObjectOrdering(boolean ascending) {
- if (ascending) {
- return Ordering.from(new AscendingComparator());
- }
- return Ordering.from(new DescendingComparator());
- }
-
- List<MeasureFilterRow> execute(Connection connection) throws SQLException {
- PreparedStatement statement = connection.prepareStatement(sql);
- ResultSet rs = null;
- try {
- for (int index = 0; index < dateParameters.size(); index++) {
- statement.setLong(index + 1, dateParameters.get(index));
- }
- rs = statement.executeQuery();
- return process(rs);
-
- } finally {
- DbUtils.closeQuietly(rs);
- DbUtils.closeQuietly(statement);
- }
- }
-
- String sql() {
- return sql;
- }
-
- private String generateSql() {
- StringBuilder sb = new StringBuilder(1000);
- sb.append("select c.uuid, c.project_uuid, ");
- sb.append(filter.sort().column());
- sb.append(" from projects c");
- sb.append(" inner join snapshots s on s.component_uuid=c.project_uuid ");
- if (context.getBaseComponent() != null) {
- sb.append(" inner join projects base on base.project_uuid = c.project_uuid ");
- }
-
- for (int index = 0; index < filter.getMeasureConditions().size(); index++) {
- MeasureFilterCondition condition = filter.getMeasureConditions().get(index);
- sb.append(" inner join project_measures pmcond").append(index);
- sb.append(" on pmcond").append(index).append(".analysis_uuid = s.uuid and ");
- sb.append(" pmcond").append(index).append(".component_uuid = c.uuid and ");
- condition.appendSqlCondition(sb, index);
- }
-
- if (filter.isOnFavourites()) {
- sb.append(" inner join properties props on props.resource_id=c.id ");
- }
-
- if (filter.sort().isOnMeasure()) {
- sb.append(" left outer join project_measures pmsort ON s.uuid = pmsort.analysis_uuid and pmsort.component_uuid = c.uuid and pmsort.metric_id=");
- sb.append(filter.sort().metric().getId());
- sb.append(" and pmsort.person_id is null ");
- }
-
- sb.append(" where ");
- sb.append(" s.islast=").append(database.getDialect().getTrueSqlValue());
- appendComponentConditions(sb);
-
- for (int index = 0; index < filter.getMeasureConditions().size(); index++) {
- MeasureFilterCondition condition = filter.getMeasureConditions().get(index);
- sb.append(" and ");
- condition.appendSqlCondition(sb, index);
- }
-
- return sb.toString();
- }
-
- private void appendComponentConditions(StringBuilder sb) {
- sb.append(" and c.enabled=").append(database.getDialect().getTrueSqlValue());
- ComponentDto base = context.getBaseComponent();
- if (base == null) {
- sb.append(" and c.copy_component_uuid is null ");
- } else {
- sb.append(" and base.uuid = '").append(base.uuid()).append("' ");
- if (filter.isOnBaseResourceChildren()) {
- String path = base.getUuidPath() + base.uuid() + UUID_PATH_SEPARATOR;
- sb.append(" and c.uuid_path = '").append(path).append("' ");
- } else {
- String like = DatabaseUtils.buildLikeValue(base.getUuidPath() + base.uuid() + UUID_PATH_SEPARATOR, WildcardPosition.AFTER);
- sb.append(" and c.uuid_path like '").append(like).append("' escape '/' ");
- }
- }
- if (!filter.getResourceQualifiers().isEmpty()) {
- sb.append(" and c.qualifier in ");
- appendInStatement(filter.getResourceQualifiers(), sb);
- }
- if (!filter.getResourceScopes().isEmpty()) {
- sb.append(" and c.scope in ");
- appendInStatement(filter.getResourceScopes(), sb);
- }
- appendDateConditions(sb);
- appendFavouritesCondition(sb);
- appendResourceNameCondition(sb);
- appendResourceKeyCondition(sb);
- }
-
- private void appendDateConditions(StringBuilder sb) {
- Date fromDate = filter.getFromDate();
- if (fromDate != null) {
- sb.append(" and s.created_at >= ? ");
- dateParameters.add(fromDate.getTime());
- }
- Date toDate = filter.getToDate();
- if (toDate != null) {
- sb.append(" and s.created_at <= ? ");
- dateParameters.add(toDate.getTime());
- }
- }
-
- private void appendFavouritesCondition(StringBuilder sb) {
- if (filter.isOnFavourites()) {
- sb.append(" and props.prop_key='favourite' and props.resource_id is not null and props.user_id=");
- sb.append(context.getUserId());
- sb.append(" ");
- }
- }
-
- private void appendResourceKeyCondition(StringBuilder sb) {
- if (StringUtils.isNotBlank(filter.getResourceKey())) {
- sb.append(" and UPPER(c.kee) like '%");
- sb.append(escapePercentAndUnderscrore(StringEscapeUtils.escapeSql(StringUtils.upperCase(filter.getResourceKey()))));
- sb.append("%'");
- appendEscapeForSomeDb(sb);
- }
- }
-
- private void appendResourceNameCondition(StringBuilder sb) {
- if (StringUtils.isNotBlank(filter.getResourceName())) {
- sb.append(" and c.uuid in (select rindex.component_uuid from resource_index rindex WHERE rindex.kee LIKE '");
- sb.append(escapePercentAndUnderscrore(StringEscapeUtils.escapeSql(StringUtils.lowerCase(filter.getResourceName()))));
- sb.append("%'");
- appendEscapeForSomeDb(sb);
- if (!filter.getResourceQualifiers().isEmpty()) {
- sb.append(" AND rindex.qualifier IN ");
- appendInStatement(filter.getResourceQualifiers(), sb);
- }
- sb.append(") ");
- }
- }
-
- List<MeasureFilterRow> process(ResultSet rs) throws SQLException {
- List<MeasureFilterRow> rows = Lists.newArrayList();
- RowProcessor rowProcessor;
- if (filter.sort().isOnNumericMeasure()) {
- rowProcessor = new NumericSortRowProcessor();
- } else if (filter.sort().isOnDate()) {
- rowProcessor = new DateSortRowProcessor();
- } else if (filter.sort().isOnTime()) {
- rowProcessor = new LongSortRowProcessor();
- } else if (filter.sort().isOnAlert()) {
- rowProcessor = new AlertSortRowProcessor();
- } else {
- rowProcessor = new TextSortRowProcessor();
- }
-
- while (rs.next()) {
- rows.add(rowProcessor.fetch(rs));
- }
-
- return rowProcessor.sort(rows, filter.sort().isAsc());
- }
-
- /**
- * Replace escape percent and underscore by adding a slash just before
- */
- private static String escapePercentAndUnderscrore(String value) {
- return value.replaceAll("%", "\\\\%").replaceAll("_", "\\\\_");
- }
-
- private void appendEscapeForSomeDb(StringBuilder sb) {
- if (database.getDialect().getId().equals(Oracle.ID) || database.getDialect().getId().equals(MsSql.ID)) {
- sb.append(" ESCAPE '\\'");
- }
- }
-
- abstract static class RowProcessor {
- abstract Function sortFieldFunction();
-
- abstract Ordering sortFieldOrdering(boolean ascending);
-
- abstract MeasureFilterRow fetch(ResultSet rs) throws SQLException;
-
- final List<MeasureFilterRow> sort(List<MeasureFilterRow> rows, boolean ascending) {
- Ordering<MeasureFilterRow> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
- return ordering.immutableSortedCopy(rows);
- }
- }
-
- static class TextSortRowProcessor extends RowProcessor {
- @Override
- MeasureFilterRow fetch(ResultSet rs) throws SQLException {
- MeasureFilterRow row = new MeasureFilterRow(rs.getString(1), rs.getString(2));
- row.setSortText(rs.getString(3));
- return row;
- }
-
- @Override
- Function sortFieldFunction() {
- return new Function<MeasureFilterRow, String>() {
- @Override
- public String apply(MeasureFilterRow row) {
- return row.getSortText();
- }
- };
- }
-
- @Override
- Ordering sortFieldOrdering(boolean ascending) {
- Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER);
- if (!ascending) {
- ordering = ordering.reverse();
- }
- return ordering;
- }
- }
-
- static class AlertSortRowProcessor extends TextSortRowProcessor {
- @Override
- Function sortFieldFunction() {
- return new MeasureFilterRowToAlertIndexFunction();
- }
-
- @Override
- Ordering sortFieldOrdering(boolean ascending) {
- Ordering<Integer> ordering = Ordering.<Integer>natural().nullsLast();
- if (!ascending) {
- ordering = ordering.reverse();
- }
- return ordering;
- }
-
- }
- static class NumericSortRowProcessor extends RowProcessor {
-
- @Override
- MeasureFilterRow fetch(ResultSet rs) throws SQLException {
- MeasureFilterRow row = new MeasureFilterRow(rs.getString(1), rs.getString(2));
- double value = rs.getDouble(3);
- if (!rs.wasNull()) {
- row.setSortDouble(value);
- }
- return row;
- }
- @Override
- Function sortFieldFunction() {
- return new MeasureFilterRowToSortDoubleFunction();
- }
-
- @Override
- Ordering sortFieldOrdering(boolean ascending) {
- return ascending ? Ordering.natural().nullsLast() : Ordering.natural().reverse().nullsLast();
- }
-
- private static class MeasureFilterRowToSortDoubleFunction implements Function<MeasureFilterRow, Double> {
-
- @Override
- public Double apply(MeasureFilterRow row) {
- return row.getSortDouble();
- }
- }
- }
- static class DateSortRowProcessor extends RowProcessor {
-
- @Override
- MeasureFilterRow fetch(ResultSet rs) throws SQLException {
- MeasureFilterRow row = new MeasureFilterRow(rs.getString(1), rs.getString(2));
- row.setSortDate(rs.getTimestamp(3).getTime());
- return row;
- }
- @Override
- Function sortFieldFunction() {
- return new MeasureFilterRowToSortDateFunction();
- }
-
- @Override
- Ordering sortFieldOrdering(boolean ascending) {
- return newObjectOrdering(ascending);
- }
-
- }
- static class LongSortRowProcessor extends RowProcessor {
-
- @Override
- MeasureFilterRow fetch(ResultSet rs) throws SQLException {
- MeasureFilterRow row = new MeasureFilterRow(rs.getString(1), rs.getString(2));
- row.setSortDate(rs.getLong(3));
- return row;
- }
-
- @Override
- Function sortFieldFunction() {
- return new MeasureFilterRowToSortDateFunction();
- }
-
- @Override
- Ordering sortFieldOrdering(boolean ascending) {
- return newObjectOrdering(ascending);
- }
-
- }
-
- private static class MeasureFilterRowToAlertIndexFunction implements Function<MeasureFilterRow, Integer> {
- @Override
- public Integer apply(MeasureFilterRow row) {
- return ImmutableList.of("OK", "WARN", "ERROR").indexOf(row.getSortText());
- }
- }
-
- private static class MeasureFilterRowToSortDateFunction implements Function<MeasureFilterRow, Long> {
- @Override
- public Long apply(MeasureFilterRow row) {
- return row.getSortDate();
- }
- }
-
- private static class AscendingComparator implements Comparator<Comparable> {
- @Override
- public int compare(@Nullable Comparable left, @Nullable Comparable right) {
- if (left == null) {
- return 1;
- }
- if (right == null) {
- return -1;
- }
-
- return left.compareTo(right);
- }
- }
-
- private static class DescendingComparator implements Comparator<Comparable> {
- @Override
- public int compare(@Nullable Comparable left, @Nullable Comparable right) {
- if (left == null) {
- return 1;
- }
- if (right == null) {
- return -1;
- }
-
- return right.compareTo(left);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import javax.annotation.ParametersAreNonnullByDefault;
import org.sonar.server.issue.ws.IssueWsModule;
import org.sonar.server.language.ws.LanguageWs;
import org.sonar.server.license.ws.LicensesWsModule;
-import org.sonar.server.measure.MeasureFilterEngine;
-import org.sonar.server.measure.MeasureFilterExecutor;
-import org.sonar.server.measure.MeasureFilterFactory;
import org.sonar.server.measure.custom.ws.CustomMeasuresWsModule;
import org.sonar.server.measure.template.MyFavouritesFilter;
import org.sonar.server.measure.template.ProjectFilter;
org.sonar.server.language.ws.ListAction.class,
// measure
- MeasureFilterFactory.class,
- MeasureFilterExecutor.class,
- MeasureFilterEngine.class,
MetricsWsModule.class,
MeasuresWsModule.class,
CustomMeasuresWsModule.class,
import org.sonar.server.startup.DisplayLogOnDeprecatedProjects;
import org.sonar.server.startup.GeneratePluginIndex;
import org.sonar.server.startup.RegisterMetrics;
-import org.sonar.server.startup.RegisterNewMeasureFilters;
import org.sonar.server.startup.RegisterPermissionTemplates;
import org.sonar.server.startup.RenameDeprecatedPropertyKeys;
import org.sonar.server.user.DoPrivileged;
RegisterQualityGates.class,
RegisterRules.class,
RegisterQualityProfiles.class,
- RegisterNewMeasureFilters.class,
RegisterPermissionTemplates.class,
RenameDeprecatedPropertyKeys.class,
RegisterIssueFilters.class,
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.startup;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.utils.log.Logger;
-import org.sonar.api.utils.log.Loggers;
-import org.sonar.api.utils.log.Profiler;
-import org.sonar.api.web.Criterion;
-import org.sonar.api.web.Filter;
-import org.sonar.api.web.FilterColumn;
-import org.sonar.api.web.FilterTemplate;
-import org.sonar.db.measure.MeasureFilterDao;
-import org.sonar.db.measure.MeasureFilterDto;
-import org.sonar.db.loadedtemplate.LoadedTemplateDao;
-import org.sonar.db.loadedtemplate.LoadedTemplateDto;
-
-import java.util.Date;
-import java.util.List;
-
-/**
- * @since 3.1
- */
-public final class RegisterNewMeasureFilters {
- private static final Logger LOG = Loggers.get(RegisterNewMeasureFilters.class);
-
- private final List<FilterTemplate> filterTemplates;
- private final MeasureFilterDao filterDao;
- private final LoadedTemplateDao loadedTemplateDao;
-
- public RegisterNewMeasureFilters(FilterTemplate[] filterTemplates, MeasureFilterDao filterDao, LoadedTemplateDao loadedTemplateDao) {
- this.filterTemplates = ImmutableList.copyOf(filterTemplates);
- this.filterDao = filterDao;
- this.loadedTemplateDao = loadedTemplateDao;
- }
-
- /**
- * Used when no plugin is defining some FilterTemplate
- */
- public RegisterNewMeasureFilters(MeasureFilterDao filterDao, LoadedTemplateDao loadedTemplateDao) {
- this(new FilterTemplate[] {}, filterDao, loadedTemplateDao);
- }
-
- public void start() {
- Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register measure filters");
-
- for (FilterTemplate template : filterTemplates) {
- if (shouldRegister(template.getName())) {
- Filter filter = template.createFilter();
- register(template.getName(), filter);
- }
- }
-
- profiler.stopDebug();
- }
-
- private boolean shouldRegister(String filterName) {
- return loadedTemplateDao.countByTypeAndKey(LoadedTemplateDto.FILTER_TYPE, filterName) == 0;
- }
-
- @VisibleForTesting
- MeasureFilterDto register(String name, Filter filter) {
- MeasureFilterDto dto = null;
- if (filterDao.selectSystemFilterByName(name) == null) {
- LOG.info("Register measure filter: " + name);
- dto = createDtoFromExtension(name, filter);
- filterDao.insert(dto);
- }
- // and save the fact that is has now already been loaded
- loadedTemplateDao.insert(new LoadedTemplateDto(name, LoadedTemplateDto.FILTER_TYPE));
- return dto;
- }
-
- @VisibleForTesting
- MeasureFilterDto createDtoFromExtension(String name, Filter filter) {
- Date now = new Date();
- String data = toData(filter);
- return new MeasureFilterDto()
- .setName(name)
- .setShared(true)
- .setUserId(null)
- .setCreatedAt(now)
- .setUpdatedAt(now)
- .setData(data);
- }
-
- static String toData(Filter filter) {
- List<String> fields = Lists.newArrayList();
-
- fields.add("display=" + filter.getDisplayAs());
- if (filter.isFavouritesOnly()) {
- fields.add("onFavourites=true");
- }
- if (filter.getPageSize() > 0) {
- fields.add("pageSize=" + filter.getPageSize());
- }
- appendCriteria(filter, fields);
- appendColumns(filter, fields);
- return Joiner.on("|").join(fields);
- }
-
- private static void appendCriteria(Filter filter, List<String> fields) {
- int metricCriterionId = 1;
- for (Criterion criterion : filter.getCriteria()) {
- if ("qualifier".equals(criterion.getFamily())) {
- fields.add("qualifiers=" + criterion.getTextValue());
- } else if ("name".equals(criterion.getFamily())) {
- fields.add("nameSearch=" + criterion.getTextValue());
- } else if ("key".equals(criterion.getFamily())) {
- fields.add("keySearch=" + criterion.getTextValue());
- } else if ("language".equals(criterion.getFamily())) {
- fields.add("languages=" + criterion.getTextValue());
- } else if ("date".equals(criterion.getFamily())) {
- if ("<".equals(criterion.getOperator())) {
- fields.add("ageMaxDays=" + criterion.getValue());
- } else if (">".equals(criterion.getOperator())) {
- fields.add("ageMinDays=" + criterion.getValue());
- }
- } else if ("direct-children".equals(criterion.getFamily()) && "true".equals(criterion.getTextValue())) {
- fields.add("onBaseComponents=true");
- } else if ("metric".equals(criterion.getFamily()) && StringUtils.isNotBlank(criterion.getKey())
- && StringUtils.isNotBlank(criterion.getOperator()) && criterion.getValue() != null) {
- fields.add("c" + metricCriterionId + "_metric=" + criterion.getKey());
- fields.add("c" + metricCriterionId + "_op=" + criterion.getOperator());
- fields.add("c" + metricCriterionId + "_val=" + criterion.getValue());
- metricCriterionId += 1;
- }
- }
- }
-
- private static void appendColumns(Filter filter, List<String> fields) {
- List<String> columnFields = Lists.newArrayList();
- for (FilterColumn column : filter.getColumns()) {
- StringBuilder columnKey = new StringBuilder().append(column.getFamily());
- if (StringUtils.isNotBlank(column.getKey()) && !column.isVariation()) {
- columnKey.append(":").append(column.getKey());
- }
- columnFields.add(columnKey.toString());
- }
- if (!columnFields.isEmpty()) {
- fields.add("cols=" + Joiner.on(",").join(columnFields));
- }
- }
-}
import org.sonar.process.ProcessProperties;
import org.sonar.server.authentication.IdentityProviderRepository;
import org.sonar.server.component.ComponentCleanerService;
-import org.sonar.server.measure.MeasureFilterEngine;
-import org.sonar.server.measure.MeasureFilterResult;
import org.sonar.server.platform.PersistentSettings;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.db.migrations.DatabaseMigrator;
return getContainer().getComponentByType(componentType);
}
- public MeasureFilterResult executeMeasureFilter(Map<String, Object> map, @Nullable Long userId) {
- return get(MeasureFilterEngine.class).execute(map, userId);
- }
-
public Collection<ResourceType> getResourceTypesForFilter() {
return get(ResourceTypes.class).getAll(ResourceTypes.AVAILABLE_FOR_FILTERS);
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.measures.Metric;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MeasureFilterConditionTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void create_operator_from_code() {
- assertThat(MeasureFilterCondition.Operator.fromCode("eq")).isEqualTo(MeasureFilterCondition.Operator.EQUALS);
- assertThat(MeasureFilterCondition.Operator.fromCode("lte")).isEqualTo(MeasureFilterCondition.Operator.LESS_OR_EQUALS);
- }
-
- @Test
- public void fail_if_operator_code_not_found() {
- thrown.expect(IllegalArgumentException.class);
- MeasureFilterCondition.Operator.fromCode("xxx");
- }
-
- @Test
- public void operator_sql() {
- assertThat(MeasureFilterCondition.Operator.EQUALS.getSql()).isEqualTo("=");
- assertThat(MeasureFilterCondition.Operator.LESS_OR_EQUALS.getSql()).isEqualTo("<=");
- assertThat(MeasureFilterCondition.Operator.GREATER.getSql()).isEqualTo(">");
- }
-
- @Test
- public void value_condition() {
- Metric ncloc = new Metric.Builder("ncloc", "NCLOC", Metric.ValueType.INT).create();
- ncloc.setId(123);
- MeasureFilterCondition condition = new MeasureFilterCondition(ncloc, MeasureFilterCondition.Operator.GREATER, 10.0);
-
- assertThat(condition.metric()).isEqualTo(ncloc);
- assertThat(condition.operator()).isEqualTo(MeasureFilterCondition.Operator.GREATER);
- assertThat(condition.period()).isNull();
- assertThat(condition.value()).isEqualTo(10.0);
- assertThat(condition.textValue()).isNull();
- assertThat(condition.appendSqlColumn(new StringBuilder(), 1).toString()).isEqualTo("pmcond1.value");
- assertThat(condition.toString()).isNotEmpty();
- assertThat(condition.appendSqlCondition(new StringBuilder(), 1).toString()).isEqualTo(" pmcond1.metric_id=123 and pmcond1.value > 10.0 and pmcond1.person_id is null ");
- }
-
- @Test
- public void variation_condition() {
- Metric ncloc = new Metric.Builder("ncloc", "NCLOC", Metric.ValueType.INT).create();
- ncloc.setId(123);
- MeasureFilterCondition condition = new MeasureFilterCondition(ncloc, MeasureFilterCondition.Operator.LESS_OR_EQUALS, 10.0);
- condition.setPeriod(3);
-
- assertThat(condition.metric()).isEqualTo(ncloc);
- assertThat(condition.operator()).isEqualTo(MeasureFilterCondition.Operator.LESS_OR_EQUALS);
- assertThat(condition.period()).isEqualTo(3);
- assertThat(condition.value()).isEqualTo(10.0);
- assertThat(condition.appendSqlColumn(new StringBuilder(), 2).toString()).isEqualTo("pmcond2.variation_value_3");
- assertThat(condition.toString()).isNotEmpty();
- assertThat(condition.appendSqlCondition(new StringBuilder(), 2).toString())
- .isEqualTo(" pmcond2.metric_id=123 and pmcond2.variation_value_3 <= 10.0 and pmcond2.person_id is null ");
- }
-
- @Test
- public void text_value_condition() {
- Metric ncloc = new Metric.Builder("ncloc", "NCLOC", Metric.ValueType.INT).create();
- ncloc.setId(123);
- MeasureFilterCondition condition = new MeasureFilterCondition(ncloc, MeasureFilterCondition.Operator.EQUALS, "\"foo\"");
-
- assertThat(condition.metric()).isEqualTo(ncloc);
- assertThat(condition.operator()).isEqualTo(MeasureFilterCondition.Operator.EQUALS);
- assertThat(condition.period()).isNull();
- assertThat(condition.value()).isEqualTo(0);
- assertThat(condition.textValue()).isEqualTo("\"foo\"");
- assertThat(condition.appendSqlColumn(new StringBuilder(), 1).toString()).isEqualTo("pmcond1.text_value");
- assertThat(condition.toString()).isNotEmpty();
- assertThat(condition.appendSqlCondition(new StringBuilder(), 1).toString()).isEqualTo(" pmcond1.metric_id=123 and pmcond1.text_value = \"foo\" and pmcond1.person_id is null ");
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import org.junit.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MeasureFilterContextTest {
- @Test
- public void test_empty_toString() {
- MeasureFilterContext context = new MeasureFilterContext();
- assertThat(context.toString()).isNotEmpty();
- }
-
- @Test
- public void test_toString() {
- MeasureFilterContext context = new MeasureFilterContext();
- context.setData("{qualifiers=TRK}");
- context.setSql("SELECT *");
- context.setUserId(50L);
- assertThat(context.toString()).isEqualTo("MeasureFilterContext[filter={qualifiers=TRK},sql=SELECT *,user=50]");
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.collect.ImmutableMap;
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.*;
-
-public class MeasureFilterEngineTest {
-
- @Test
- public void should_create_and_execute_filter() throws Exception {
- Map<String, Object> filterMap = ImmutableMap.of("qualifiers", (Object) "TRK");
- MeasureFilterFactory factory = mock(MeasureFilterFactory.class);
- MeasureFilter filter = new MeasureFilter();
- when(factory.create(filterMap)).thenReturn(filter);
- MeasureFilterExecutor executor = mock(MeasureFilterExecutor.class);
-
- MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor);
-
- final long userId = 50L;
- engine.execute(filterMap, userId);
- verify(executor).execute(refEq(filter), argThat(new BaseMatcher<MeasureFilterContext>() {
- public boolean matches(Object o) {
- MeasureFilterContext context = (MeasureFilterContext) o;
- return "{qualifiers=TRK}".equals(context.getData()) && context.getUserId() == userId;
- }
-
- public void describeTo(Description description) {
- }
- }));
- }
-
- @Test
- public void keep_error_but_do_not_fail() {
- Map<String, Object> filterMap = ImmutableMap.of("qualifiers", (Object) "TRK");
- MeasureFilterFactory factory = mock(MeasureFilterFactory.class);
- when(factory.create(filterMap)).thenThrow(new IllegalArgumentException());
- MeasureFilterExecutor executor = mock(MeasureFilterExecutor.class);
-
- MeasureFilterEngine engine = new MeasureFilterEngine(factory, executor);
- MeasureFilterResult result = engine.execute(filterMap, 50L);
-
- assertThat(result.isSuccess()).isFalse();
- assertThat(result.getError()).isEqualTo(MeasureFilterResult.Error.UNKNOWN);
- assertThat(result.getRows()).isNull();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import java.sql.SQLException;
-import java.util.Date;
-import java.util.List;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbTester;
-import org.sonar.db.component.ComponentDao;
-import org.sonar.db.component.ComponentDto;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-
-
-public class MeasureFilterExecutorTest {
-
- private static final String JAVA_PROJECT_UUID = "UUID_JAVA_PROJECT";
- private static final String JAVA_BIG_FILE_UUID = "UUID_JAVA_BIG_FILE";
- private static final String JAVA_TINY_FILE_UUID = "UUID_JAVA_TINY_FILE";
- private static final String JAVA_DIR_UUID = "UUID_JAVA_DIR";
- private static final String PHP_PROJECT_UUID = "UUID_PHP_PROJECT";
- private static final Metric METRIC_LINES = new Metric.Builder("lines", "Lines", Metric.ValueType.INT).create().setId(1);
- private static final Metric METRIC_PROFILE = new Metric.Builder("profile", "Profile", Metric.ValueType.STRING).create().setId(2);
- private static final Metric METRIC_COVERAGE = new Metric.Builder("coverage", "Coverage", Metric.ValueType.FLOAT).create().setId(3);
- private static final Metric METRIC_UNKNOWN = new Metric.Builder("unknown", "Unknown", Metric.ValueType.FLOAT).create().setId(4);
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
- private MeasureFilterExecutor executor;
-
- @Before
- public void before() {
- executor = new MeasureFilterExecutor(db.myBatis(), db.database(), new ComponentDao());
- }
-
- @Test
- public void should_return_empty_results_if_empty_filter() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter();
- assertThat(filter.isEmpty()).isTrue();
-
- assertThat(executor.execute(filter, new MeasureFilterContext())).isEmpty();
- }
-
- @Test
- public void invalid_filter_should_not_return_results() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setUserFavourites(true);
- // anonymous user does not have favourites
- assertThat(executor.execute(filter, new MeasureFilterContext())).isEmpty();
- }
-
- @Test
- public void filter_is_not_valid_if_missing_base_component() {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilterContext context = new MeasureFilterContext();
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setOnBaseResourceChildren(true);
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isFalse();
-
- context.setBaseComponent(new ComponentDto().setId(123L));
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isTrue();
- }
-
- @Test
- public void filter_is_not_valid_if_condition_on_unknown_metric() {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilterContext context = new MeasureFilterContext();
- MeasureFilter filter = new MeasureFilter().addCondition(new MeasureFilterCondition(null, MeasureFilterCondition.Operator.LESS, 3.0));
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isFalse();
- }
-
- @Test
- public void filter_is_not_valid_if_sorting_on_unknown_metric() {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilterContext context = new MeasureFilterContext();
- MeasureFilter filter = new MeasureFilter().setSortOnMetric(null);
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isFalse();
- }
-
- @Test
- public void filter_is_not_valid_if_anonymous_favourites() {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilterContext context = new MeasureFilterContext();
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setUserFavourites(true);
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isFalse();
-
- context.setUserId(123L);
- assertThat(MeasureFilterExecutor.isValid(filter, context)).isTrue();
- }
-
- @Test
- public void projects_without_measure_conditions() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOn(MeasureFilterSort.Field.DATE);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));
- verifyPhpProject(rows.get(1));
- }
-
- @Test
- public void should_prevent_sql_injection_through_parameters() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter()
- .setResourceQualifiers(asList("'"))
- .setBaseResourceKey("'")
- .setResourceKey("'")
- .setResourceName("'")
- .setResourceName("'")
- .setResourceScopes(asList("'"));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
- // an exception would be thrown if SQL is not valid
- assertThat(rows).isEmpty();
- }
-
- @Test
- public void test_default_sort() {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL"));
-
- assertThat(filter.sort().isAsc()).isTrue();
- assertThat(filter.sort().field()).isEqualTo(MeasureFilterSort.Field.NAME);
- assertThat(filter.sort().metric()).isNull();
- }
-
- @Test
- public void sort_by_ascending_resource_name() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortAsc(true);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Big -> Tiny
- assertThat(rows).hasSize(2);
- verifyJavaBigFile(rows.get(0));
- verifyJavaTinyFile(rows.get(1));
- }
-
- @Test
- public void sort_by_ascending_resource_key() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortAsc(true).setSortOn(MeasureFilterSort.Field.KEY);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Big -> Tiny
- assertThat(rows).hasSize(2);
- verifyJavaBigFile(rows.get(0));
- verifyJavaTinyFile(rows.get(1));
- }
-
- @Test
- public void sort_by_ascending_resource_version() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortAsc(true).setSortOn(MeasureFilterSort.Field.VERSION);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Java Project 1.0 then Php Project 3.0
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));
- verifyPhpProject(rows.get(1));
- }
-
- @Test
- public void sort_by_descending_resource_name() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Tiny -> Big
- assertThat(rows).hasSize(2);
- verifyJavaTinyFile(rows.get(0));
- verifyJavaBigFile(rows.get(1));
- }
-
- @Test
- public void sort_by_ascending_text_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(METRIC_PROFILE);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- verifyPhpProject(rows.get(0));// php way
- verifyJavaProject(rows.get(1));// Sonar way
- }
-
- @Test
- public void sort_by_descending_text_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(METRIC_PROFILE).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));// Sonar way
- verifyPhpProject(rows.get(1));// php way
- }
-
- @Test
- public void sort_by_missing_text_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- // the metric 'profile' is not set on files
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortOnMetric(METRIC_PROFILE);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);// 2 files randomly sorted
- }
-
- @Test
- public void sort_by_ascending_numeric_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortOnMetric(METRIC_LINES);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Tiny -> Big
- assertThat(rows).hasSize(2);
- verifyJavaTinyFile(rows.get(0));
- verifyJavaBigFile(rows.get(1));
- }
-
- @Test
- public void sort_by_descending_numeric_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortOnMetric(METRIC_LINES).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Big -> Tiny
- assertThat(rows).hasSize(2);
- verifyJavaBigFile(rows.get(0));
- verifyJavaTinyFile(rows.get(1));
- }
-
- @Test
- public void null_measures_are_ordered_after_descending_numeric_measures() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK"))
- .setSortOnMetric(METRIC_COVERAGE).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Java project has coverage but not PHP
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));
- verifyPhpProject(rows.get(1));
- }
-
- @Test
- public void null_measures_are_ordered_after_ascending_numeric_measures() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK"))
- .setSortOnMetric(METRIC_COVERAGE).setSortAsc(true);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Java project has coverage but not PHP
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));
- verifyPhpProject(rows.get(1));
- }
-
- @Test
- public void sort_by_missing_numeric_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- // coverage measures are not computed
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setSortOnMetric(METRIC_UNKNOWN);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // 2 files, random order
- assertThat(rows).hasSize(2);
- }
-
- @Test
- public void sort_by_ascending_variation() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(METRIC_LINES).setSortOnPeriod(5);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- verifyJavaProject(rows.get(0));// +400
- verifyPhpProject(rows.get(1));// +4900
- }
-
- @Test
- public void sort_by_descending_variation() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK"))
- .setSortOnMetric(METRIC_LINES).setSortOnPeriod(5).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- verifyPhpProject(rows.get(0));// +4900
- verifyJavaProject(rows.get(1));// +400
- }
-
- @Test
- public void sort_by_ascending_date() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOn(MeasureFilterSort.Field.DATE);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- verifyJavaProject(rows.get(0));// 2008
- verifyPhpProject(rows.get(1));// 2012
- }
-
- @Test
- public void sort_by_descending_date() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOn(MeasureFilterSort.Field.DATE).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- verifyPhpProject(rows.get(0));// 2012
- verifyJavaProject(rows.get(1));// 2008
- }
-
- @Test
- public void sort_by_ascending_created_at() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOn(MeasureFilterSort.Field.PROJECT_CREATION_DATE);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- verifyJavaProject(rows.get(0));// 2008
- assertThat(DateUtils.formatDate(new Date(rows.get(0).getSortDate()))).isEqualTo("2008-12-19");
- verifyPhpProject(rows.get(1));// 2012
- assertThat(DateUtils.formatDate(new Date(rows.get(1).getSortDate()))).isEqualTo("2012-12-12");
- }
-
- @Test
- public void sort_by_descending_created_at() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOn(MeasureFilterSort.Field.PROJECT_CREATION_DATE).setSortAsc(false);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- verifyPhpProject(rows.get(0));// 2012
- assertThat(DateUtils.formatDate(new Date(rows.get(0).getSortDate()))).isEqualTo("2012-12-12");
- verifyJavaProject(rows.get(1));// 2008
- assertThat(DateUtils.formatDate(new Date(rows.get(1).getSortDate()))).isEqualTo("2008-12-19");
- }
-
- @Test
- public void sort_by_ascending_quality_gate_status() throws SQLException {
- db.prepareDbUnit(getClass(), "sort_by_alert.xml");
- Metric alert = new Metric.Builder(CoreMetrics.ALERT_STATUS_KEY, "Alert", Metric.ValueType.LEVEL).create().setId(5);
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(alert);
-
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Php Project OK, Java Project WARN then Js Project ERROR
- assertThat(rows).hasSize(3);
- verifyPhpProject(rows.get(0));
- verifyJavaProject(rows.get(1));
- verifyComponent(rows.get(2), "UUID_JS_PROJECT", "UUID_JS_PROJECT");
- }
-
- @Test
- public void sort_by_descending_quality_gate_status() throws SQLException {
- db.prepareDbUnit(getClass(), "sort_by_alert.xml");
- Metric alert = new Metric.Builder(CoreMetrics.ALERT_STATUS_KEY, "Alert", Metric.ValueType.LEVEL).create().setId(5);
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(alert).setSortAsc(false);
-
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // Js Project ERROR, Java Project WARN, then Php Project OK
- assertThat(rows).hasSize(3);
- verifyComponent(rows.get(0), "UUID_JS_PROJECT", "UUID_JS_PROJECT");
- verifyJavaProject(rows.get(1));
- verifyPhpProject(rows.get(2));
- }
-
- @Test
- public void condition_on_numeric_measure() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL"))
- .setSortOnMetric(METRIC_LINES)
- .addCondition(new MeasureFilterCondition(METRIC_LINES, MeasureFilterCondition.Operator.GREATER, 200));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyJavaBigFile(rows.get(0));
- }
-
- @Test
- public void condition_on_measure_variation() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK"))
- .setSortOnMetric(METRIC_LINES)
- .addCondition(new MeasureFilterCondition(METRIC_LINES, MeasureFilterCondition.Operator.GREATER, 1000).setPeriod(5));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyPhpProject(rows.get(0));
- }
-
- @Test
- public void multiple_conditions_on_numeric_measures() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL"))
- .setSortOnMetric(METRIC_LINES)
- .addCondition(new MeasureFilterCondition(METRIC_LINES, MeasureFilterCondition.Operator.GREATER, 2))
- .addCondition(new MeasureFilterCondition(METRIC_LINES, MeasureFilterCondition.Operator.LESS_OR_EQUALS, 50));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyJavaTinyFile(rows.get(0));
- }
-
- @Test
- public void filter_by_min_date() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setFromDate(DateUtils.parseDateTime("2012-12-13T00:00:00+0000"));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // php has been analyzed in 2012-12-13, whereas java project has been analyzed in 2008
- assertThat(rows).hasSize(1);
- verifyPhpProject(rows.get(0));
- }
-
- @Test
- public void filter_by_range_of_dates() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK"))
- .setFromDate(DateUtils.parseDate("2007-01-01"))
- .setToDate(DateUtils.parseDate("2010-01-01"));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- // php has been analyzed in 2012-12-13, whereas java project has been analyzed in 2008
- assertThat(rows).hasSize(1);
- verifyJavaProject(rows.get(0));
- }
-
- @Test
- public void filter_by_component_name() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setResourceName("PHP Proj");
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyPhpProject(rows.get(0));
- }
-
- @Test
- public void filter_by_component_key() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setResourceKey("Va_proje");
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyJavaProject(rows.get(0));
- }
-
- /**
- * see SONAR-4195
- */
- @Test
- public void filter_by_upper_case_component_key() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setResourceKey("big");
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(1);
- verifyJavaBigFile(rows.get(0));
- }
-
- /**
- * see SONAR-4796
- */
- @Test
- public void escape_percent_and_underscore_when_filter_by_component_name_or_key() throws SQLException {
- db.prepareDbUnit(getClass(), "escape_percent_and_underscore_when_filter_by_component_name_or_key.xml");
-
- assertThat(executor.execute(
- new MeasureFilter().setResourceQualifiers(newArrayList("FIL")).setResourceName("java%"),
- new MeasureFilterContext())).hasSize(2);
- }
-
- @Test
- public void filter_by_base_component() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("FIL")).setBaseResourceKey("java_project");
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).hasSize(2);
- // default sort is on resource name
- verifyJavaBigFile(rows.get(0));
- verifyJavaTinyFile(rows.get(1));
- }
-
- @Test
- public void filter_by_parent_component() throws SQLException {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setBaseResourceKey("java_project").setOnBaseResourceChildren(true);
-
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).extracting(MeasureFilterRow::getComponentUuid).containsOnly(JAVA_DIR_UUID);
- }
-
- @Test
- public void filter_by_parent_without_children() throws Exception {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK", "DIR", "FIL")).setBaseResourceKey("java_project:org.sonar.foo.Big")
- .setOnBaseResourceChildren(true);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext());
-
- assertThat(rows).isEmpty();
- }
-
- @Test
- public void filter_by_user_favourites() throws Exception {
- db.prepareDbUnit(getClass(), "shared.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK", "FIL")).setUserFavourites(true);
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext().setUserId(50L));
-
- assertThat(rows).hasSize(2);
- verifyJavaBigFile(rows.get(0));
- verifyPhpProject(rows.get(1));
- }
-
- @Test
- public void ignore_person_measures_in_condition() throws Exception {
- db.prepareDbUnit(getClass(), "ignore_person_measures.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).addCondition(
- new MeasureFilterCondition(new Metric("ncloc").setId(1), MeasureFilterCondition.Operator.GREATER, 0.0)
- );
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext().setUserId(50L));
-
- assertThat(rows).hasSize(1);
- assertThat(rows.get(0).getComponentUuid()).isEqualTo(JAVA_PROJECT_UUID);
- }
-
- @Test
- public void ignore_person_measures_in_sort() throws Exception {
- db.prepareDbUnit(getClass(), "ignore_person_measures.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(new Metric("ncloc").setId(1));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext().setUserId(50L));
-
- assertThat(rows).hasSize(1);
- assertThat(rows.get(0).getComponentUuid()).isEqualTo(JAVA_PROJECT_UUID);
- }
-
- @Test
- public void ignore_quality_model_measures_in_condition() throws Exception {
- db.prepareDbUnit(getClass(), "ignore_quality_model_measures.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).addCondition(
- new MeasureFilterCondition(new Metric("ncloc").setId(1), MeasureFilterCondition.Operator.GREATER, 0.0)
- );
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext().setUserId(50L));
-
- assertThat(rows).hasSize(1);
- assertThat(rows.get(0).getComponentUuid()).isEqualTo(JAVA_PROJECT_UUID);
- }
-
- @Test
- public void ignore_quality_model_measures_in_sort() throws Exception {
- db.prepareDbUnit(getClass(), "ignore_quality_model_measures.xml");
- MeasureFilter filter = new MeasureFilter().setResourceQualifiers(asList("TRK")).setSortOnMetric(new Metric("ncloc").setId(1));
- List<MeasureFilterRow> rows = executor.execute(filter, new MeasureFilterContext().setUserId(50L));
-
- assertThat(rows).hasSize(1);
- assertThat(rows.get(0).getComponentUuid()).isEqualTo(JAVA_PROJECT_UUID);
- }
-
- private void verifyJavaProject(MeasureFilterRow row) {
- verifyComponent(row, JAVA_PROJECT_UUID, JAVA_PROJECT_UUID);
- }
-
- private void verifyJavaBigFile(MeasureFilterRow row) {
- verifyComponent(row, JAVA_BIG_FILE_UUID, JAVA_PROJECT_UUID);
- }
-
- private void verifyJavaTinyFile(MeasureFilterRow row) {
- verifyComponent(row, JAVA_TINY_FILE_UUID, JAVA_PROJECT_UUID);
- }
-
- private void verifyPhpProject(MeasureFilterRow row) {
- verifyComponent(row, PHP_PROJECT_UUID, PHP_PROJECT_UUID);
- }
-
- private void verifyComponent(MeasureFilterRow row, String componentUuid, String rootComponentUuid) {
- assertThat(row.getComponentUuid()).isEqualTo(componentUuid);
- assertThat(row.getRootComponentUuid()).isEqualTo(rootComponentUuid);
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
-import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.api.utils.System2;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class MeasureFilterFactoryTest {
-
- System2 system = mock(System2.class);
-
- @Test
- public void sort_on_measure_value() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of("sort", "metric:ncloc");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("pmsort.value");
- assertThat(filter.sort().metric().getKey()).isEqualTo("ncloc");
- assertThat(filter.sort().period()).isNull();
- }
-
- @Test
- public void sort_on_measure_variation() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of("sort", "metric:ncloc:3");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("pmsort.variation_value_3");
- assertThat(filter.sort().metric().getKey()).isEqualTo("ncloc");
- assertThat(filter.sort().period()).isEqualTo(3);
- }
-
- @Test
- public void sort_on_name() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of("sort", "name");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("c.long_name");
- assertThat(filter.sort().metric()).isNull();
- assertThat(filter.sort().period()).isNull();
- }
-
- @Test
- public void fallback_on_name_sort_when_metric_is_unknown() {
- MetricFinder finder = mock(MetricFinder.class);
- when(finder.findByKey(anyString())).thenReturn(null);
- MeasureFilterFactory factory = new MeasureFilterFactory(finder, system);
- Map<String, Object> props = ImmutableMap.of("sort", "metric:sqale_index");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("c.long_name");
- assertThat(filter.sort().metric()).isNull();
- assertThat(filter.sort().period()).isNull();
- assertThat(filter.sort().isAsc()).isTrue();
- }
-
- @Test
- public void fallback_on_name_sort_when_sort_is_unknown() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of("sort", "unknown");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("c.long_name");
- assertThat(filter.sort().metric()).isNull();
- assertThat(filter.sort().period()).isNull();
- assertThat(filter.sort().isAsc()).isTrue();
- }
-
- @Test
- public void descending_sort() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of("asc", "false");
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("c.long_name");
- assertThat(filter.sort().metric()).isNull();
- assertThat(filter.sort().period()).isNull();
- assertThat(filter.sort().isAsc()).isFalse();
- }
-
- @Test
- public void ascending_sort_by_default() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = Maps.newHashMap();
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.sort().column()).isEqualTo("c.long_name");
- assertThat(filter.sort().metric()).isNull();
- assertThat(filter.sort().period()).isNull();
- assertThat(filter.sort().isAsc()).isTrue();
- }
-
- @Test
- public void date_conditions() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "fromDate", "2012-01-25",
- "toDate", "2012-02-18"
- );
- MeasureFilter filter = factory.create(props);
-
- assertThat(DateUtils.formatDate(filter.getFromDate())).isEqualTo("2012-01-25");
- assertThat(DateUtils.formatDate(filter.getToDate())).isEqualTo("2012-02-18");
- }
-
- @Test
- public void age_conditions() {
- long today = DateUtils.parseDateTime("2013-05-18T11:00:00+0000").getTime();
- when(system.now()).thenReturn(today);
-
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "ageMaxDays", "3",
- "ageMinDays", "1"
- );
- MeasureFilter filter = factory.create(props);
- assertThat(DateUtils.formatDate(filter.getFromDate())).isEqualTo("2013-05-15");
- assertThat(DateUtils.formatDate(filter.getToDate())).isEqualTo("2013-05-17");
- }
-
- @Test
- public void measure_value_condition() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "c1_metric", "complexity",
- "c1_op", "gte",
- "c1_val", "3.14"
- );
- MeasureFilter filter = factory.create(props);
-
- List<MeasureFilterCondition> conditions = filter.getMeasureConditions();
- assertThat(conditions).hasSize(1);
- assertThat(conditions.get(0).metric().getKey()).isEqualTo("complexity");
- assertThat(conditions.get(0).operator()).isEqualTo(MeasureFilterCondition.Operator.GREATER_OR_EQUALS);
- assertThat(conditions.get(0).value()).isEqualTo(3.14);
- assertThat(conditions.get(0).period()).isNull();
- }
-
- @Test
- public void measure_variation_condition() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "c1_metric", "complexity",
- "c1_op", "gte",
- "c1_val", "3.14",
- "c1_period", "3"
- );
- MeasureFilter filter = factory.create(props);
-
- List<MeasureFilterCondition> conditions = filter.getMeasureConditions();
- assertThat(conditions).hasSize(1);
- assertThat(conditions.get(0).metric().getKey()).isEqualTo("complexity");
- assertThat(conditions.get(0).operator()).isEqualTo(MeasureFilterCondition.Operator.GREATER_OR_EQUALS);
- assertThat(conditions.get(0).value()).isEqualTo(3.14);
- assertThat(conditions.get(0).period()).isEqualTo(3);
- }
-
- @Test
- public void alert_level_condition() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- MeasureFilter filter = factory.create(ImmutableMap.of(
- "alertLevels", Arrays.asList("error", "warn", "unknown")
- ));
-
- List<MeasureFilterCondition> conditions = filter.getMeasureConditions();
- assertThat(conditions).hasSize(1);
- assertThat(conditions.get(0).metric().getKey()).isEqualTo("alert_status");
- assertThat(conditions.get(0).operator()).isEqualTo(MeasureFilterCondition.Operator.IN);
- assertThat(conditions.get(0).value()).isEqualTo(0);
- assertThat(conditions.get(0).textValue()).isEqualTo("('ERROR', 'WARN')");
- assertThat(conditions.get(0).period()).isNull();
- }
-
- @Test
- public void alert_level_condition_with_no_alert_status_metric() {
- MeasureFilterFactory factory = new MeasureFilterFactory(mock(MetricFinder.class), system);
- MeasureFilter filter = factory.create(ImmutableMap.of(
- "alertLevels", Arrays.asList("error", "warn", "unknown")
- ));
-
- List<MeasureFilterCondition> conditions = filter.getMeasureConditions();
- assertThat(conditions).isEmpty();
- }
-
- @Test
- public void name_conditions() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "nameSearch", "SonarQube"
- );
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.getResourceName()).isEqualTo("SonarQube");
- }
-
- @Test
- public void not_fail_when_name_conditions_contains_array() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "nameSearch", new String[] {"sonar", "qube"}
- );
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.getResourceName()).isEqualTo("sonar,qube");
- }
-
- @Test
- public void not_fail_when_name_conditions_contains_list() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "nameSearch", newArrayList("sonar", "qube")
- );
- MeasureFilter filter = factory.create(props);
-
- assertThat(filter.getResourceName()).isEqualTo("sonar,qube");
- }
-
- @Test
- public void ignore_partial_measure_condition() {
- MeasureFilterFactory factory = new MeasureFilterFactory(newMetricFinder(), system);
- Map<String, Object> props = ImmutableMap.of(
- "c1_op", "gte",
- "c1_val", "3.14"
- );
- MeasureFilter filter = factory.create(props);
-
- List<MeasureFilterCondition> conditions = filter.getMeasureConditions();
- assertThat(conditions).isEmpty();
- }
-
- private MetricFinder newMetricFinder() {
- MetricFinder finder = mock(MetricFinder.class);
- when(finder.findByKey(anyString())).thenAnswer(new Answer<Metric>() {
- public Metric answer(InvocationOnMock invocationOnMock) throws Throwable {
- String key = (String) invocationOnMock.getArguments()[0];
- return new Metric.Builder(key, key, Metric.ValueType.INT).create();
- }
- });
- return finder;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-import com.google.common.collect.Lists;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Collections;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MeasureFilterTest {
- @Test
- public void should_sanitize_list() {
- assertThat(MeasureFilter.sanitize(null)).isEmpty();
- assertThat(MeasureFilter.sanitize(Lists.<String>newArrayList())).isEmpty();
- assertThat(MeasureFilter.sanitize(Arrays.asList(""))).isEmpty();
- assertThat(MeasureFilter.sanitize(Lists.newArrayList("TRK"))).containsExactly("TRK");
- assertThat(MeasureFilter.sanitize(Lists.newArrayList("TRK", "BRC"))).containsExactly("TRK", "BRC");
- }
-
- @Test
- public void filter_is_not_empty_if_at_least_condition_on_favourites() {
- assertThat(new MeasureFilter().isEmpty()).isTrue();
- assertThat(new MeasureFilter().setUserFavourites(true).isEmpty()).isFalse();
- }
-
- @Test
- public void filter_is_not_empty_if_at_least_condition_on_qualifiers() {
- assertThat(new MeasureFilter().isEmpty()).isTrue();
- assertThat(new MeasureFilter().setResourceQualifiers(Collections.<String>emptyList()).isEmpty()).isTrue();
- assertThat(new MeasureFilter().setResourceQualifiers(Arrays.asList("TRK")).isEmpty()).isFalse();
- }
-
- @Test
- public void filter_is_not_empty_if_at_least_condition_on_scopes() {
- assertThat(new MeasureFilter().isEmpty()).isTrue();
- assertThat(new MeasureFilter().setResourceScopes(Collections.<String>emptyList()).isEmpty()).isTrue();
- assertThat(new MeasureFilter().setResourceScopes(Arrays.asList("PRJ")).isEmpty()).isFalse();
- }
-
- @Test
- public void filter_is_not_empty_if_at_least_condition_on_root_resource() {
- assertThat(new MeasureFilter().isEmpty()).isTrue();
- assertThat(new MeasureFilter().setBaseResourceKey("foo").isEmpty()).isFalse();
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.startup;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.web.Criterion;
-import org.sonar.api.web.Filter;
-import org.sonar.api.web.FilterColumn;
-import org.sonar.api.web.FilterTemplate;
-import org.sonar.db.measure.MeasureFilterDao;
-import org.sonar.db.measure.MeasureFilterDto;
-import org.sonar.db.loadedtemplate.LoadedTemplateDao;
-import org.sonar.db.loadedtemplate.LoadedTemplateDto;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.*;
-
-public class RegisterNewMeasureFiltersTest {
- private RegisterNewMeasureFilters registration;
- private MeasureFilterDao filterDao;
- private LoadedTemplateDao loadedTemplateDao;
- private FilterTemplate filterTemplate;
-
- @Before
- public void init() {
- filterDao = mock(MeasureFilterDao.class);
- loadedTemplateDao = mock(LoadedTemplateDao.class);
- filterTemplate = mock(FilterTemplate.class);
-
- registration = new RegisterNewMeasureFilters(new FilterTemplate[]{filterTemplate}, filterDao, loadedTemplateDao);
- }
-
- @Test
- public void should_insert_filters_on_start() {
- when(loadedTemplateDao.countByTypeAndKey(eq(LoadedTemplateDto.FILTER_TYPE), anyString())).thenReturn(0);
- when(filterTemplate.createFilter()).thenReturn(Filter.create());
-
- registration.start();
-
- verify(filterDao).insert(any(MeasureFilterDto.class));
- verify(loadedTemplateDao).insert(any(LoadedTemplateDto.class));
- }
-
- @Test
- public void should_insert_nothing_if_templates_are_alreday_loaded() {
- when(loadedTemplateDao.countByTypeAndKey(eq(LoadedTemplateDto.FILTER_TYPE), anyString())).thenReturn(1);
-
- registration.start();
-
- verify(filterDao, never()).insert(any(MeasureFilterDto.class));
- verify(loadedTemplateDao, never()).insert(any(LoadedTemplateDto.class));
- }
-
- @Test
- public void should_register_filter() {
- when(filterTemplate.createFilter()).thenReturn(Filter.create());
-
- MeasureFilterDto filterDto = registration.register("Fake", filterTemplate.createFilter());
-
- assertThat(filterDto).isNotNull();
- verify(filterDao).insert(filterDto);
- verify(loadedTemplateDao).insert(eq(new LoadedTemplateDto("Fake", LoadedTemplateDto.FILTER_TYPE)));
- }
-
- @Test
- public void should_not_recreate_filter() {
- when(filterDao.selectSystemFilterByName("Fake")).thenReturn(new MeasureFilterDto());
-
- MeasureFilterDto filterDto = registration.register("Fake", null);
-
- assertThat(filterDto).isNull();
- verify(filterDao, never()).insert(filterDto);
- verify(loadedTemplateDao).insert(eq(new LoadedTemplateDto("Fake", LoadedTemplateDto.FILTER_TYPE)));
- }
-
- @Test
- public void should_create_dto_from_extension() {
- when(filterTemplate.createFilter()).thenReturn(Filter.create()
- .setFavouritesOnly(false)
- .setDisplayAs("list")
- .add(Criterion.createForMetric("complexity", Criterion.LT, 12f, false))
- .add(Criterion.createForMetric("lcom4", Criterion.GTE, 5f, false))
- .add(FilterColumn.create("metric", "distance", "ASC", false))
- );
-
- MeasureFilterDto dto = registration.createDtoFromExtension("Fake", filterTemplate.createFilter());
-
- assertThat(dto.getName()).isEqualTo("Fake");
- assertThat(dto.isShared()).isTrue();
- assertThat(dto.getData()).doesNotContain("onFavourites=true");
- assertThat(dto.getData()).contains("display=list");
- assertThat(dto.getData()).contains("c1_metric=complexity");
- assertThat(dto.getData()).contains("c1_op=lt");
- assertThat(dto.getData()).contains("c1_val=12.0");
- assertThat(dto.getData()).contains("c2_metric=lcom4");
- assertThat(dto.getData()).contains("c2_op=gte");
- assertThat(dto.getData()).contains("c2_val=5.0");
- assertThat(dto.getData()).contains("cols=metric:distance");
- }
-}
import org.sonar.db.issue.IssueFilterFavouriteDao;
import org.sonar.db.loadedtemplate.LoadedTemplateDao;
import org.sonar.db.measure.MeasureDao;
-import org.sonar.db.measure.MeasureFilterDao;
-import org.sonar.db.measure.MeasureFilterFavouriteDao;
import org.sonar.db.measure.custom.CustomMeasureDao;
import org.sonar.db.metric.MetricDao;
import org.sonar.db.notification.NotificationQueueDao;
IssueFilterFavouriteDao.class,
LoadedTemplateDao.class,
MeasureDao.class,
- MeasureFilterDao.class,
- MeasureFilterFavouriteDao.class,
MetricDao.class,
NotificationQueueDao.class,
OrganizationDao.class,
import org.sonar.db.issue.IssueFilterFavouriteDao;
import org.sonar.db.loadedtemplate.LoadedTemplateDao;
import org.sonar.db.measure.MeasureDao;
-import org.sonar.db.measure.MeasureFilterDao;
-import org.sonar.db.measure.MeasureFilterFavouriteDao;
import org.sonar.db.measure.custom.CustomMeasureDao;
import org.sonar.db.metric.MetricDao;
import org.sonar.db.notification.NotificationQueueDao;
private final ResourceDao resourceDao;
private final ComponentKeyUpdaterDao componentKeyUpdaterDao;
private final MeasureDao measureDao;
- private final MeasureFilterDao measureFilterDao;
- private final MeasureFilterFavouriteDao measureFilterFavouriteDao;
private final UserDao userDao;
private final UserGroupDao userGroupDao;
private final UserTokenDao userTokenDao;
resourceDao = getDao(map, ResourceDao.class);
componentKeyUpdaterDao = getDao(map, ComponentKeyUpdaterDao.class);
measureDao = getDao(map, MeasureDao.class);
- measureFilterDao = getDao(map, MeasureFilterDao.class);
- measureFilterFavouriteDao = getDao(map, MeasureFilterFavouriteDao.class);
userDao = getDao(map, UserDao.class);
userGroupDao = getDao(map, UserGroupDao.class);
userTokenDao = getDao(map, UserTokenDao.class);
return measureDao;
}
- public MeasureFilterDao measureFilterDao() {
- return measureFilterDao;
- }
-
- public MeasureFilterFavouriteDao measureFilterFavouriteDao() {
- return measureFilterFavouriteDao;
- }
-
public UserDao userDao() {
return userDao;
}
import org.sonar.db.loadedtemplate.LoadedTemplateDto;
import org.sonar.db.loadedtemplate.LoadedTemplateMapper;
import org.sonar.db.measure.MeasureDto;
-import org.sonar.db.measure.MeasureFilterDto;
-import org.sonar.db.measure.MeasureFilterFavouriteDto;
-import org.sonar.db.measure.MeasureFilterFavouriteMapper;
-import org.sonar.db.measure.MeasureFilterMapper;
import org.sonar.db.measure.MeasureMapper;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.measure.custom.CustomMeasureMapper;
confBuilder.loadAlias("IssueFilter", IssueFilterDto.class);
confBuilder.loadAlias("Issue", IssueDto.class);
confBuilder.loadAlias("LoadedTemplate", LoadedTemplateDto.class);
- confBuilder.loadAlias("MeasureFilterFavourite", MeasureFilterFavouriteDto.class);
- confBuilder.loadAlias("MeasureFilter", MeasureFilterDto.class);
confBuilder.loadAlias("Measure", MeasureDto.class);
confBuilder.loadAlias("NotificationQueue", NotificationQueueDto.class);
confBuilder.loadAlias("Organization", OrganizationDto.class);
IssueFilterMapper.class,
IssueMapper.class,
LoadedTemplateMapper.class,
- MeasureFilterFavouriteMapper.class,
- MeasureFilterMapper.class,
MeasureMapper.class,
MetricMapper.class,
Migration45Mapper.class,
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import org.apache.ibatis.session.SqlSession;
-import org.sonar.db.Dao;
-import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
-
-public class MeasureFilterDao implements Dao {
- private MyBatis mybatis;
-
- public MeasureFilterDao(MyBatis mybatis) {
- this.mybatis = mybatis;
- }
-
- public MeasureFilterDto selectSystemFilterByName(String name) {
- SqlSession session = mybatis.openSession(false);
- try {
- MeasureFilterMapper mapper = session.getMapper(MeasureFilterMapper.class);
- return mapper.findSystemFilterByName(name);
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- public MeasureFilterDto selectById(DbSession session, long id){
- return session.getMapper(MeasureFilterMapper.class).selectById(id);
- }
-
- public void insert(DbSession session, MeasureFilterDto filter) {
- session.getMapper(MeasureFilterMapper.class).insert(filter);
- }
-
- public void insert(MeasureFilterDto filter) {
- DbSession session = mybatis.openSession(false);
- try {
- insert(session, filter);
- session.commit();
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import java.util.Date;
-import javax.annotation.Nullable;
-
-/**
- * @since 3.4
- */
-public class MeasureFilterDto {
- private Long id;
- private String name;
- private Long userId;
- private Boolean shared;
- private String description;
- private String data;
- private Date createdAt;
- private Date updatedAt;
-
- public Long getId() {
- return id;
- }
-
- public MeasureFilterDto setId(Long id) {
- this.id = id;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- public MeasureFilterDto setName(String name) {
- this.name = name;
- return this;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public MeasureFilterDto setUserId(@Nullable Long userId) {
- this.userId = userId;
- return this;
- }
-
- public Boolean isShared() {
- return shared;
- }
-
- public MeasureFilterDto setShared(@Nullable Boolean shared) {
- this.shared = shared;
- return this;
- }
-
- public String getDescription() {
- return description;
- }
-
- public MeasureFilterDto setDescription(@Nullable String description) {
- this.description = description;
- return this;
- }
-
- public String getData() {
- return data;
- }
-
- public MeasureFilterDto setData(String data) {
- this.data = data;
- return this;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public MeasureFilterDto setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- return this;
- }
-
- public Date getUpdatedAt() {
- return updatedAt;
- }
-
- public MeasureFilterDto setUpdatedAt(Date updatedAt) {
- this.updatedAt = updatedAt;
- return this;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import org.sonar.db.Dao;
-import org.sonar.db.DbSession;
-
-public class MeasureFilterFavouriteDao implements Dao {
-
- public MeasureFilterFavouriteDto selectById(DbSession session, long id) {
- return session.getMapper(MeasureFilterFavouriteMapper.class).selectById(id);
- }
-
- public void insert(DbSession session, MeasureFilterFavouriteDto filter) {
- session.getMapper(MeasureFilterFavouriteMapper.class).insert(filter);
- }
-
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import java.util.Date;
-
-public class MeasureFilterFavouriteDto {
- private Long id;
- private Long userId;
- private Long measureFilterId;
- private Date createdAt;
-
- public Long getId() {
- return id;
- }
-
- public MeasureFilterFavouriteDto setId(Long id) {
- this.id = id;
- return this;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public MeasureFilterFavouriteDto setUserId(Long userId) {
- this.userId = userId;
- return this;
- }
-
- public Long getMeasureFilterId() {
- return measureFilterId;
- }
-
- public MeasureFilterFavouriteDto setMeasureFilterId(Long measureFilterId) {
- this.measureFilterId = measureFilterId;
- return this;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public MeasureFilterFavouriteDto setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- return this;
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-public interface MeasureFilterFavouriteMapper {
-
- MeasureFilterFavouriteDto selectById(long id);
-
- void insert(MeasureFilterFavouriteDto filter);
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-/**
- * @since 3.4
- */
-public interface MeasureFilterMapper {
- MeasureFilterDto findSystemFilterByName(String name);
-
- MeasureFilterDto selectById(long id);
-
- void insert(MeasureFilterDto filter);
-}
mapper.removeUserFromGroups(dto.getId());
mapper.deleteUnsharedUserIssueFilters(dto.getLogin());
mapper.deleteUserIssueFilterFavourites(dto.getLogin());
- mapper.deleteUnsharedUserMeasureFilters(dto.getId());
- mapper.deleteUserMeasureFilterFavourites(dto.getId());
mapper.deleteUserProperties(dto.getId());
mapper.deleteUserRoles(dto.getId());
mapper.deletePropertiesMatchingLogin(asList(DEFAULT_ISSUE_ASSIGNEE), dto.getLogin());
void deleteUserIssueFilterFavourites(String login);
- void deleteUnsharedUserMeasureFilters(long userId);
-
- void deleteUserMeasureFilterFavourites(long userId);
-
void deleteUserProperties(long userId);
void deleteUserRoles(long userId);
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
-<mapper namespace="org.sonar.db.measure.MeasureFilterFavouriteMapper">
-
- <sql id="measureFilterFavouriteColumns">
- mff.id,
- mff.user_id as "userId",
- mff.measure_filter_id as "measureFilterId",
- mff.created_at as "createdAt"
- </sql>
-
- <select id="selectById" parameterType="long" resultType="MeasureFilterFavourite">
- SELECT <include refid="measureFilterFavouriteColumns"/>
- FROM measure_filter_favourites mff
- WHERE mff.id=#{id}
- </select>
-
- <insert id="insert" parameterType="MeasureFilterFavourite" keyColumn="id" useGeneratedKeys="true" keyProperty="id">
- INSERT INTO measure_filter_favourites (user_id, measure_filter_id, created_at)
- VALUES (#{userId,jdbcType=BIGINT}, #{measureFilterId,jdbcType=BIGINT}, #{createdAt,jdbcType=TIMESTAMP})
- </insert>
-
-</mapper>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
-<mapper namespace="org.sonar.db.measure.MeasureFilterMapper">
-
- <sql id="measureFilterColumns">
- mf.id,
- mf.name,
- mf.user_id as "userId",
- mf.shared,
- mf.description,
- mf.data,
- mf.created_at as "createdAt",
- mf.updated_at as "updatedAt"
- </sql>
-
- <select id="findSystemFilterByName" parameterType="string" resultType="MeasureFilter">
- SELECT <include refid="measureFilterColumns"/>
- FROM measure_filters mf
- WHERE mf.user_id is null and mf.name=#{id}
- </select>
-
- <select id="selectById" parameterType="long" resultType="MeasureFilter">
- SELECT <include refid="measureFilterColumns"/>
- FROM measure_filters mf
- WHERE mf.id=#{id}
- </select>
-
- <insert id="insert" parameterType="MeasureFilter" keyColumn="id" useGeneratedKeys="true" keyProperty="id">
- INSERT INTO measure_filters (name, user_id, shared, description, data, created_at, updated_at)
- VALUES (#{name,jdbcType=VARCHAR}, #{userId,jdbcType=BIGINT}, #{shared,jdbcType=BOOLEAN}, #{description,jdbcType=VARCHAR}, #{data,jdbcType=VARCHAR},
- #{createdAt,jdbcType=TIMESTAMP}, #{updatedAt,jdbcType=TIMESTAMP})
- </insert>
-
-</mapper>
DELETE FROM properties WHERE user_id=#{id}
</delete>
- <delete id="deleteUnsharedUserMeasureFilters" parameterType="long">
- DELETE FROM measure_filters WHERE user_id=#{id} and shared <> ${_true}
- </delete>
-
- <delete id="deleteUserMeasureFilterFavourites" parameterType="long">
- DELETE FROM measure_filter_favourites WHERE user_id=#{id}
- </delete>
-
<delete id="deleteUnsharedUserIssueFilters" parameterType="String">
DELETE FROM issue_filters WHERE user_login=#{id} and shared <> ${_true}
</delete>
public void verify_count_of_added_components() {
ComponentContainer container = new ComponentContainer();
new DaoModule().configure(container);
- assertThat(container.size()).isEqualTo(2 + 48);
+ assertThat(container.size()).isEqualTo(2 + 46);
}
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import java.util.Date;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MeasureFilterDaoTest {
-
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- final DbSession session = db.getSession();
-
- MeasureFilterDao underTest = db.getDbClient().measureFilterDao();
-
- @Test
- public void should_find_filter() {
- db.prepareDbUnit(getClass(), "shared.xml");
-
- MeasureFilterDto filter = underTest.selectSystemFilterByName("Projects");
-
- assertThat(filter.getId()).isEqualTo(1L);
- assertThat(filter.getName()).isEqualTo("Projects");
- }
-
- @Test
- public void should_not_find_filter() {
- db.prepareDbUnit(getClass(), "shared.xml");
-
- assertThat(underTest.selectSystemFilterByName("Unknown")).isNull();
- }
-
- @Test
- public void select_by_id() throws Exception {
- MeasureFilterDto dto = new MeasureFilterDto()
- .setUserId(10L)
- .setName("name")
- .setDescription("description")
- .setData("data")
- .setShared(true)
- .setCreatedAt(new Date(1000L))
- .setUpdatedAt(new Date(2000L));
- underTest.insert(session, dto);
- session.commit();
-
- MeasureFilterDto dtoReloded = underTest.selectById(session, dto.getId());
- assertThat(dtoReloded).isNotNull();
- assertThat(dtoReloded.getUserId()).isEqualTo(10L);
- assertThat(dtoReloded.getName()).isEqualTo("name");
- assertThat(dtoReloded.getDescription()).isEqualTo("description");
- assertThat(dtoReloded.getData()).isEqualTo("data");
- assertThat(dtoReloded.isShared()).isTrue();
- assertThat(dtoReloded.getCreatedAt()).isEqualTo(new Date(1000L));
- assertThat(dtoReloded.getUpdatedAt()).isEqualTo(new Date(2000L));
-
- assertThat(underTest.selectById(session, 123L)).isNull();
- }
-
- @Test
- public void should_insert() {
- db.prepareDbUnit(getClass(), "shared.xml");
-
- MeasureFilterDto filterDto = new MeasureFilterDto();
- filterDto.setName("Project Treemap");
- filterDto.setUserId(123L);
- filterDto.setShared(true);
- filterDto.setDescription("Treemap of projects");
- filterDto.setData("qualifiers=TRK|display=treemap");
-
- underTest.insert(filterDto);
-
- db.assertDbUnit(getClass(), "shouldInsert-result.xml", new String[]{"created_at", "updated_at"}, "measure_filters");
- }
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.db.measure;
-
-import java.util.Date;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.utils.System2;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MeasureFilterFavouriteDaoTest {
-
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- final DbSession session = db.getSession();
-
- MeasureFilterFavouriteDao underTest = db.getDbClient().measureFilterFavouriteDao();
-
- @Test
- public void insert_and_select_by_id() throws Exception {
- MeasureFilterFavouriteDto dto = new MeasureFilterFavouriteDto()
- .setMeasureFilterId(5L)
- .setUserId(10L)
- .setCreatedAt(new Date(1000L));
- underTest.insert(session, dto);
- session.commit();
-
- MeasureFilterFavouriteDto dtoReloaded = underTest.selectById(session, dto.getId());
- assertThat(dtoReloaded).isNotNull();
- assertThat(dtoReloaded.getMeasureFilterId()).isEqualTo(5L);
- assertThat(dtoReloaded.getUserId()).isEqualTo(10L);
- assertThat(dtoReloaded.getCreatedAt()).isEqualTo(new Date(1000L));
-
- assertThat(underTest.selectById(session, 123L)).isNull();
- }
-
-}
import org.sonar.db.RowNotFoundException;
import org.sonar.db.issue.IssueFilterDto;
import org.sonar.db.issue.IssueFilterFavouriteDto;
-import org.sonar.db.measure.MeasureFilterDto;
-import org.sonar.db.measure.MeasureFilterFavouriteDto;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
UserDto user = newActiveUser();
IssueFilterDto issueFilter = insertIssueFilter(user, false);
IssueFilterFavouriteDto issueFilterFavourite = insertIssueFilterFavourite(issueFilter, user);
- MeasureFilterDto measureFilter = insertMeasureFilter(user, false);
- MeasureFilterFavouriteDto measureFilterFavourite = insertMeasureFilterFavourite(measureFilter, user);
PropertyDto property = insertProperty(user);
db.users().insertPermissionOnUser(user, "perm");
insertUserGroup(user);
assertThat(dbClient.issueFilterDao().selectById(session, issueFilter.getId())).isNull();
assertThat(dbClient.issueFilterFavouriteDao().selectById(session, issueFilterFavourite.getId())).isNull();
- assertThat(dbClient.measureFilterDao().selectById(session, measureFilter.getId())).isNull();
- assertThat(dbClient.measureFilterFavouriteDao().selectById(session, measureFilterFavourite.getId())).isNull();
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setKey(property.getKey()).build(), session)).isEmpty();
assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(session, user.getId(), db.getDefaultOrganization().getUuid())).isEmpty();
assertThat(dbClient.groupMembershipDao().countGroups(session, builder().login(user.getLogin()).membership(IN).build(), user.getId())).isZero();
assertThat(sharedFilterReloaded.getUserLogin()).isEqualTo(user.getLogin());
}
- @Test
- public void deactivate_user_does_not_remove_shared_measure_filter() throws Exception {
- UserDto user = newActiveUser();
- MeasureFilterDto notSharedFilter = insertMeasureFilter(user, false);
- MeasureFilterDto sharedFilter = insertMeasureFilter(user, true);
- session.commit();
-
- boolean deactivated = underTest.deactivateUserByLogin(session, user.getLogin());
- assertThat(deactivated).isTrue();
-
- assertThat(dbClient.measureFilterDao().selectById(session, notSharedFilter.getId())).isNull();
- MeasureFilterDto sharedFilterReloaded = dbClient.measureFilterDao().selectById(session, sharedFilter.getId());
- assertThat(sharedFilterReloaded).isNotNull();
- assertThat(sharedFilterReloaded.getUserId()).isEqualTo(user.getId());
- }
-
@Test
public void deactivate_user_also_remove_default_assignee_login_properties() throws Exception {
UserDto user = newActiveUser();
return dto;
}
- private MeasureFilterDto insertMeasureFilter(UserDto user, boolean shared) {
- MeasureFilterDto dto = new MeasureFilterDto().setUserId(user.getId()).setName(randomAlphanumeric(100)).setShared(shared);
- dbClient.measureFilterDao().insert(session, dto);
- return dto;
- }
-
- private MeasureFilterFavouriteDto insertMeasureFilterFavourite(MeasureFilterDto measureFilter, UserDto user) {
- MeasureFilterFavouriteDto dto = new MeasureFilterFavouriteDto().setUserId(user.getId()).setMeasureFilterId(measureFilter.getId());
- dbClient.measureFilterFavouriteDao().insert(session, dto);
- return dto;
- }
-
private PropertyDto insertProperty(UserDto user) {
PropertyDto dto = new PropertyDto().setKey(randomAlphanumeric(100)).setUserId(user.getId());
dbClient.propertiesDao().saveProperty(session, dto);
+++ /dev/null
-<dataset>
-
- <measure_filters
- id="1"
- name="Projects"
- user_id="[null]"
- shared="[true]"
- description="All projects"
- data="qualifiers=TRK"
- created_at="2012-12-25"
- updated_at="2012-12-25"/>
-
- <measure_filters
- id="2"
- name="Files"
- user_id="[null]"
- shared="[true]"
- description="All files"
- data="qualifiers=FIL"
- created_at="2012-01-25"
- updated_at="2012-01-25"/>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <measure_filters
- id="1"
- name="Projects"
- user_id="[null]"
- shared="[true]"
- description="All projects"
- data="qualifiers=TRK"
- created_at="2012-12-25"
- updated_at="2012-12-25"/>
-
- <measure_filters
- id="2"
- name="Files"
- user_id="[null]"
- shared="[true]"
- description="All files"
- data="qualifiers=FIL"
- created_at="2012-01-25"
- updated_at="2012-01-25"/>
-
-
- <measure_filters
- id="3"
- name="Project Treemap"
- user_id="123"
- shared="[true]"
- description="Treemap of projects"
- data="qualifiers=TRK|display=treemap"
- created_at="2012-12-25"
- updated_at="2012-12-25"/>
-
-</dataset>