From d59163c9ea99cfa76f7fb880ec69076b67fa60c7 Mon Sep 17 00:00:00 2001 From: Simon Brandhof Date: Wed, 21 May 2014 14:41:38 +0200 Subject: [PATCH] SONAR-5007 remove code using previous ES rule indices --- .../server/platform/ServerComponents.java | 4 - .../server/qualityprofile/ESActiveRule.java | 225 --------- .../qualityprofile/ProfileRuleQuery.java | 291 ----------- .../QProfileActiveRuleOperations.java | 366 +------------- .../server/qualityprofile/QProfileBackup.java | 21 +- .../server/qualityprofile/QProfileLookup.java | 4 - .../qualityprofile/QProfileOperations.java | 16 +- .../QProfileRepositoryExporter.java | 10 +- .../server/qualityprofile/QProfileRule.java | 194 -------- .../qualityprofile/QProfileRuleLookup.java | 386 --------------- .../qualityprofile/QProfileRuleParam.java | 69 --- .../server/qualityprofile/QProfiles.java | 86 +--- .../sonar/server/rule/RubyRuleService.java | 12 - .../org/sonar/server/rule/RuleOperations.java | 169 +------ .../java/org/sonar/server/rule/Rules.java | 107 +--- .../startup/RegisterQualityProfiles.java | 241 --------- .../config/mappings/active_rule_mapping.json | 64 --- .../rules_configuration_controller.rb | 192 ------- .../views/rules_configuration/_rule.html.erb | 125 ----- .../rules_configuration/_rule_note.html.erb | 68 --- .../rules_configuration/_rule_param.html.erb | 47 -- .../rules_configuration/_rule_tags.html.erb | 8 - .../rules_configuration/_select_tags.html.erb | 54 -- .../_select_tags_list.html.erb | 9 - .../views/rules_configuration/edit.html.erb | 69 --- .../views/rules_configuration/new.html.erb | 55 -- .../qualityprofile/ESActiveRuleTest.java | 255 ---------- .../qualityprofile/InheritedProfilesTest.java | 1 - .../qualityprofile/ProfileRuleQueryTest.java | 150 ------ .../qualityprofile/ProfilesManagerTest.java | 1 - .../qualityprofile/QProfileBackupTest.java | 25 +- .../QProfileOperationsTest.java | 25 +- .../QProfileRepositoryExporterTest.java | 7 +- .../QProfileRuleLookupTest.java | 468 ------------------ .../qualityprofile/QProfilesMediumTest.java | 78 ++- .../server/qualityprofile/QProfilesTest.java | 134 +---- .../RegisterQualityProfilesTest.java | 21 +- .../server/rule/RubyRuleServiceTest.java | 20 - .../sonar/server/rule/RuleOperationsTest.java | 203 +------- .../java/org/sonar/server/rule/RulesTest.java | 211 -------- .../startup/RegisterQualityProfilesTest.java | 364 -------------- 41 files changed, 97 insertions(+), 4758 deletions(-) delete mode 100644 sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java delete mode 100644 sonar-server/src/main/java/org/sonar/server/qualityprofile/ProfileRuleQuery.java delete mode 100644 sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRule.java delete mode 100644 sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleLookup.java delete mode 100644 sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleParam.java delete mode 100644 sonar-server/src/main/java/org/sonar/server/startup/RegisterQualityProfiles.java delete mode 100644 sonar-server/src/main/resources/org/sonar/server/es/config/mappings/active_rule_mapping.json delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_note.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_param.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_tags.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_select_tags.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_select_tags_list.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/edit.html.erb delete mode 100644 sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/new.html.erb delete mode 100644 sonar-server/src/test/java/org/sonar/server/qualityprofile/ESActiveRuleTest.java delete mode 100644 sonar-server/src/test/java/org/sonar/server/qualityprofile/ProfileRuleQueryTest.java delete mode 100644 sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleLookupTest.java delete mode 100644 sonar-server/src/test/java/org/sonar/server/rule/RulesTest.java delete mode 100644 sonar-server/src/test/java/org/sonar/server/startup/RegisterQualityProfilesTest.java diff --git a/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java b/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java index d92f34f77ce..6c097fe5fa0 100644 --- a/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java +++ b/sonar-server/src/main/java/org/sonar/server/platform/ServerComponents.java @@ -171,7 +171,6 @@ import org.sonar.server.qualitygate.ws.QGatesUpdateConditionAction; import org.sonar.server.qualitygate.ws.QGatesWs; import org.sonar.server.qualityprofile.ActiveRuleService; import org.sonar.server.qualityprofile.DefaultProfilesCache; -import org.sonar.server.qualityprofile.ESActiveRule; import org.sonar.server.qualityprofile.ProfilesManager; import org.sonar.server.qualityprofile.QProfileActiveRuleOperations; import org.sonar.server.qualityprofile.QProfileBackup; @@ -180,7 +179,6 @@ import org.sonar.server.qualityprofile.QProfileOperations; import org.sonar.server.qualityprofile.QProfileProjectLookup; import org.sonar.server.qualityprofile.QProfileProjectOperations; import org.sonar.server.qualityprofile.QProfileRepositoryExporter; -import org.sonar.server.qualityprofile.QProfileRuleLookup; import org.sonar.server.qualityprofile.QProfiles; import org.sonar.server.qualityprofile.QualityProfileService; import org.sonar.server.qualityprofile.RegisterQualityProfiles; @@ -399,7 +397,6 @@ class ServerComponents { pico.addComponent(ProfilesDao.class, false); pico.addComponent(ProfilesManager.class, false); pico.addSingleton(AnnotationProfileParser.class); - pico.addSingleton(QProfileRuleLookup.class); pico.addSingleton(QualityProfileService.class); pico.addSingleton(QProfiles.class); @@ -411,7 +408,6 @@ class ServerComponents { pico.addSingleton(QProfileBackup.class); pico.addSingleton(QProfileRepositoryExporter.class); pico.addSingleton(DefaultProfilesCache.class); - pico.addSingleton(ESActiveRule.class); pico.addSingleton(QProfileRecreateBuiltInAction.class); pico.addSingleton(QProfilesWs.class); pico.addSingleton(ProfilesWs.class); diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java deleted file mode 100644 index 47be3d63855..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ESActiveRule.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualityprofile; - -import com.google.common.base.Function; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; -import org.apache.ibatis.session.SqlSession; -import org.elasticsearch.common.io.BytesStream; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.FilterBuilders; -import org.elasticsearch.index.query.QueryBuilders; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.core.persistence.MyBatis; -import org.sonar.core.profiling.Profiling; -import org.sonar.core.profiling.Profiling.Level; -import org.sonar.core.profiling.StopWatch; -import org.sonar.core.qualityprofile.db.ActiveRuleDao; -import org.sonar.core.qualityprofile.db.ActiveRuleDto; -import org.sonar.core.qualityprofile.db.ActiveRuleParamDto; -import org.sonar.server.es.ESIndex; -import org.sonar.server.es.SearchQuery; -import org.sonar.server.rule.RuleRegistry; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated -public class ESActiveRule { - - public static final String TYPE_ACTIVE_RULE = "active_rule"; - private final ESIndex esIndex; - private final ActiveRuleDao activeRuleDao; - private final MyBatis myBatis; - private final Profiling profiling; - - public ESActiveRule(ESIndex esIndex, ActiveRuleDao activeRuleDao, MyBatis myBatis, Profiling profiling) { - this.esIndex = esIndex; - this.activeRuleDao = activeRuleDao; - this.myBatis = myBatis; - this.profiling = profiling; - } - - public void start() { - esIndex.addMappingFromClasspath(RuleRegistry.INDEX_RULES, TYPE_ACTIVE_RULE, "/org/sonar/server/es/config/mappings/active_rule_mapping.json"); - } - - public void bulkRegisterActiveRules() { - SqlSession session = myBatis.openSession(false); - try { - - StopWatch bulkWatch = startWatch(); - List activeRules = activeRuleDao.selectAll(session); - List activeRuleParams = activeRuleDao.selectAllParams(session); - bulkWatch.stop(String.format("Loaded %d active rules from DB", activeRules.size())); - - Multimap paramsByActiveRule = ArrayListMultimap.create(); - for (ActiveRuleParamDto param : activeRuleParams) { - paramsByActiveRule.put(param.getActiveRuleId(), param); - } - - String[] ids = bulkIndexActiveRules(activeRules, paramsByActiveRule); - removeDeletedActiveRules(ids); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void bulkIndexProfile(int profileId) { - SqlSession session = myBatis.openSession(false); - try { - bulkIndexProfile(profileId, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void bulkIndexProfile(int profileId, SqlSession session) { - bulkIndexActiveRules(activeRuleDao.selectByProfileId(profileId, session), session); - } - - public void bulkIndexActiveRuleIds(List activeRulesIds, SqlSession session) { - bulkIndexActiveRules(activeRuleDao.selectByIds(activeRulesIds, session), session); - } - - public void bulkIndexActiveRules(List ids) { - SqlSession session = myBatis.openSession(false); - try { - bulkIndexActiveRuleIds(ids, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void deleteActiveRulesFromProfile(int profileId) { - esIndex.client().prepareDeleteByQuery(RuleRegistry.INDEX_RULES).setTypes(ESActiveRule.TYPE_ACTIVE_RULE) - .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), - FilterBuilders.termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, profileId))) - .execute().actionGet(); - } - - public String[] bulkIndexActiveRules(List activeRules, Multimap paramsByActiveRule) { - StopWatch bulkWatch = startWatch(); - try { - int size = activeRules.size(); - String[] ids = new String[size]; - BytesStream[] docs = new BytesStream[size]; - String[] parentIds = new String[size]; - int index = 0; - - for (ActiveRuleDto activeRule : activeRules) { - ids[index] = activeRule.getId().toString(); - docs[index] = activeRuleDocument(activeRule, paramsByActiveRule.get(activeRule.getId())); - parentIds[index] = activeRule.getRulId().toString(); - index++; - } - - if (!activeRules.isEmpty()) { - esIndex.bulkIndex(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, ids, docs, parentIds); - } - bulkWatch.stop(String.format("Indexed %d active rules", size)); - return ids; - } catch (IOException e) { - bulkWatch.stop("Failed to indes active rules"); - throw new IllegalStateException("Unable to index active rules", e); - } - } - - public void save(ActiveRuleDto activeRule, Collection params) { - try { - esIndex.putSynchronous(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, Long.toString(activeRule.getId()), activeRuleDocument(activeRule, params), - Long.toString(activeRule.getRulId())); - } catch (IOException ioexception) { - throw new IllegalStateException("Unable to index active rule with id=" + activeRule.getId(), ioexception); - } - } - - public void deleteActiveRules(List activeRuleIds) { - List indexIds = newArrayList(); - for (Integer ruleId : activeRuleIds) { - indexIds.add(ruleId.toString()); - } - bulkDeleteActiveRules(indexIds); - } - - private void bulkDeleteActiveRules(List indexIds) { - if (!indexIds.isEmpty()) { - esIndex.bulkDelete(RuleRegistry.INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, indexIds.toArray(new String[0])); - } - } - - private void bulkIndexActiveRules(List activeRules, SqlSession session) { - Multimap paramsByActiveRule = ArrayListMultimap.create(); - List activeRulesIdList = newArrayList(Iterables.transform(activeRules, new Function() { - @Override - public Integer apply(ActiveRuleDto input) { - return input.getId(); - } - })); - for (ActiveRuleParamDto param : activeRuleDao.selectParamsByActiveRuleIds(activeRulesIdList, session)) { - paramsByActiveRule.put(param.getActiveRuleId(), param); - } - bulkIndexActiveRules(activeRules, paramsByActiveRule); - } - - private void removeDeletedActiveRules(String[] ids) { - TimeProfiler profiler = new TimeProfiler(); - List indexIds = esIndex.findDocumentIds(SearchQuery.create().index(RuleRegistry.INDEX_RULES).type(ESActiveRule.TYPE_ACTIVE_RULE)); - indexIds.removeAll(newArrayList(ids)); - profiler.start("Remove deleted active rule documents"); - bulkDeleteActiveRules(indexIds); - profiler.stop(); - } - - private XContentBuilder activeRuleDocument(ActiveRuleDto activeRule, Collection params) throws IOException { - XContentBuilder document = XContentFactory.jsonBuilder() - .startObject() - .field(ActiveRuleDocument.FIELD_ID, activeRule.getId()) - .field(ActiveRuleDocument.FIELD_ACTIVE_RULE_PARENT_ID, activeRule.getParentId()) - .field(ActiveRuleDocument.FIELD_SEVERITY, activeRule.getSeverityString()) - .field(ActiveRuleDocument.FIELD_PROFILE_ID, activeRule.getProfileId()) - .field(ActiveRuleDocument.FIELD_INHERITANCE, activeRule.getInheritance()); - if (!params.isEmpty()) { - document.startArray(ActiveRuleDocument.FIELD_PARAMS); - for (ActiveRuleParamDto param : params) { - document.startObject() - .field(ActiveRuleDocument.FIELD_PARAM_KEY, param.getKey()) - .field(ActiveRuleDocument.FIELD_PARAM_VALUE, param.getValue()) - .endObject(); - } - document.endArray(); - } - document.endObject(); - return document; - } - - private StopWatch startWatch() { - return profiling.start("qprofile", Level.BASIC); - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ProfileRuleQuery.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ProfileRuleQuery.java deleted file mode 100644 index ec4e3de3f8a..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ProfileRuleQuery.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package org.sonar.server.qualityprofile; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import org.sonar.server.exceptions.BadRequestException; -import org.sonar.server.util.RubyUtils; - -import javax.annotation.CheckForNull; - -import java.util.*; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated -public class ProfileRuleQuery { - - public static final String SORT_BY_CREATION_DATE = "SORT_BY_CREATION_DATE"; - public static final String SORT_BY_RULE_NAME = "SORT_BY_RULE_NAME"; - public static final Set SORTS = ImmutableSet.of(SORT_BY_CREATION_DATE, SORT_BY_RULE_NAME); - - private static final String INHERITANCE_ANY = "any"; - private static final String INHERITANCE_NOT = "NOT"; - private static final Set AUTHORIZED_INHERITANCE_PARAMS = ImmutableSet.of(QProfileRule.INHERITED, QProfileRule.OVERRIDES, INHERITANCE_ANY, INHERITANCE_NOT); - - private static final String PARAM_PROFILE_ID = "profileId"; - private static final String PARAM_LANGUAGE = "language"; - private static final String PARAM_NAME_OR_KEY = "nameOrKey"; - private static final String PARAM_REPOSITORY_KEYS = "repositoryKeys"; - private static final String PARAM_SEVERITIES = "severities"; - private static final String PARAM_STATUSES = "statuses"; - private static final String PARAM_TAGS = "tags"; - private static final String PARAM_INHERITANCE = "inheritance"; - private static final String PARAM_SORT = "sort_by"; - private static final String PARAM_ASC = "asc"; - - private int profileId; - private String language; - private String nameOrKey; - private List repositoryKeys; - private List severities; - private List statuses; - private List tags; - private String inheritance; - private boolean anyInheritance; - private boolean noInheritance; - - private String sort; - private boolean asc; - - private ProfileRuleQuery() { - repositoryKeys = Lists.newArrayList(); - severities = Lists.newArrayList(); - statuses = Lists.newArrayList(); - tags = Lists.newArrayList(); - sort = SORT_BY_RULE_NAME; - asc = true; - } - - public static ProfileRuleQuery parse(Map params) { - List errors = newArrayList(); - - validatePresenceOf(params, errors, PARAM_PROFILE_ID); - - ProfileRuleQuery result = new ProfileRuleQuery(); - - if (params.containsKey(PARAM_LANGUAGE)) { - result.setLanguage((String) params.get(PARAM_LANGUAGE)); - } - if (params.containsKey(PARAM_NAME_OR_KEY)) { - result.setNameOrKey((String) params.get(PARAM_NAME_OR_KEY)); - } - if (params.get(PARAM_REPOSITORY_KEYS) != null) { - result.addRepositoryKeys(optionalVarargs(params.get(PARAM_REPOSITORY_KEYS))); - } - if (params.get(PARAM_SEVERITIES) != null) { - result.addSeverities(optionalVarargs(params.get(PARAM_SEVERITIES))); - } - if (params.get(PARAM_STATUSES) != null) { - result.addStatuses(optionalVarargs(params.get(PARAM_STATUSES))); - } - if (params.get(PARAM_TAGS) != null) { - result.addTags(optionalVarargs(params.get(PARAM_TAGS))); - } - - parseInheritance(params, errors, result); - - parseParams(params, errors, result); - - if (!errors.isEmpty()) { - throw BadRequestException.of("Incorrect rule search parameters", errors); - } else { - result.profileId = RubyUtils.toInteger(params.get(PARAM_PROFILE_ID)); - } - return result; - } - - private static void parseInheritance(Map params, List errors, ProfileRuleQuery result) { - if (params.containsKey(PARAM_INHERITANCE)) { - String inheritance = (String) params.get(PARAM_INHERITANCE); - validateInheritance(inheritance, errors); - if (inheritance.equals(INHERITANCE_ANY)) { - result.setAnyInheritance(true); - } else if (inheritance.equals(INHERITANCE_NOT)) { - result.setNoInheritance(true); - } else { - result.setInheritance(inheritance); - } - } else { - result.setAnyInheritance(true); - } - } - - private static void parseParams(Map params, List errors, ProfileRuleQuery result) { - if (params.get(PARAM_SORT) != null) { - String sort = (String) params.get(PARAM_SORT); - Boolean asc = RubyUtils.toBoolean(params.get(PARAM_ASC)); - validateSort(sort, errors); - result.setSort(sort); - if (asc != null) { - result.setAsc(asc); - } - } - } - - private static void validatePresenceOf(Map params, List errors, String... paramNames) { - for (String param : paramNames) { - if (params.get(param) == null) { - errors.add(BadRequestException.Message.of("Missing parameter " + param)); - } - } - } - - private static void validateInheritance(String value, List errors) { - if (!AUTHORIZED_INHERITANCE_PARAMS.contains(value)) { - errors.add(BadRequestException.Message.of("Wrong inheritance param, should be one of " + AUTHORIZED_INHERITANCE_PARAMS)); - } - } - - private static void validateSort(String sort, List errors) { - if (!SORTS.contains(sort)) { - errors.add(BadRequestException.Message.of("Bad sort field, should be one of " + SORTS)); - } - } - - public static ProfileRuleQuery create(int profileId) { - ProfileRuleQuery newQuery = new ProfileRuleQuery(); - newQuery.profileId = profileId; - return newQuery; - } - - public ProfileRuleQuery setNameOrKey(String nameOrKey) { - this.nameOrKey = nameOrKey; - return this; - } - - public ProfileRuleQuery setLanguage(String language) { - this.language = language; - return this; - } - - public ProfileRuleQuery addRepositoryKeys(String... repositoryKeys) { - this.repositoryKeys.addAll(Arrays.asList(repositoryKeys)); - return this; - } - - public ProfileRuleQuery addSeverities(String... severities) { - this.severities.addAll(Arrays.asList(severities)); - return this; - } - - public ProfileRuleQuery addStatuses(String... statuses) { - this.statuses.addAll(Arrays.asList(statuses)); - return this; - } - - public ProfileRuleQuery addTags(String... tags) { - this.tags.addAll(Arrays.asList(tags)); - return this; - } - - public ProfileRuleQuery setInheritance(String inheritance) { - this.inheritance = inheritance; - return this; - } - - public ProfileRuleQuery setAnyInheritance(boolean anyInheritance) { - this.anyInheritance = anyInheritance; - return this; - } - - public ProfileRuleQuery setNoInheritance(boolean noInheritance) { - this.noInheritance = noInheritance; - return this; - } - - public ProfileRuleQuery setSort(String sort) { - this.sort = sort; - return this; - } - - public ProfileRuleQuery setAsc(boolean asc) { - this.asc = asc; - return this; - } - - public int profileId() { - return profileId; - } - - @CheckForNull - public String language() { - return language; - } - - @CheckForNull - public String nameOrKey() { - return nameOrKey; - } - - public Collection repositoryKeys() { - return ImmutableList.copyOf(repositoryKeys); - } - - public Collection severities() { - return ImmutableList.copyOf(severities); - } - - public Collection statuses() { - return ImmutableList.copyOf(statuses); - } - - public Collection tags() { - return ImmutableList.copyOf(tags); - } - - @CheckForNull - public String inheritance() { - return inheritance; - } - - public boolean anyInheritance() { - return anyInheritance; - } - - public boolean noInheritance() { - return noInheritance; - } - - public String sort() { - return sort; - } - - public boolean asc() { - return asc; - } - - private static String[] optionalVarargs(Object jRubyArray) { - List items = RubyUtils.toStrings(jRubyArray); - String[] empty = new String[0]; - if (items == null) { - return empty; - } else { - items.remove(""); - return items.toArray(empty); - } - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperations.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperations.java index 6b60de6aceb..81cdc65bc3e 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperations.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileActiveRuleOperations.java @@ -20,39 +20,24 @@ package org.sonar.server.qualityprofile; -import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import org.apache.ibatis.session.SqlSession; -import org.elasticsearch.common.base.Predicate; -import org.elasticsearch.common.collect.Iterables; import org.sonar.api.ServerComponent; import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RulePriority; import org.sonar.api.server.rule.RuleParamType; -import org.sonar.api.utils.System2; -import org.sonar.core.permission.GlobalPermissions; import org.sonar.core.persistence.DbSession; -import org.sonar.core.persistence.MyBatis; import org.sonar.core.qualityprofile.db.ActiveRuleDto; -import org.sonar.core.qualityprofile.db.ActiveRuleKey; import org.sonar.core.qualityprofile.db.ActiveRuleParamDto; import org.sonar.core.qualityprofile.db.QualityProfileDao; import org.sonar.core.qualityprofile.db.QualityProfileDto; import org.sonar.core.qualityprofile.db.QualityProfileKey; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleParamDto; -import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualityprofile.persistence.ActiveRuleDao; import org.sonar.server.rule2.persistence.RuleDao; -import org.sonar.server.user.UserSession; import org.sonar.server.util.TypeValidations; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import java.util.Date; import java.util.List; import static com.google.common.collect.Lists.newArrayList; @@ -63,62 +48,17 @@ import static com.google.common.collect.Lists.newArrayList; @Deprecated public class QProfileActiveRuleOperations implements ServerComponent { - private final MyBatis myBatis; private final ActiveRuleDao activeRuleDao; private final RuleDao ruleDao; private final QualityProfileDao profileDao; - private final ESActiveRule esActiveRule; - private final ProfilesManager profilesManager; - private final QProfileRuleLookup rules; - - private final System2 system; private final TypeValidations typeValidations; - public QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, ESActiveRule esActiveRule, - ProfilesManager profilesManager, TypeValidations typeValidations, QProfileRuleLookup rules) { - this(myBatis, activeRuleDao, ruleDao, profileDao, esActiveRule, profilesManager, rules, typeValidations, System2.INSTANCE); - } - - @VisibleForTesting - QProfileActiveRuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, ESActiveRule esActiveRule, - ProfilesManager profilesManager, QProfileRuleLookup rules, TypeValidations typeValidations, System2 system) { - this.myBatis = myBatis; + public QProfileActiveRuleOperations(ActiveRuleDao activeRuleDao, RuleDao ruleDao, QualityProfileDao profileDao, + TypeValidations typeValidations) { this.activeRuleDao = activeRuleDao; this.ruleDao = ruleDao; this.profileDao = profileDao; - this.esActiveRule = esActiveRule; - this.profilesManager = profilesManager; - this.rules = rules; this.typeValidations = typeValidations; - this.system = system; - } - - public void activateRule(QualityProfileKey profileKey, RuleKey ruleKey, String severity, UserSession userSession) { - validatePermission(userSession); - validateSeverity(severity); - - DbSession session = myBatis.openSession(false); - try { - ActiveRuleDto activeRule = findActiveRule(profileKey, ruleKey, session); - if (activeRule == null) { - activateRule(profileKey, ruleKey, severity, userSession, session); - } else { - updateSeverity(activeRule, severity, userSession, session); - } - } finally { - MyBatis.closeQuietly(session); - } - } - - private ActiveRuleDto activateRule(QualityProfileKey profileKey, RuleKey ruleKey, String severity, UserSession userSession, DbSession session) { - ActiveRuleDto activeRule = createActiveRule(profileKey, ruleKey, severity, session); - session.commit(); - //FIXME this is because profileManger uses Hibernate still - QualityProfileDto profile = profileDao.selectByNameAndLanguage(profileKey.name(), profileKey.lang()); - ProfilesManager.RuleInheritanceActions actions = profilesManager.activated(profile.getId(), activeRule.getId(), getLoggedName(userSession)); - reindexInheritanceResult(actions, session); - return activeRule; - } ActiveRuleDto createActiveRule(QualityProfileKey profileKey, RuleKey ruleKey, String severity, DbSession session) { @@ -141,118 +81,6 @@ public class QProfileActiveRuleOperations implements ServerComponent { return activeRule; } - private void updateSeverity(ActiveRuleDto activeRule, String newSeverity, UserSession userSession, DbSession session) { - String oldSeverity = activeRule.getSeverityString(); - activeRule.setSeverity(newSeverity); - activeRuleDao.update(activeRule, session); - session.commit(); - - notifySeverityChanged(activeRule, newSeverity, oldSeverity, session, userSession); - } - - public int activateRules(QualityProfileKey profileKey, ProfileRuleQuery query, UserSession userSession) { - validatePermission(userSession); - - DbSession session = myBatis.openSession(false); - try { - List ruleIdsToActivate = rules.searchInactiveProfileRuleIds(query); - for (Integer ruleId : ruleIdsToActivate) { - RuleDto rule = findRuleNotNull(ruleId, session); - activateRule(profileKey, rule.getKey(), rule.getSeverityString(), userSession, session); - } - return ruleIdsToActivate.size(); - } finally { - MyBatis.closeQuietly(session); - } - } - - public boolean deactivateRule(QualityProfileKey profileKey, RuleKey ruleKey, UserSession userSession) { - validatePermission(userSession); - DbSession session = myBatis.openSession(false); - try { - ActiveRuleDto activeRule = findActiveRuleNotNull(profileKey, ruleKey, session); - return deactivateRule(activeRule, userSession, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - private boolean deactivateRule(ActiveRuleDto activeRule, UserSession userSession, DbSession session) { - if (activeRule.getInheritance() == null) { - ProfilesManager.RuleInheritanceActions actions = profilesManager.deactivated(activeRule.getProfileId(), activeRule.getId(), getLoggedName(userSession)); - - activeRuleDao.removeAllParam(activeRule, session); - activeRuleDao.delete(activeRule, session); - actions.addToDelete(activeRule.getId()); - session.commit(); - - reindexInheritanceResult(actions, session); - return true; - } - return false; - } - - public int deactivateRules(ProfileRuleQuery query, UserSession userSession) { - validatePermission(userSession); - - DbSession session = myBatis.openSession(false); - int numberOfDeactivatedRules = 0; - try { - List activeRuleIdsToDeactivate = rules.searchProfileRuleIds(query); - for (int activeRuleId : activeRuleIdsToDeactivate) { - ActiveRuleDto activeRule = findActiveRuleNotNull(activeRuleId, session); - if (deactivateRule(activeRule, userSession, session)) { - numberOfDeactivatedRules++; - } - } - return numberOfDeactivatedRules; - } finally { - MyBatis.closeQuietly(session); - } - } - - public void updateActiveRuleParam(int activeRuleId, String key, @Nullable String value, UserSession userSession) { - validatePermission(userSession); - - DbSession session = myBatis.openSession(false); - try { - String sanitizedValue = Strings.emptyToNull(value); - ActiveRuleParamDto activeRuleParam = findActiveRuleParam(activeRuleId, key, session); - ActiveRuleDto activeRule = findActiveRuleNotNull(activeRuleId, session); - if (activeRuleParam == null && sanitizedValue != null) { - createActiveRuleParam(activeRule, key, sanitizedValue, userSession, session); - } else if (activeRuleParam != null && sanitizedValue == null) { - deleteActiveRuleParam(activeRule, activeRuleParam, userSession, session); - } else if (activeRuleParam != null) { - updateActiveRuleParam(activeRule, activeRuleParam, sanitizedValue, userSession, session); - } - // If no active rule param and no value -> do nothing - - } finally { - MyBatis.closeQuietly(session); - } - } - - private void createActiveRuleParam(ActiveRuleDto activeRule, String key, String value, UserSession userSession, DbSession session) { - RuleParamDto ruleParam = findRuleParamNotNull(activeRule.getRulId(), key, session); - validateParam(ruleParam, value); - ActiveRuleParamDto activeRuleParam = ActiveRuleParamDto.createFor(ruleParam) - .setKey(key) - .setValue(value); - activeRuleDao.addParam(activeRule, activeRuleParam, session); - session.commit(); - - ProfilesManager.RuleInheritanceActions actions = profilesManager.ruleParamChanged( - activeRule.getProfileId(), activeRule.getId(), key, null, value, getLoggedName(userSession)); - reindexInheritanceResult(actions, session); - } - - private void deleteActiveRuleParam(ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam, UserSession userSession, DbSession session) { - activeRuleDao.removeParam(activeRule, activeRuleParam, session); - session.commit(); - notifyParamsDeleted(activeRule, newArrayList(activeRuleParam), session, userSession); - } - void updateActiveRuleParam(ActiveRuleDto activeRule, String key, String sanitizedValue, DbSession session) { RuleParamDto ruleParam = findRuleParamNotNull(activeRule.getRulId(), key, session); ActiveRuleParamDto activeRuleParam = findActiveRuleParamNotNull(activeRule.getId(), key, session); @@ -262,159 +90,6 @@ public class QProfileActiveRuleOperations implements ServerComponent { activeRuleDao.updateParam(activeRule, activeRuleParam, session); } - private void updateActiveRuleParam(ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam, String sanitizedValue, UserSession userSession, DbSession session) { - RuleParamDto ruleParam = findRuleParamNotNull(activeRule.getRulId(), activeRuleParam.getKey(), session); - validateParam(ruleParam, sanitizedValue); - - String oldValue = activeRuleParam.getValue(); - activeRuleParam.setValue(sanitizedValue); - activeRuleDao.updateParam(activeRule, activeRuleParam, session); - session.commit(); - - ProfilesManager.RuleInheritanceActions actions = profilesManager.ruleParamChanged(activeRule.getProfileId(), activeRule.getId(), activeRuleParam.getKey(), oldValue, - sanitizedValue, getLoggedName(userSession)); - reindexInheritanceResult(actions, session); - } - - public void revertActiveRule(int activeRuleId, UserSession userSession) { - validatePermission(userSession); - - DbSession session = myBatis.openSession(false); - try { - ActiveRuleDto activeRule = findActiveRuleNotNull(activeRuleId, session); - if (activeRule.doesOverride()) { - revertActiveRule(activeRule, userSession, session); - } - } finally { - MyBatis.closeQuietly(session); - } - } - - private void revertActiveRule(ActiveRuleDto activeRule, UserSession userSession, DbSession session) { - ProfilesManager.RuleInheritanceActions actions = new ProfilesManager.RuleInheritanceActions(); - ActiveRuleDto parent = getParent(activeRule, session); - - List newParams = restoreActiveParametersFromActiveRuleParent(activeRule, parent, actions, userSession, session); - restoreSeverityFromActiveRuleParent(activeRule, parent, actions, userSession, session); - reindexInheritanceResult(actions, session); - - // Update inheritance - activeRule.setInheritance(ActiveRuleDto.INHERITED); - activeRuleDao.update(activeRule, session); - session.commit(); - reindexActiveRule(activeRule, newParams); - } - - private ActiveRuleDto getParent(ActiveRuleDto activeRule, DbSession session) { - Integer parentId = activeRule.getParentId(); - if (parentId != null) { - ActiveRuleDto parent = activeRuleDao.getById(parentId, session); - if (parent != null) { - return parent; - } - } - throw new IllegalStateException("Can't find parent of active rule : " + activeRule.getId()); - } - - private List restoreActiveParametersFromActiveRuleParent(ActiveRuleDto activeRule, ActiveRuleDto parent, ProfilesManager.RuleInheritanceActions actions, - UserSession userSession, DbSession session) { - // Restore all parameters from parent - List parentParams = activeRuleDao.findParamsByActiveRule(parent, session); - List activeRuleParams = activeRuleDao.findParamsByActiveRule(activeRule, session); - List newParams = newArrayList(); - List paramKeys = newArrayList(); - for (ActiveRuleParamDto param : activeRuleParams) { - final String key = param.getKey(); - ActiveRuleParamDto parentParam = Iterables.find(parentParams, new Predicate() { - @Override - public boolean apply(ActiveRuleParamDto activeRuleParamDto) { - return activeRuleParamDto.getKey().equals(key); - } - }, null); - if (parentParam != null && !Strings.isNullOrEmpty(parentParam.getValue())) { - String oldValue = param.getValue(); - String newValue = parentParam.getValue(); - param.setValue(newValue); - activeRuleDao.updateParam(activeRule, param, session); - session.commit(); - newParams.add(param); - actions.add(profilesManager.ruleParamChanged(activeRule.getProfileId(), activeRule.getId(), key, oldValue, newValue, getLoggedName(userSession))); - } else { - activeRuleDao.removeParam(activeRule, param, session); - session.commit(); - actions.add(profilesManager.ruleParamChanged(activeRule.getProfileId(), activeRule.getId(), key, param.getValue(), null, getLoggedName(userSession))); - } - paramKeys.add(key); - } - for (ActiveRuleParamDto parentParam : parentParams) { - if (!paramKeys.contains(parentParam.getKey())) { - ActiveRuleParamDto activeRuleParam = ActiveRuleParamDto.createFrom(parentParam) - .setKey(parentParam.getKey()) - .setValue(parentParam.getValue()); - activeRuleDao.addParam(activeRule, activeRuleParam, session); - session.commit(); - newParams.add(activeRuleParam); - actions.add(profilesManager.ruleParamChanged(activeRule.getProfileId(), activeRule.getId(), parentParam.getKey(), null, parentParam.getValue(), - getLoggedName(userSession))); - } - } - return newParams; - } - - private void restoreSeverityFromActiveRuleParent(ActiveRuleDto activeRule, ActiveRuleDto parent, ProfilesManager.RuleInheritanceActions actions, - UserSession userSession, DbSession session) { - String oldSeverity = activeRule.getSeverityString(); - String newSeverity = parent.getSeverityString(); - if (!oldSeverity.equals(newSeverity)) { - activeRule.setSeverity(newSeverity); - activeRuleDao.update(activeRule, session); - session.commit(); - actions.add(profilesManager.ruleSeverityChanged(activeRule.getProfileId(), activeRule.getId(), - RulePriority.valueOf(oldSeverity), RulePriority.valueOf(newSeverity), getLoggedName(userSession))); - } - } - - private void notifyParamsDeleted(ActiveRuleDto activeRule, List params, SqlSession session, UserSession userSession) { - ProfilesManager.RuleInheritanceActions actions = new ProfilesManager.RuleInheritanceActions(); - for (ActiveRuleParamDto activeRuleParam : params) { - actions.add(profilesManager.ruleParamChanged(activeRule.getProfileId(), activeRule.getId(), activeRuleParam.getKey(), activeRuleParam.getValue(), - null, getLoggedName(userSession))); - } - reindexInheritanceResult(actions, session); - } - - private void notifySeverityChanged(ActiveRuleDto activeRule, String newSeverity, String oldSeverity, SqlSession session, UserSession userSession) { - ProfilesManager.RuleInheritanceActions actions = profilesManager.ruleSeverityChanged(activeRule.getProfileId(), activeRule.getId(), - RulePriority.valueOf(oldSeverity), RulePriority.valueOf(newSeverity), - getLoggedName(userSession)); - reindexInheritanceResult(actions, session); - } - - private void reindexInheritanceResult(ProfilesManager.RuleInheritanceActions actions, SqlSession session) { - esActiveRule.deleteActiveRules(actions.idsToDelete()); - esActiveRule.bulkIndexActiveRuleIds(actions.idsToIndex(), session); - } - - @Deprecated - private void reindexActiveRule(ActiveRuleDto activeRuleDto, DbSession session) { - reindexActiveRule(activeRuleDto, activeRuleDao.findParamsByActiveRule(activeRuleDto, session)); - } - - @Deprecated - private void reindexActiveRule(ActiveRuleDto activeRuleDto, List params) { - esActiveRule.save(activeRuleDto, params); - } - - private void validatePermission(UserSession userSession) { - userSession.checkLoggedIn(); - userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN); - } - - private void validateSeverity(String severity) { - if (!Severity.ALL.contains(severity)) { - throw new BadRequestException("The severity is not valid"); - } - } private void validateParam(RuleParamDto ruleParam, String value) { RuleParamType ruleParamType = RuleParamType.parse(ruleParam.getType()); @@ -426,13 +101,6 @@ public class QProfileActiveRuleOperations implements ServerComponent { } } - private String getLoggedName(UserSession userSession) { - String name = userSession.name(); - if (Strings.isNullOrEmpty(name)) { - throw new BadRequestException("User name can't be null"); - } - return name; - } private RuleParamDto findRuleParamNotNull(Integer ruleId, String key, DbSession session) { RuleDto rule = ruleDao.getById(ruleId, session); @@ -443,36 +111,6 @@ public class QProfileActiveRuleOperations implements ServerComponent { return ruleParam; } - private QualityProfileDto findProfileNotNull(int profileId, DbSession session) { - QualityProfileDto profile = profileDao.selectById(profileId, session); - QProfileValidations.checkProfileIsNotNull(profile); - return profile; - } - - private RuleDto findRuleNotNull(int ruleId, DbSession session) { - RuleDto rule = ruleDao.getById(ruleId, session); - QProfileValidations.checkRuleIsNotNull(rule); - return rule; - } - - @CheckForNull - private ActiveRuleDto findActiveRule(QualityProfileKey profileKey, RuleKey ruleKey, DbSession session) { - return activeRuleDao.getByKey( - ActiveRuleKey.of(profileKey,ruleKey), session); - } - - private ActiveRuleDto findActiveRuleNotNull(QualityProfileKey profileKey, RuleKey ruleKey, DbSession session) { - ActiveRuleDto activeRule = findActiveRule(profileKey, ruleKey, session); - QProfileValidations.checkActiveRuleIsNotNull(activeRule); - return activeRule; - } - - private ActiveRuleDto findActiveRuleNotNull(int activeRuleId, DbSession session) { - ActiveRuleDto activeRule = activeRuleDao.getById(activeRuleId, session); - QProfileValidations.checkActiveRuleIsNotNull(activeRule); - return activeRule; - } - @CheckForNull private ActiveRuleParamDto findActiveRuleParam(int activeRuleId, String key, DbSession session) { ActiveRuleDto activeRule = activeRuleDao.getById(activeRuleId, session); diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java index bfb5e517357..c6789a360d9 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java @@ -55,10 +55,6 @@ import java.util.Map; import static com.google.common.collect.Lists.newArrayList; -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated public class QProfileBackup implements ServerComponent { private final DatabaseSessionFactory sessionFactory; @@ -70,21 +66,20 @@ public class QProfileBackup implements ServerComponent { private final QProfileOperations qProfileOperations; private final QProfileActiveRuleOperations qProfileActiveRuleOperations; private final RuleDao ruleDao; - private final ESActiveRule esActiveRule; private final List definitions; private final DefaultProfilesCache defaultProfilesCache; private final PreviewCache dryRunCache; public QProfileBackup(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, XMLProfileSerializer xmlProfileSerializer, MyBatis myBatis, QProfileLookup qProfileLookup, QProfileOperations qProfileOperations, QProfileActiveRuleOperations qProfileActiveRuleOperations, RuleDao ruleDao, - ESActiveRule esActiveRule, DefaultProfilesCache defaultProfilesCache, PreviewCache dryRunCache) { - this(sessionFactory, xmlProfileParser, xmlProfileSerializer, myBatis, qProfileLookup, qProfileOperations, qProfileActiveRuleOperations, ruleDao, esActiveRule, + DefaultProfilesCache defaultProfilesCache, PreviewCache dryRunCache) { + this(sessionFactory, xmlProfileParser, xmlProfileSerializer, myBatis, qProfileLookup, qProfileOperations, qProfileActiveRuleOperations, ruleDao, Collections.emptyList(), defaultProfilesCache, dryRunCache); } public QProfileBackup(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, XMLProfileSerializer xmlProfileSerializer, MyBatis myBatis, QProfileLookup qProfileLookup, QProfileOperations qProfileOperations, QProfileActiveRuleOperations qProfileActiveRuleOperations, RuleDao ruleDao, - ESActiveRule esActiveRule, List definitions, DefaultProfilesCache defaultProfilesCache, PreviewCache dryRunCache) { + List definitions, DefaultProfilesCache defaultProfilesCache, PreviewCache dryRunCache) { this.sessionFactory = sessionFactory; this.xmlProfileParser = xmlProfileParser; this.xmlProfileSerializer = xmlProfileSerializer; @@ -93,7 +88,6 @@ public class QProfileBackup implements ServerComponent { this.qProfileOperations = qProfileOperations; this.qProfileActiveRuleOperations = qProfileActiveRuleOperations; this.ruleDao = ruleDao; - this.esActiveRule = esActiveRule; this.definitions = definitions; this.defaultProfilesCache = defaultProfilesCache; this.dryRunCache = dryRunCache; @@ -129,7 +123,7 @@ public class QProfileBackup implements ServerComponent { if (newProfile == null) { throw new BadRequestException("Restore of the profile has failed."); } - esActiveRule.bulkIndexProfile(newProfile.id(), session); + //esActiveRule.bulkIndexProfile(newProfile.id(), session); dryRunCache.reportGlobalModification(session); session.commit(); result.setProfile(newProfile); @@ -159,7 +153,7 @@ public class QProfileBackup implements ServerComponent { QualityProfileKey.of(name, language), currentRulesProfile, session); } - esActiveRule.bulkIndexProfile(profile.id(), session); + //esActiveRule.bulkIndexProfile(profile.id(), session); } dryRunCache.reportGlobalModification(session); session.commit(); @@ -182,9 +176,6 @@ public class QProfileBackup implements ServerComponent { return profilesByName; } - /** - * Used by {@link org.sonar.server.startup.RegisterQualityProfiles} - */ public void restoreFromActiveRules(QualityProfileKey profileKey, RulesProfile rulesProfile, DbSession session) { for (org.sonar.api.rules.ActiveRule activeRule : rulesProfile.getActiveRules()) { RuleKey ruleKey = RuleKey.of(activeRule.getRepositoryKey(), activeRule.getRuleKey()); @@ -220,7 +211,7 @@ public class QProfileBackup implements ServerComponent { // Warning, profile with children can be deleted as no check is done! hibernateSession.removeWithoutFlush(existingProfile); hibernateSession.commit(); - esActiveRule.deleteActiveRulesFromProfile(existingProfile.getId()); + //esActiveRule.deleteActiveRulesFromProfile(existingProfile.getId()); } } diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java index 2edcbc171eb..b6c15ae3df6 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java @@ -34,10 +34,6 @@ import java.util.List; import static com.google.common.collect.Lists.newArrayList; -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated public class QProfileLookup implements ServerComponent { private final MyBatis myBatis; diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java index be0597a2fae..6994e030ad2 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java @@ -40,10 +40,6 @@ import javax.annotation.Nullable; import java.util.List; import java.util.Map; -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated public class QProfileOperations implements ServerComponent { public static final String PROFILE_PROPERTY_PREFIX = "sonar.profile."; @@ -54,12 +50,11 @@ public class QProfileOperations implements ServerComponent { private final PropertiesDao propertiesDao; private final QProfileRepositoryExporter exporter; private final PreviewCache dryRunCache; - private final ESActiveRule esActiveRule; private final QProfileLookup profileLookup; private final ProfilesManager profilesManager; public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao, - QProfileRepositoryExporter exporter, PreviewCache dryRunCache, ESActiveRule esActiveRule, QProfileLookup profileLookup, + QProfileRepositoryExporter exporter, PreviewCache dryRunCache, QProfileLookup profileLookup, ProfilesManager profilesManager) { this.myBatis = myBatis; this.dao = dao; @@ -67,7 +62,6 @@ public class QProfileOperations implements ServerComponent { this.propertiesDao = propertiesDao; this.exporter = exporter; this.dryRunCache = dryRunCache; - this.esActiveRule = esActiveRule; this.profileLookup = profileLookup; this.profilesManager = profilesManager; } @@ -156,7 +150,7 @@ public class QProfileOperations implements ServerComponent { activeRuleDao.deleteByProfile(profile, session); dao.delete(profile.id(), session); propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.language(), profile.name(), session); - esActiveRule.deleteActiveRulesFromProfile(profile.id()); + //esActiveRule.deleteActiveRulesFromProfile(profile.id()); dryRunCache.reportGlobalModification(session); } @@ -191,8 +185,8 @@ public class QProfileOperations implements ServerComponent { dao.update(profile, session); session.commit(); - esActiveRule.deleteActiveRules(actions.idsToDelete()); - esActiveRule.bulkIndexActiveRuleIds(actions.idsToIndex(), session); + //esActiveRule.deleteActiveRules(actions.idsToDelete()); + //esActiveRule.bulkIndexActiveRuleIds(actions.idsToIndex(), session); } finally { MyBatis.closeQuietly(session); } @@ -207,7 +201,7 @@ public class QProfileOperations implements ServerComponent { int copyProfileId = profilesManager.copyProfile(profileId, copyProfileName); // Cannot reuse same session as hibernate as create active rules in another session - esActiveRule.bulkIndexProfile(copyProfileId); +// esActiveRule.bulkIndexProfile(copyProfileId); } finally { MyBatis.closeQuietly(session); } diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRepositoryExporter.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRepositoryExporter.java index a6a5becc61b..5a098665cce 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRepositoryExporter.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRepositoryExporter.java @@ -57,22 +57,20 @@ public class QProfileRepositoryExporter implements ServerComponent { private final DatabaseSessionFactory sessionFactory; private final ActiveRuleDao activeRuleDao; - private final ESActiveRule ruleRegistry; private final List exporters; private final List importers; /** * Used by pico when no plugin provide profile exporter / importer */ - public QProfileRepositoryExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, ESActiveRule esActiveRule) { - this(sessionFactory, activeRuleDao, esActiveRule, Lists.newArrayList(), Lists.newArrayList()); + public QProfileRepositoryExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao) { + this(sessionFactory, activeRuleDao, Lists.newArrayList(), Lists.newArrayList()); } - public QProfileRepositoryExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, ESActiveRule esActiveRule, + public QProfileRepositoryExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, List importers, List exporters) { this.sessionFactory = sessionFactory; this.activeRuleDao = activeRuleDao; - this.ruleRegistry = esActiveRule; this.importers = importers; this.exporters = exporters; } @@ -116,7 +114,7 @@ public class QProfileRepositoryExporter implements ServerComponent { paramsByActiveRule.put(activeRuleDto.getId(), activeRuleParamDto); } } - ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule); + //ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule); } private void processValidationMessages(ValidationMessages messages, QProfileResult result) { diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRule.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRule.java deleted file mode 100644 index 095ba6924d0..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRule.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualityprofile; - -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.elasticsearch.common.collect.Lists; -import org.elasticsearch.common.collect.Maps; -import org.elasticsearch.common.joda.time.format.ISODateTimeFormat; -import org.sonar.server.rule.Rule; -import org.sonar.server.rule.RuleDocumentParser; -import org.sonar.server.rule.RuleNote; -import org.sonar.server.rule.RuleParam; - -import javax.annotation.CheckForNull; - -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; - -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated -public class QProfileRule { - - public static final String INHERITED = "INHERITED"; - public static final String OVERRIDES = "OVERRIDES"; - - private final Rule rule; - - private final Integer activeRuleId; - private final Integer activeRuleParentId; - private final String severity; - private final String inheritance; - private final List params; - - // TODO move this in a parser class - public QProfileRule(Map ruleSource, Map activeRuleSource) { - rule = RuleDocumentParser.parse(ruleSource); - if (activeRuleSource.isEmpty()) { - activeRuleId = null; - severity = (String) ruleSource.get(ActiveRuleDocument.FIELD_SEVERITY); - inheritance = null; - activeRuleParentId = null; - } else { - activeRuleId = (Integer) activeRuleSource.get(ActiveRuleDocument.FIELD_ID); - severity = (String) activeRuleSource.get(ActiveRuleDocument.FIELD_SEVERITY); - inheritance = (String) activeRuleSource.get(ActiveRuleDocument.FIELD_INHERITANCE); - activeRuleParentId = (Integer) activeRuleSource.get(ActiveRuleDocument.FIELD_ACTIVE_RULE_PARENT_ID); - } - - params = Lists.newArrayList(); - Map paramValues = Maps.newHashMap(); - if (activeRuleSource.containsKey(ActiveRuleDocument.FIELD_PARAMS)) { - for (Map activeRuleParam: (List>) activeRuleSource.get(ActiveRuleDocument.FIELD_PARAMS)) { - paramValues.put((String) activeRuleParam.get(ActiveRuleDocument.FIELD_PARAM_KEY), (String) activeRuleParam.get(ActiveRuleDocument.FIELD_PARAM_VALUE)); - } - } - for (RuleParam param: rule.params()) { - params.add(new QProfileRuleParam(param, paramValues.get(param.key()))); - } - } - - public QProfileRule(Map ruleSource) { - this(ruleSource, Maps. newHashMap()); - } - - public int id() { - return rule.id(); - } - - public String key() { - return rule.ruleKey().rule(); - } - - public String repositoryKey() { - return rule.ruleKey().repository(); - } - - public String language() { - return rule.language(); - } - - public String name() { - return rule.name(); - } - - public String description() { - return rule.description(); - } - - public String status() { - return rule.status(); - } - - public Date createdAt() { - return rule.createdAt(); - } - - @CheckForNull - public Date updatedAt() { - return rule.updatedAt(); - } - - @CheckForNull - public Integer templateId() { - return rule.templateId(); - } - - public boolean isTemplate() { - return rule.isTemplate(); - } - - public boolean isEditable() { - return rule.isEditable(); - } - - public static Date parseOptionalDate(String field, Map ruleSource) { - String dateValue = (String) ruleSource.get(field); - if (dateValue == null) { - return null; - } else { - return ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(dateValue).toDate(); - } - } - - @CheckForNull - public RuleNote ruleNote() { - return rule.ruleNote(); - } - - public Collection systemTags() { - return rule.systemTags(); - } - - public Collection adminTags() { - return rule.adminTags(); - } - - @CheckForNull - public Integer activeRuleId() { - return activeRuleId; - } - - public String severity() { - return severity; - } - - @CheckForNull - public String inheritance() { - return inheritance; - } - - @CheckForNull - public Integer activeRuleParentId() { - return activeRuleParentId; - } - - public boolean isInherited() { - return INHERITED.equals(inheritance); - } - - public boolean isOverrides() { - return OVERRIDES.equals(inheritance); - } - - public List params() { - return params; - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this).toString(); - } - -} diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleLookup.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleLookup.java deleted file mode 100644 index 3c53aacb3cd..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleLookup.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualityprofile; - -import org.sonar.server.paging.Paging; -import org.sonar.server.paging.PagingResult; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; -import org.elasticsearch.action.get.GetResponse; -import org.elasticsearch.action.search.SearchRequestBuilder; -import org.elasticsearch.common.collect.Lists; -import org.elasticsearch.index.query.BoolFilterBuilder; -import org.elasticsearch.index.query.FilterBuilder; -import org.elasticsearch.index.query.MatchQueryBuilder.Operator; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.SearchHits; -import org.elasticsearch.search.sort.SortOrder; -import org.sonar.api.ServerExtension; -import org.sonar.api.rules.Rule; -import org.sonar.server.es.ESIndex; -import org.sonar.server.rule.RuleDocument; - -import javax.annotation.CheckForNull; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import static com.google.common.collect.Lists.newArrayList; -import static org.elasticsearch.index.query.FilterBuilders.*; -import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; -import static org.sonar.server.rule.RuleRegistry.INDEX_RULES; -import static org.sonar.server.rule.RuleRegistry.TYPE_RULE; - -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated -public class QProfileRuleLookup implements ServerExtension { - - private static final int PAGE_SIZE = 100; - - private static final String FIELD_PARENT = "_parent"; - private static final String FIELD_SOURCE = "_source"; - - private final ESIndex index; - - public QProfileRuleLookup(ESIndex index) { - this.index = index; - } - - @CheckForNull - public QProfileRule findByActiveRuleId(int activeRuleId) { - GetResponse activeRuleResponse = index.client().prepareGet(INDEX_RULES, ESActiveRule.TYPE_ACTIVE_RULE, Integer.toString(activeRuleId)) - .setFields(FIELD_SOURCE, FIELD_PARENT) - .execute().actionGet(); - Map activeRuleSource = activeRuleResponse.getSourceAsMap(); - if (activeRuleSource != null) { - Map ruleSource = index.client().prepareGet(INDEX_RULES, TYPE_RULE, (String) activeRuleResponse.getField(FIELD_PARENT).getValue()) - .execute().actionGet().getSourceAsMap(); - if (ruleSource != null) { - return new QProfileRule(ruleSource, activeRuleSource); - } - } - return null; - } - - @CheckForNull - public QProfileRule findByProfileIdAndRuleId(int profileId, int ruleId) { - Map ruleSource = index.client().prepareGet(INDEX_RULES, TYPE_RULE, Integer.toString(ruleId)) - .execute().actionGet().getSourceAsMap(); - if (ruleSource != null) { - SearchHits activeRuleHits = searchActiveRules(ProfileRuleQuery.create(profileId), newArrayList(ruleId), FIELD_SOURCE, FIELD_PARENT); - long resultSize = activeRuleHits.totalHits(); - if (resultSize > 0) { - if (resultSize == 1) { - return new QProfileRule(ruleSource, activeRuleHits.getAt(0).sourceAsMap()); - } else { - throw new IllegalStateException("There is more than one result."); - } - } - } - return null; - } - - @CheckForNull - public QProfileRule findByRuleId(int ruleId) { - Map ruleSource = index.client().prepareGet(INDEX_RULES, TYPE_RULE, Integer.toString(ruleId)) - .execute().actionGet().getSourceAsMap(); - if (ruleSource != null) { - return new QProfileRule(ruleSource); - } - return null; - } - - @CheckForNull - public QProfileRule findParentProfileRule(QProfileRule rule) { - Integer parentId = rule.activeRuleParentId(); - if (parentId != null) { - return findByActiveRuleId(parentId); - } - return null; - } - - public QProfileRuleResult search(ProfileRuleQuery query, Paging paging) { - SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, activeRuleFilter(query)))); - List ruleIds = Lists.newArrayList(); - for (SearchHit ruleHit : ruleHits) { - ruleIds.add(Integer.valueOf(ruleHit.id())); - } - - List result = Lists.newArrayList(); - if (!ruleIds.isEmpty()) { - SearchHits activeRuleHits = searchActiveRules(query, ruleIds, FIELD_SOURCE, FIELD_PARENT); - - Map activeRuleByParent = Maps.newHashMap(); - for (SearchHit activeRuleHit : activeRuleHits) { - activeRuleByParent.put((String) activeRuleHit.field(FIELD_PARENT).getValue(), activeRuleHit); - } - - for (SearchHit ruleHit : ruleHits) { - result.add(new QProfileRule(ruleHit.sourceAsMap(), activeRuleByParent.get(ruleHit.id()).sourceAsMap())); - } - } - return new QProfileRuleResult(result, PagingResult.create(paging.pageSize(), paging.pageIndex(), ruleHits.getTotalHits())); - } - - public List searchProfileRuleIds(final ProfileRuleQuery query) { - return searchProfileRuleIds(query, PAGE_SIZE); - } - - @VisibleForTesting - List searchProfileRuleIds(final ProfileRuleQuery query, int pageSize) { - final List activeRuleIds = newArrayList(); - new Search(pageSize) { - @Override - public int search(int currentPage) { - Paging paging = Paging.create(pageSize, currentPage); - SearchHits ruleHits = searchRules(query, paging, ruleFilterForActiveRuleSearch(query).must(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, activeRuleFilter(query)))); - List ruleIds = Lists.newArrayList(); - for (SearchHit ruleHit : ruleHits) { - ruleIds.add(Integer.valueOf(ruleHit.id())); - } - - if (!ruleIds.isEmpty()) { - SearchHits activeRuleHits = searchActiveRules(query, ruleIds, ActiveRuleDocument.FIELD_ID); - for (SearchHit activeRuleHit : activeRuleHits) { - activeRuleIds.add((Integer) activeRuleHit.field(ActiveRuleDocument.FIELD_ID).getValue()); - } - } - return ruleHits.getHits().length; - } - }.execute(); - return activeRuleIds; - } - - public long countProfileRules(ProfileRuleQuery query) { - return index.executeCount( - index.client() - .prepareCount(INDEX_RULES) - .setTypes(ESActiveRule.TYPE_ACTIVE_RULE) - .setQuery(QueryBuilders.filteredQuery( - QueryBuilders.matchAllQuery(), - activeRuleFilter(query).must(hasParentFilter(TYPE_RULE, ruleFilterForActiveRuleSearch(query)))) - ) - ); - } - - public long countProfileRules(int ruleId) { - return index.executeCount( - index.client() - .prepareCount(INDEX_RULES) - .setTypes(ESActiveRule.TYPE_ACTIVE_RULE) - .setQuery(QueryBuilders.filteredQuery( - QueryBuilders.matchAllQuery(), - boolFilter().must(hasParentFilter(TYPE_RULE, boolFilter().must(termFilter(RuleDocument.FIELD_ID, ruleId)))) - ) - )); - } - - public QProfileRuleResult searchInactives(ProfileRuleQuery query, Paging paging) { - SearchHits hits = searchRules(query, paging, ruleFilterForInactiveRuleSearch(query), FIELD_SOURCE, FIELD_PARENT); - List result = Lists.newArrayList(); - for (SearchHit hit : hits.getHits()) { - result.add(new QProfileRule(hit.sourceAsMap())); - } - return new QProfileRuleResult(result, PagingResult.create(paging.pageSize(), paging.pageIndex(), hits.getTotalHits())); - } - - public List searchInactiveProfileRuleIds(final ProfileRuleQuery query) { - final List ruleIds = newArrayList(); - - new Search(PAGE_SIZE) { - @Override - public int search(int currentPage) { - Paging paging = Paging.create(pageSize, currentPage); - SearchHits hits = searchRules(query, paging, ruleFilterForInactiveRuleSearch(query), RuleDocument.FIELD_ID); - for (SearchHit hit : hits.getHits()) { - ruleIds.add((Integer) hit.field(RuleDocument.FIELD_ID).getValue()); - } - return hits.getHits().length; - } - }.execute(); - - return ruleIds; - } - - public long countInactiveProfileRules(ProfileRuleQuery query) { - return index.executeCount(index.client().prepareCount(INDEX_RULES).setTypes(TYPE_RULE) - .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), - ruleFilterForInactiveRuleSearch(query)))); - } - - private SearchHits searchRules(ProfileRuleQuery query, Paging paging, FilterBuilder filterBuilder, String... fields) { - SearchRequestBuilder builder = index.client().prepareSearch(INDEX_RULES).setTypes(TYPE_RULE) - .setPostFilter(filterBuilder) - .setSize(paging.pageSize()) - .setFrom(paging.offset()); - if (fields.length > 0) { - builder.addFields(fields); - } - addOrder(query, builder); - return index.executeRequest(builder); - } - - private SearchHits searchActiveRules(ProfileRuleQuery query, List ruleIds, String... fields) { - SearchRequestBuilder activeRuleBuilder = index.client().prepareSearch(INDEX_RULES).setTypes(ESActiveRule.TYPE_ACTIVE_RULE) - .setPostFilter(boolFilter() - .must( - termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId()), - hasParentFilter(TYPE_RULE, termsFilter(RuleDocument.FIELD_ID, ruleIds)) - )) - .setSize(ruleIds.size()); - if (fields.length > 0) { - activeRuleBuilder.addFields(fields); - } - return index.executeRequest(activeRuleBuilder); - } - - private BoolFilterBuilder activeRuleFilter(ProfileRuleQuery query) { - BoolFilterBuilder filter = boolFilter().must(termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId())); - addMustTermOrTerms(filter, ActiveRuleDocument.FIELD_SEVERITY, query.severities()); - String inheritance = query.inheritance(); - if (inheritance != null) { - addMustTermOrTerms(filter, ActiveRuleDocument.FIELD_INHERITANCE, newArrayList(inheritance)); - } else if (query.noInheritance()) { - filter.mustNot(getTermOrTerms(ActiveRuleDocument.FIELD_INHERITANCE, newArrayList(QProfileRule.INHERITED, QProfileRule.OVERRIDES))); - } - return filter; - } - - private BoolFilterBuilder ruleFilterForActiveRuleSearch(ProfileRuleQuery query) { - BoolFilterBuilder result = boolFilter(); - - if (StringUtils.isNotBlank(query.language())) { - result.must(termFilter(RuleDocument.FIELD_LANGUAGE, query.language())); - } - - addMustTermOrTerms(result, RuleDocument.FIELD_REPOSITORY_KEY, query.repositoryKeys()); - if (query.statuses().isEmpty()) { - result.mustNot(termFilter(RuleDocument.FIELD_STATUS, Rule.STATUS_REMOVED)); - } else { - addMustTermOrTerms(result, RuleDocument.FIELD_STATUS, query.statuses()); - } - - for (String tag: query.tags()) { - result.must( - queryFilter( - multiMatchQuery(tag, RuleDocument.FIELD_ADMIN_TAGS, RuleDocument.FIELD_SYSTEM_TAGS))); - } - - if (StringUtils.isNotBlank(query.nameOrKey())) { - result.must( - queryFilter( - multiMatchQuery(query.nameOrKey().trim(), RuleDocument.FIELD_NAME, RuleDocument.FIELD_NAME + ".search", RuleDocument.FIELD_KEY) - .operator(Operator.AND))); - } - - return result; - } - - private BoolFilterBuilder ruleFilterForInactiveRuleSearch(ProfileRuleQuery query) { - BoolFilterBuilder filter = ruleFilterForActiveRuleSearch(query) - .mustNot(hasChildFilter(ESActiveRule.TYPE_ACTIVE_RULE, termFilter(ActiveRuleDocument.FIELD_PROFILE_ID, query.profileId()))); - addMustTermOrTerms(filter, RuleDocument.FIELD_SEVERITY, query.severities()); - - for (String tag: query.tags()) { - filter.must( - queryFilter( - multiMatchQuery(tag, RuleDocument.FIELD_ADMIN_TAGS, RuleDocument.FIELD_SYSTEM_TAGS))); - } - - return filter; - } - - private void addMustTermOrTerms(BoolFilterBuilder filter, String field, Collection terms) { - FilterBuilder termOrTerms = getTermOrTerms(field, terms); - if (termOrTerms != null) { - filter.must(termOrTerms); - } - } - - private FilterBuilder getTermOrTerms(String field, Collection terms) { - if (terms.isEmpty()) { - return null; - } else { - if (terms.size() == 1) { - return termFilter(field, terms.iterator().next()); - } else { - return termsFilter(field, terms.toArray()); - } - } - } - - private void addOrder(ProfileRuleQuery query, SearchRequestBuilder builder) { - SortOrder sortOrder = query.asc() ? SortOrder.ASC : SortOrder.DESC; - if (query.sort().equals(ProfileRuleQuery.SORT_BY_RULE_NAME)) { - builder.addSort(RuleDocument.FIELD_NAME + ".raw", sortOrder); - } else if (query.sort().equals(ProfileRuleQuery.SORT_BY_CREATION_DATE)) { - builder.addSort(RuleDocument.FIELD_CREATED_AT, sortOrder); - } - } - - private abstract static class Search { - - int pageSize = 100; - - protected Search(int pageSize) { - this.pageSize = pageSize; - } - - abstract int search(int currentPage); - - void execute() { - int currentPage = 1; - boolean hasNextPage = true; - while (hasNextPage) { - int resultSize = search(currentPage); - if (resultSize < pageSize) { - hasNextPage = false; - } else { - currentPage++; - } - } - } - } - - public static class QProfileRuleResult { - - private final List rules; - private final PagingResult paging; - - public QProfileRuleResult(List rules, PagingResult paging) { - this.rules = rules; - this.paging = paging; - } - - public List rules() { - return rules; - } - - public PagingResult paging() { - return paging; - } - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleParam.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleParam.java deleted file mode 100644 index b0757783610..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileRuleParam.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualityprofile; - -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.server.rule.RuleParam; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated -public class QProfileRuleParam { - - private RuleParam param; - private final String value; - - public QProfileRuleParam(RuleParam param, @Nullable String value) { - this.param = param; - this.value = value; - } - - @CheckForNull - public String value() { - return value; - } - - public String key() { - return param.key(); - } - - public String description() { - return param.description(); - } - - @CheckForNull - public String defaultValue() { - return param.defaultValue(); - } - - public RuleParamType type() { - return param.type(); - } - - @Override - public String toString() { - return new ReflectionToStringBuilder(this).toString(); - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java index 4336713a596..2f1703ed336 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java @@ -23,10 +23,7 @@ package org.sonar.server.qualityprofile; import com.google.common.base.Strings; import org.sonar.api.ServerComponent; import org.sonar.api.component.Component; -import org.sonar.api.rule.RuleKey; -import org.sonar.core.qualityprofile.db.QualityProfileKey; import org.sonar.server.exceptions.BadRequestException; -import org.sonar.server.paging.Paging; import org.sonar.server.user.UserSession; import org.sonar.server.util.Validation; @@ -35,10 +32,6 @@ import javax.annotation.Nullable; import java.util.List; import java.util.Map; -/** - * @deprecated to be dropped in 4.4 - */ -@Deprecated public class QProfiles implements ServerComponent { private static final String LANGUAGE_PARAM = "language"; @@ -47,18 +40,13 @@ public class QProfiles implements ServerComponent { private final QProfileProjectLookup projectLookup; private final QProfileLookup profileLookup; private final QProfileOperations operations; - private final QProfileActiveRuleOperations activeRuleOperations; - private final QProfileRuleLookup rules; public QProfiles(QProfileProjectOperations projectOperations, QProfileProjectLookup projectLookup, - QProfileLookup profileLookup, QProfileOperations operations, QProfileActiveRuleOperations activeRuleOperations, - QProfileRuleLookup rules) { + QProfileLookup profileLookup, QProfileOperations operations) { this.projectOperations = projectOperations; this.projectLookup = projectLookup; this.profileLookup = profileLookup; this.operations = operations; - this.activeRuleOperations = activeRuleOperations; - this.rules = rules; } public List allProfiles() { @@ -168,77 +156,15 @@ public class QProfiles implements ServerComponent { // PROFILE RULES - - @CheckForNull - public QProfileRule findByRule(int ruleId) { - return rules.findByRuleId(ruleId); - } - - @CheckForNull - public QProfileRule findByActiveRuleId(int activeRuleId) { - return rules.findByActiveRuleId(activeRuleId); - } - - @CheckForNull - public QProfileRule findByProfileAndRule(int profileId, int ruleId) { - return rules.findByProfileIdAndRuleId(profileId, ruleId); - } - - public QProfileRuleLookup.QProfileRuleResult searchProfileRules(ProfileRuleQuery query, Paging paging) { - return rules.search(query, paging); - } - - public long countProfileRules(ProfileRuleQuery query) { - return rules.countProfileRules(query); - } - - public QProfileRuleLookup.QProfileRuleResult searchInactiveProfileRules(ProfileRuleQuery query, Paging paging) { - return rules.searchInactives(query, paging); - } - - public long countInactiveProfileRules(ProfileRuleQuery query) { - return rules.countInactiveProfileRules(query); - } - public long countProfileRules(QProfile profile) { - return rules.countProfileRules(ProfileRuleQuery.create(profile.id())); + // TODO + return -1; } public long countOverridingProfileRules(QProfile profile) { - return rules.countProfileRules(ProfileRuleQuery.create(profile.id()).setInheritance(QProfileRule.OVERRIDES)); - } - - public void activateRule(QualityProfileKey profileKey, RuleKey rulekey, String severity) { - activeRuleOperations.activateRule(profileKey, rulekey, severity, UserSession.get()); - } - - public int bulkActivateRule(QualityProfileKey profileKey, ProfileRuleQuery query) { - return activeRuleOperations.activateRules(profileKey, query, UserSession.get()); - } - - public void deactivateRule(QualityProfileKey profileKey, RuleKey rulekey) { - activeRuleOperations.deactivateRule(profileKey, rulekey, UserSession.get()); - } - - public int bulkDeactivateRule(ProfileRuleQuery query) { - return activeRuleOperations.deactivateRules(query, UserSession.get()); - } - - public void updateActiveRuleParam(int activeRuleId, String key, @Nullable String value) { - activeRuleOperations.updateActiveRuleParam(activeRuleId, key, value, UserSession.get()); - } - - public void revertActiveRule(int activeRuleId) { - activeRuleOperations.revertActiveRule(activeRuleId, UserSession.get()); - } - - @CheckForNull - public QProfileRule parentProfileRule(QProfileRule rule) { - return rules.findParentProfileRule(rule); - } - - public long countActiveRules(int ruleId) { - return rules.countProfileRules(ruleId); + // TODO + return -1; + //return rules.countProfileRules(ProfileRuleQuery.create(profile.id()).setInheritance(QProfileRule.OVERRIDES)); } private void checkProfileNameParam(String name) { diff --git a/sonar-server/src/main/java/org/sonar/server/rule/RubyRuleService.java b/sonar-server/src/main/java/org/sonar/server/rule/RubyRuleService.java index a614efd3a31..a6112a97812 100644 --- a/sonar-server/src/main/java/org/sonar/server/rule/RubyRuleService.java +++ b/sonar-server/src/main/java/org/sonar/server/rule/RubyRuleService.java @@ -93,18 +93,6 @@ public class RubyRuleService implements ServerComponent, Startable { .setDebtRemediationOffset(Strings.emptyToNull((String) params.get("debtRemediationOffset")))); } - public Integer createCustomRule(int ruleId, @Nullable String name, @Nullable String severity, @Nullable String description, Map paramsByKey) { - return rules.createCustomRule(ruleId, name, severity, description, paramsByKey); - } - - public void updateCustomRule(int ruleId, @Nullable String name, @Nullable String severity, @Nullable String description, Map paramsByKey) { - rules.updateCustomRule(ruleId, name, severity, description, paramsByKey); - } - - public void deleteCustomRule(int ruleId) { - rules.deleteCustomRule(ruleId); - } - @Override public void start() { // used to force pico to instantiate the singleton at startup diff --git a/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java b/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java index 62ada1b5427..0f063f25b14 100644 --- a/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java +++ b/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java @@ -21,40 +21,28 @@ package org.sonar.server.rule; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Strings; -import com.google.common.collect.Iterables; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.ibatis.session.SqlSession; import org.sonar.api.ServerComponent; import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction; import org.sonar.api.utils.System2; -import org.sonar.check.Cardinality; import org.sonar.core.permission.GlobalPermissions; import org.sonar.core.persistence.DbSession; import org.sonar.core.persistence.MyBatis; -import org.sonar.core.qualityprofile.db.ActiveRuleDao; -import org.sonar.core.qualityprofile.db.ActiveRuleDto; import org.sonar.core.rule.RuleDao; import org.sonar.core.rule.RuleDto; -import org.sonar.core.rule.RuleParamDto; import org.sonar.core.technicaldebt.db.CharacteristicDao; import org.sonar.core.technicaldebt.db.CharacteristicDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; -import org.sonar.server.qualityprofile.ESActiveRule; import org.sonar.server.user.UserSession; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import java.util.Date; -import java.util.List; -import java.util.Map; - -import static com.google.common.collect.Lists.newArrayList; /** * @deprecated to be dropped in 4.4 @@ -63,166 +51,27 @@ import static com.google.common.collect.Lists.newArrayList; public class RuleOperations implements ServerComponent { private final MyBatis myBatis; - private final ActiveRuleDao activeRuleDao; private final RuleDao ruleDao; private final CharacteristicDao characteristicDao; - private final ESActiveRule esActiveRule; private final RuleRegistry ruleRegistry; private final System2 system; - public RuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, CharacteristicDao characteristicDao, - ESActiveRule esActiveRule, RuleRegistry ruleRegistry) { - this(myBatis, activeRuleDao, ruleDao, characteristicDao, esActiveRule, ruleRegistry, System2.INSTANCE); + public RuleOperations(MyBatis myBatis, RuleDao ruleDao, CharacteristicDao characteristicDao, + RuleRegistry ruleRegistry) { + this(myBatis, ruleDao, characteristicDao, ruleRegistry, System2.INSTANCE); } @VisibleForTesting - RuleOperations(MyBatis myBatis, ActiveRuleDao activeRuleDao, RuleDao ruleDao, CharacteristicDao characteristicDao, - ESActiveRule esActiveRule, RuleRegistry ruleRegistry, System2 system) { + RuleOperations(MyBatis myBatis, RuleDao ruleDao, CharacteristicDao characteristicDao, + RuleRegistry ruleRegistry, System2 system) { this.myBatis = myBatis; - this.activeRuleDao = activeRuleDao; this.ruleDao = ruleDao; this.characteristicDao = characteristicDao; - this.esActiveRule = esActiveRule; this.ruleRegistry = ruleRegistry; this.system = system; } - public void updateRuleNote(RuleDto rule, String note, UserSession userSession) { - checkPermission(userSession); - Date now = new Date(system.now()); - - SqlSession session = myBatis.openSession(false); - try { - if (rule.getNoteData() == null) { - rule.setNoteCreatedAt(now); - rule.setNoteUserLogin(getLoggedLogin(userSession)); - } - rule.setNoteUpdatedAt(now); - rule.setNoteData(note); - ruleDao.update(rule); - session.commit(); - - reindexRule(rule, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void deleteRuleNote(RuleDto rule, UserSession userSession) { - checkPermission(userSession); - - SqlSession session = myBatis.openSession(false); - try { - rule.setNoteData(null); - rule.setNoteUserLogin(null); - rule.setNoteCreatedAt(null); - rule.setNoteUpdatedAt(null); - ruleDao.update(rule); - session.commit(); - - reindexRule(rule, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public RuleDto createCustomRule(RuleDto templateRule, String name, String severity, String description, Map paramsByKey, - UserSession userSession) { - checkPermission(userSession); - DbSession session = myBatis.openSession(false); - try { - RuleDto rule = new RuleDto() - .setParentId(templateRule.getId()) - .setName(name) - .setDescription(description) - .setSeverity(severity) - .setRepositoryKey(templateRule.getRepositoryKey()) - .setConfigKey(templateRule.getConfigKey()) - .setRuleKey(templateRule.getRuleKey() + "_" + system.now()) - .setCardinality(Cardinality.SINGLE) - .setStatus(Rule.STATUS_READY) - .setLanguage(templateRule.getLanguage()) - .setDefaultSubCharacteristicId(templateRule.getDefaultSubCharacteristicId()) - .setDefaultRemediationFunction(templateRule.getDefaultRemediationFunction()) - .setDefaultRemediationCoefficient(templateRule.getDefaultRemediationCoefficient()) - .setDefaultRemediationOffset(templateRule.getDefaultRemediationOffset()); - ruleDao.insert(rule, session); - - List templateRuleParams = ruleDao.selectParametersByRuleId(templateRule.getId(), session); - for (RuleParamDto templateRuleParam : templateRuleParams) { - String key = templateRuleParam.getName(); - String value = paramsByKey.get(key); - - RuleParamDto param = new RuleParamDto() - .setRuleId(rule.getId()) - .setName(key) - .setDescription(templateRuleParam.getDescription()) - .setType(templateRuleParam.getType()) - .setDefaultValue(Strings.emptyToNull(value)); - ruleDao.insert(param, session); - } - - session.commit(); - reindexRule(rule, session); - return rule; - } finally { - MyBatis.closeQuietly(session); - } - } - - public void updateCustomRule(RuleDto rule, String name, String severity, String description, Map paramsByKey, - UserSession userSession) { - checkPermission(userSession); - DbSession session = myBatis.openSession(false); - try { - rule.setName(name) - .setDescription(description) - .setSeverity(severity) - .setUpdatedAt(new Date(system.now())); - ruleDao.update(rule, session); - - List ruleParams = ruleDao.selectParametersByRuleId(rule.getId(), session); - for (RuleParamDto ruleParam : ruleParams) { - String value = paramsByKey.get(ruleParam.getName()); - ruleParam.setDefaultValue(Strings.emptyToNull(value)); - ruleDao.update(ruleParam, session); - } - session.commit(); - reindexRule(rule, session); - } finally { - MyBatis.closeQuietly(session); - } - } - - public void deleteCustomRule(RuleDto rule, UserSession userSession) { - checkPermission(userSession); - DbSession session = myBatis.openSession(false); - try { - // Set status REMOVED on rule - rule.setStatus(Rule.STATUS_REMOVED) - .setUpdatedAt(new Date(system.now())); - ruleDao.update(rule, session); - session.commit(); - reindexRule(rule, session); - - // Delete all active rules and active rule params linked to the rule - List activeRules = activeRuleDao.selectByRuleId(rule.getId()); - for (ActiveRuleDto activeRule : activeRules) { - activeRuleDao.deleteParameters(activeRule.getId(), session); - } - activeRuleDao.deleteFromRule(rule.getId(), session); - session.commit(); - esActiveRule.deleteActiveRules(newArrayList(Iterables.transform(activeRules, new Function() { - @Override - public Integer apply(ActiveRuleDto input) { - return input.getId(); - } - }))); - } finally { - MyBatis.closeQuietly(session); - } - } public void updateRule(RuleChange ruleChange, UserSession userSession) { checkPermission(userSession); @@ -332,14 +181,6 @@ public class RuleOperations implements ServerComponent { userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN); } - private String getLoggedLogin(UserSession userSession) { - String login = userSession.login(); - if (Strings.isNullOrEmpty(login)) { - throw new BadRequestException("User login can't be null"); - } - return login; - } - public static class RuleChange { private RuleKey ruleKey; private String debtCharacteristicKey; diff --git a/sonar-server/src/main/java/org/sonar/server/rule/Rules.java b/sonar-server/src/main/java/org/sonar/server/rule/Rules.java index 7d909603deb..2adad3bc89e 100644 --- a/sonar-server/src/main/java/org/sonar/server/rule/Rules.java +++ b/sonar-server/src/main/java/org/sonar/server/rule/Rules.java @@ -19,28 +19,12 @@ */ package org.sonar.server.rule; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; import org.sonar.api.ServerExtension; import org.sonar.api.rule.RuleKey; -import org.sonar.core.persistence.DbSession; -import org.sonar.core.persistence.MyBatis; -import org.sonar.core.rule.RuleDto; -import org.sonar.server.exceptions.BadRequestException; -import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.paging.PagedResult; -import org.sonar.server.qualityprofile.QProfileValidations; -import org.sonar.server.rule2.persistence.RuleDao; import org.sonar.server.user.UserSession; -import org.sonar.server.util.RubyUtils; -import org.sonar.server.util.Validation; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import java.util.List; -import java.util.Map; - -import static com.google.common.collect.Lists.newArrayList; /** * @deprecated to be dropped in 4.4 @@ -48,16 +32,12 @@ import static com.google.common.collect.Lists.newArrayList; @Deprecated public class Rules implements ServerExtension { - private final RuleDao ruleDao; private final RuleOperations ruleOperations; private final RuleRegistry ruleRegistry; - private final MyBatis myBatis; - public Rules(MyBatis myBatis, RuleDao ruleDao, RuleOperations ruleOperations, RuleRegistry ruleRegistry) { + public Rules(RuleOperations ruleOperations, RuleRegistry ruleRegistry) { this.ruleOperations = ruleOperations; - this.ruleDao = ruleDao; this.ruleRegistry = ruleRegistry; - this.myBatis = myBatis; } /** @@ -67,45 +47,6 @@ public class Rules implements ServerExtension { ruleOperations.updateRule(ruleChange, UserSession.get()); } - public void updateRuleNote(int ruleId, String note) { - RuleDto rule = findRuleNotNull(ruleId); - String sanitizedNote = Strings.emptyToNull(note); - if (sanitizedNote != null) { - ruleOperations.updateRuleNote(rule, note, UserSession.get()); - } else { - ruleOperations.deleteRuleNote(rule, UserSession.get()); - } - } - - /** - * Create custom rule - */ - public Integer createCustomRule(int ruleId, @Nullable String name, @Nullable String severity, @Nullable String description, Map paramsByKey) { - RuleDto rule = findRuleNotNull(ruleId); - validateRule(null, name, severity, description); - RuleDto newRule = ruleOperations.createCustomRule(rule, name, severity, description, paramsByKey, UserSession.get()); - return newRule.getId(); - } - - /** - * Update custom rule - */ - public void updateCustomRule(int ruleId, @Nullable String name, @Nullable String severity, @Nullable String description, Map paramsByKey) { - RuleDto rule = findRuleNotNull(ruleId); - validateRuleParent(rule); - validateRule(ruleId, name, severity, description); - ruleOperations.updateCustomRule(rule, name, severity, description, paramsByKey, UserSession.get()); - } - - /** - * Delete custom rule - */ - public void deleteCustomRule(int ruleId) { - RuleDto rule = findRuleNotNull(ruleId); - validateRuleParent(rule); - ruleOperations.deleteCustomRule(rule, UserSession.get()); - } - @CheckForNull public Rule findByKey(RuleKey key) { return ruleRegistry.findByKey(key); @@ -115,50 +56,4 @@ public class Rules implements ServerExtension { return ruleRegistry.find(query); } - // - // Rule validation - // - - private void validateRule(@Nullable Integer updatingRuleId, @Nullable String name, @Nullable String severity, @Nullable String description) { - List messages = newArrayList(); - if (Strings.isNullOrEmpty(name)) { - messages.add(BadRequestException.Message.ofL10n(Validation.CANT_BE_EMPTY_MESSAGE, "Name")); - } else { - checkRuleNotAlreadyExists(updatingRuleId, name, messages); - } - if (Strings.isNullOrEmpty(description)) { - messages.add(BadRequestException.Message.ofL10n(Validation.CANT_BE_EMPTY_MESSAGE, "Description")); - } - if (Strings.isNullOrEmpty(severity)) { - messages.add(BadRequestException.Message.ofL10n(Validation.CANT_BE_EMPTY_MESSAGE, "Severity")); - } - if (!messages.isEmpty()) { - throw BadRequestException.of(messages); - } - } - - private void validateRuleParent(RuleDto rule) { - if (rule.getParentId() == null) { - throw new NotFoundException("Unknown rule"); - } - } - - private RuleDto findRuleNotNull(int ruleId) { - DbSession session = myBatis.openSession(false); - RuleDto rule = ruleDao.getById(ruleId, session); - QProfileValidations.checkRuleIsNotNull(rule); - session.close(); - return rule; - } - - - private void checkRuleNotAlreadyExists(@Nullable Integer updatingRuleId, String name, List messages) { - DbSession session = myBatis.openSession(false); - RuleDto existingRule = ruleDao.getByName(name, session); - boolean isModifyingCurrentRule = updatingRuleId != null && existingRule != null && existingRule.getId().equals(updatingRuleId); - if (!isModifyingCurrentRule && existingRule != null) { - messages.add(BadRequestException.Message.ofL10n(Validation.IS_ALREADY_USED_MESSAGE, "Name")); - } - session.close(); - } } diff --git a/sonar-server/src/main/java/org/sonar/server/startup/RegisterQualityProfiles.java b/sonar-server/src/main/java/org/sonar/server/startup/RegisterQualityProfiles.java deleted file mode 100644 index c8258568c22..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/startup/RegisterQualityProfiles.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube 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. - * - * SonarQube 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.base.Function; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Multimaps; -import com.google.common.collect.Sets; -import org.apache.commons.lang.StringUtils; -import org.apache.ibatis.session.SqlSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.profiles.ProfileDefinition; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.utils.SonarException; -import org.sonar.api.utils.TimeProfiler; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.core.persistence.DbSession; -import org.sonar.core.persistence.MyBatis; -import org.sonar.core.qualityprofile.db.QualityProfileKey; -import org.sonar.core.template.LoadedTemplateDao; -import org.sonar.core.template.LoadedTemplateDto; -import org.sonar.jpa.session.DatabaseSessionFactory; -import org.sonar.server.platform.PersistentSettings; -import org.sonar.server.qualityprofile.DefaultProfilesCache; -import org.sonar.server.qualityprofile.ESActiveRule; -import org.sonar.server.qualityprofile.QProfile; -import org.sonar.server.qualityprofile.QProfileBackup; -import org.sonar.server.qualityprofile.QProfileLookup; -import org.sonar.server.qualityprofile.QProfileOperations; -import org.sonar.server.rule2.RegisterRules; -import org.sonar.server.user.UserSession; - -import javax.annotation.Nullable; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class RegisterQualityProfiles { - - private static final Logger LOGGER = LoggerFactory.getLogger(RegisterQualityProfiles.class); - private static final String DEFAULT_PROFILE_NAME = "Sonar way"; - - private final LoadedTemplateDao loadedTemplateDao; - private final QProfileBackup qProfileBackup; - private final QProfileOperations qProfileOperations; - private final QProfileLookup qProfileLookup; - private final ESActiveRule esActiveRule; - private final PersistentSettings settings; - private final List definitions; - private final DefaultProfilesCache defaultProfilesCache; - private final DatabaseSessionFactory sessionFactory; - private final MyBatis myBatis; - - public RegisterQualityProfiles(DatabaseSessionFactory sessionFactory, - MyBatis myBatis, - PersistentSettings settings, - ESActiveRule esActiveRule, - LoadedTemplateDao loadedTemplateDao, - QProfileBackup qProfileBackup, - QProfileOperations qProfileOperations, - QProfileLookup qProfileLookup, - DefaultProfilesCache defaultProfilesCache, - RegisterRules registerRulesBefore) { - this(sessionFactory, myBatis, settings, esActiveRule, loadedTemplateDao, qProfileBackup, qProfileOperations, qProfileLookup, defaultProfilesCache, registerRulesBefore, - Collections.emptyList()); - } - - public RegisterQualityProfiles(DatabaseSessionFactory sessionFactory, - MyBatis myBatis, - PersistentSettings settings, - ESActiveRule esActiveRule, - LoadedTemplateDao loadedTemplateDao, - QProfileBackup qProfileBackup, - QProfileOperations qProfileOperations, - QProfileLookup qProfileLookup, - DefaultProfilesCache defaultProfilesCache, - RegisterRules registerRulesBefore, - List definitions) { - this.sessionFactory = sessionFactory; - this.myBatis = myBatis; - this.settings = settings; - this.esActiveRule = esActiveRule; - this.qProfileBackup = qProfileBackup; - this.qProfileOperations = qProfileOperations; - this.qProfileLookup = qProfileLookup; - this.defaultProfilesCache = defaultProfilesCache; - this.definitions = definitions; - this.loadedTemplateDao = loadedTemplateDao; - } - - public void start() { - TimeProfiler profiler = new TimeProfiler(LOGGER).start("Register Quality Profiles"); - - // Hibernate session can contain an invalid cache of rules. - // As long ProfileDefinition API will be used, then we'll have to use this commit as Hibernate is used by plugin to load rules when creating their profiles. - sessionFactory.getSession().commit(); - - DbSession session = myBatis.openSession(false); - try { - ListMultimap profilesByLanguage = profilesByLanguage(); - for (String language : profilesByLanguage.keySet()) { - List profiles = profilesByLanguage.get(language); - verifyLanguage(language, profiles); - - for (Map.Entry> entry : profilesByName(profiles).entrySet()) { - String name = entry.getKey(); - if (shouldRegister(language, name, session)) { - register(language, name, entry.getValue(), session); - } - defaultProfilesCache.put(language, name); - } - setDefault(language, profiles, session); - } - session.commit(); - esActiveRule.bulkRegisterActiveRules(); - } finally { - MyBatis.closeQuietly(session); - profiler.stop(); - } - } - - private static void verifyLanguage(String language, List profiles) { - if (profiles.isEmpty()) { - LOGGER.warn("No Quality Profile defined for language: " + language); - } - - Set defaultProfileNames = defaultProfileNames(profiles); - if (defaultProfileNames.size() > 1) { - throw new SonarException("Several Quality Profiles are flagged as default for the language " + language + ": " + defaultProfileNames); - } - } - - private void register(String language, String name, Collection profiles, DbSession session) { - LOGGER.info("Register " + language + " profile: " + name); - - QProfile profile = qProfileLookup.profile(name, language, session); - if (profile != null) { - qProfileOperations.deleteProfile(profile, session); - } - profile = qProfileOperations.newProfile(name, language, true, UserSession.get(), session); - - for (RulesProfile currentRulesProfile : profiles) { - qProfileBackup.restoreFromActiveRules( - QualityProfileKey.of(profile.name(),profile.language()), - currentRulesProfile, session); - } - - loadedTemplateDao.insert(new LoadedTemplateDto(templateKey(language, name), LoadedTemplateDto.QUALITY_PROFILE_TYPE), session); - } - - private void setDefault(String language, List profiles, SqlSession session) { - String propertyKey = "sonar.profile." + language; - if (settings.getString(propertyKey) == null) { - String defaultProfileName = defaultProfileName(profiles); - LOGGER.info("Set default " + language + " profile: " + defaultProfileName); - settings.saveProperty(propertyKey, defaultProfileName); - } - } - - /** - * @return profiles by language - */ - private ListMultimap profilesByLanguage() { - ListMultimap byLang = ArrayListMultimap.create(); - for (ProfileDefinition definition : definitions) { - ValidationMessages validation = ValidationMessages.create(); - RulesProfile profile = definition.createProfile(validation); - validation.log(LOGGER); - if (profile != null && !validation.hasErrors()) { - byLang.put(StringUtils.lowerCase(profile.getLanguage()), profile); - } - } - return byLang; - } - - private static Map> profilesByName(List profiles) { - return Multimaps.index(profiles, new Function() { - public String apply(@Nullable RulesProfile profile) { - return profile != null ? profile.getName() : null; - } - }).asMap(); - } - - private static String defaultProfileName(List profiles) { - String defaultName = null; - boolean hasSonarWay = false; - - for (RulesProfile profile : profiles) { - if (profile.getDefaultProfile()) { - defaultName = profile.getName(); - } else if (DEFAULT_PROFILE_NAME.equals(profile.getName())) { - hasSonarWay = true; - } - } - - if (StringUtils.isBlank(defaultName) && !hasSonarWay && !profiles.isEmpty()) { - defaultName = profiles.get(0).getName(); - } - - return StringUtils.defaultIfBlank(defaultName, DEFAULT_PROFILE_NAME); - } - - private static Set defaultProfileNames(Collection profiles) { - Set names = Sets.newHashSet(); - for (RulesProfile profile : profiles) { - if (profile.getDefaultProfile()) { - names.add(profile.getName()); - } - } - return names; - } - - private boolean shouldRegister(String language, String profileName, SqlSession session) { - return loadedTemplateDao.countByTypeAndKey(LoadedTemplateDto.QUALITY_PROFILE_TYPE, templateKey(language, profileName), session) == 0; - } - - private static String templateKey(String language, String profileName) { - return StringUtils.lowerCase(language) + ":" + profileName; - } -} diff --git a/sonar-server/src/main/resources/org/sonar/server/es/config/mappings/active_rule_mapping.json b/sonar-server/src/main/resources/org/sonar/server/es/config/mappings/active_rule_mapping.json deleted file mode 100644 index b471e1c88e7..00000000000 --- a/sonar-server/src/main/resources/org/sonar/server/es/config/mappings/active_rule_mapping.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "active_rule": { - "_id": { - "path": "id" - }, - "_parent": { - "type": "rule" - }, - "properties": { - "id": { - "type": "integer", - "index": "not_analyzed" - }, - "severity": { - "type": "string", - "index": "not_analyzed" - }, - "profileId": { - "type": "integer", - "index": "not_analyzed" - }, - "activeRuleParentId": { - "type": "integer", - "index": "not_analyzed" - }, - "inheritance": { - "type": "string", - "index": "not_analyzed" - }, - "note": { - "properties": { - "data": { - "type": "string", - "index": "no" - }, - "userLogin": { - "type": "string", - "index": "no" - }, - "createdAt": { - "type": "date", - "format": "date_optional_time" - }, - "updatedAt": { - "type": "date", - "format": "date_optional_time" - } - } - }, - "params": { - "properties": { - "key": { - "type": "string", - "index": "no" - }, - "value": { - "type": "string", - "index": "no" - } - } - } - } - } -} diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/rules_configuration_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/rules_configuration_controller.rb index d4f6ddeb7c5..52c95c7d03d 100644 --- a/sonar-server/src/main/webapp/WEB-INF/app/controllers/rules_configuration_controller.rb +++ b/sonar-server/src/main/webapp/WEB-INF/app/controllers/rules_configuration_controller.rb @@ -17,210 +17,18 @@ # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # -require 'cgi' require 'java' class RulesConfigurationController < ApplicationController SECTION=Navigation::SECTION_QUALITY_PROFILES - STATUS_ACTIVE = "ACTIVE" - STATUS_INACTIVE = "INACTIVE" - - ANY_SELECTION = [] RULE_PRIORITIES = Sonar::RulePriority.as_options.reverse - - # - # - # POST /rules_configuration/revert_rule?id=&active_rule_id= - # - # - def revert_rule - verify_post_request - require_parameters :id, :active_rule_id - - active_rule_id = params[:active_rule_id].to_i - call_backend do - Internal.quality_profiles.revertActiveRule(active_rule_id) - end - - redirect_to request.query_parameters.merge({:action => 'index', :id => params[:id].to_i, :commit => nil}) - end - - - # - # - # POST /rules_configuration/activate_rule?id=&rule_id=&level= - # - # If the parameter "level" is blank or null, then the rule is removed from the profile. - # - # - def activate_rule - verify_post_request - require_parameters :id, :rule_id - - rule = nil - profile_id = params[:id].to_i - rule_id = params[:rule_id].to_i - call_backend do - severity = params[:level] - if severity.blank? - # deactivate the rule - Internal.quality_profiles.deactivateRule(profile_id, rule_id) - rule = Internal.quality_profiles.findByRule(rule_id) - else - # activate the rule - Internal.quality_profiles.activateRule(profile_id, rule_id, severity) - rule = Internal.quality_profiles.findByProfileAndRule(profile_id, rule_id) - end - end - - profile = Internal.quality_profiles.profile(profile_id) - parent_profile = Internal.quality_profiles.parent(profile) - - render :update do |page| - page.replace_html("rule_#{rule.id}", :partial => 'rule', :object => rule, :locals => {:rule => rule, :profile => profile, :parent_profile => parent_profile}) - page.assign('localModifications', true) - end - end - - - # - # - # GET /rules_configuration/new/?rule_id= - # - # - def new - # form to duplicate a rule - require_parameters :id, :rule_id - @profile = Internal.quality_profiles.profile(params[:id].to_i) - not_found('Profile not found') unless @profile - add_breadcrumbs ProfilesController::root_breadcrumb, Api::Utils.language_name(@profile.language), - {:name => @profile.name, :url => {:controller => 'rules_configuration', :action => 'index', :id => @profile.id}} - - @rule = Internal.quality_profiles.findByRule(params[:rule_id].to_i) - end - - # deprecated since 2.3 def export redirect_to request.query_parameters.merge({:controller => 'profiles', :action => 'export'}) end - # - # - # GET /rules_configuration/new/?rule_id= - # - # - def edit - # form to edit a rule - require_parameters :id, :rule_id - - call_backend do - @profile = Internal.quality_profiles.profile(params[:id].to_i) - not_found('Profile not found') unless @profile - @rule = Internal.quality_profiles.findByRule(params[:rule_id].to_i) - if @rule.templateId().nil? - redirect_to :action => 'index', :id => params[:id] - else - @parent_rule = Internal.quality_profiles.findByRule(@rule.templateId()) - @active_rules = Internal.quality_profiles.countActiveRules(@rule.id()).to_i - end - end - end - - - # - # - # POST /rules_configuration/bulk_edit?id=&&bulk_action= - # - # Values of the parameter 'bulk_action' : - # - 'activate' : activate all the selected rules with their default priority - # - 'deactivate' : deactivate all the selected rules - # - # - def bulk_edit - verify_post_request - access_denied unless has_role?(:profileadmin) - require_parameters :id, :bulk_action - - stop_watch = Internal.profiling.start("rules", "BASIC") - @profile = Internal.quality_profiles.profile(params[:id].to_i) - not_found('Profile not found') unless @profile - init_params - criteria = init_criteria - query = Java::OrgSonarServerQualityprofile::ProfileRuleQuery::parse(criteria.to_java) - activation = params[:rule_activation] || STATUS_ACTIVE - case params[:bulk_action] - when 'activate' - count = Internal.quality_profiles.bulkActivateRule(query) - stop_watch.stop("Activate #{count} rules with criteria #{criteria.to_json}") - - flash[:notice]=message('rules_configuration.x_rules_have_been_activated', :params => count) - activation=STATUS_ACTIVE if activation==STATUS_INACTIVE - - when 'deactivate' - count = Internal.quality_profiles.bulkDeactivateRule(query) - stop_watch.stop("Deactivate #{count} rules with criteria #{criteria.to_json}") - - flash[:notice]=message('rules_configuration.x_rules_have_been_deactivated', :params => count) - activation=STATUS_INACTIVE if activation==STATUS_ACTIVE - end - - url_parameters=request.query_parameters.merge({:action => 'index', :bulk_action => nil, :id => @profile.id, :rule_activation => activation}) - redirect_to url_parameters - end - - private - - def init_params - @id = params[:id] - @priorities = filter_any(params[:priorities]) || [''] - @repositories = filter_any(params[:repositories]) || [''] - @activation = params[:rule_activation] || STATUS_ACTIVE - @inheritance = params[:inheritance] || 'any' - @status = params[:status] - @tags = filter_any(params[:tags]) || [''] - @sort_by = !params[:sort_by].blank? ? params[:sort_by] : Rule::SORT_BY_RULE_NAME - @searchtext = params[:searchtext] - end - - def filter_any(array) - if array && array.size>1 && array.include?('') - array=[''] #keep only 'any' - end - array - end - - def init_criteria() - if @sort_by == Rule::SORT_BY_RULE_NAME - asc = true - elsif @sort_by == Rule::SORT_BY_CREATION_DATE - asc = false - else - asc = true - end - {"profileId" => @profile.id.to_i, "activation" => @activation, "severities" => @priorities, "inheritance" => @inheritance, "statuses" => @status, - "repositoryKeys" => @repositories, "nameOrKey" => @searchtext, "include_parameters_and_notes" => true, "language" => @profile.language, "tags" => @tags, - "sort_by" => @sort_by, "asc" => asc} - end - - def criteria_params - new_params = params.clone - new_params.delete('controller') - new_params.delete('action') - new_params - end - - def tag_selection_for_rule(rule) - Internal.rule_tags.listAllTags().to_a.sort.collect do |tag| - { - :value => tag, - :selected => (rule.systemTags.contains?(tag) || rule.adminTags.contains?(tag)), - :read_only => rule.systemTags.contains?(tag) - } - end - end end diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule.html.erb deleted file mode 100644 index 028c44403a0..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule.html.erb +++ /dev/null @@ -1,125 +0,0 @@ -<% #locals = rule, profile, parent_profile -%> -<% is_activated = !rule.activeRuleId.nil? %> - - -
- <% enable_modification = profiles_administrator? - select_box_id = "levels_select_#{rule.id}" - check_box_id = "levels_check_#{rule.id}" - activate_rule = "$j.ajax({url:'#{ApplicationController.root_context}/rules_configuration/activate_rule/#{profile.id}?rule_id=#{rule.id}',type: 'POST', - beforeSend: function(request){$j('#levels_#{rule.id}').replaceWith('');}, - data: 'level='+ get_level_for_rule($j('#levels_select_#{rule.id} :selected'),$j('#levels_check_#{rule.id}'))});" - changel_level = "if($j('#levels_check_#{rule.id}').prop('checked')) - {$j.ajax({url:'#{ApplicationController.root_context}/rules_configuration/activate_rule/#{profile.id}?rule_id=#{rule.id}',type:'POST', - beforeSend:function(request){$j('#levels_#{rule.id}').replaceWith('');}, - data:'level='+$j('#levels_select_#{rule.id} :selected').val()})}" - %> - - <%= check_box_tag(check_box_id, 'yes', is_activated, :onclick => activate_rule, :disabled => !enable_modification || rule.inherited? || rule.overrides?) %> - <%= select_tag(select_box_id, options_for_select(RulesConfigurationController::RULE_PRIORITIES, rule.severity), - {:onchange => changel_level, :disabled => (!(enable_modification) || !is_activated)}) %> - - <% if rule.inherited? %> - Inherited from parent - <% elsif rule.overrides? %> - Overrides parent definition - <% end %> -
- - - -
<%= link_to_function("#{h rule.name}", nil, :class => "") do |page| - page.toggle "desc_#{rule.id}" - end - %>
- - <% unless rule.status == "READY" %> -
- <% if rule.status == "BETA" %> - <%= message('rules.status.beta') %> - <% elsif rule.status == "DEPRECATED" %> - <%= message('rules.status.deprecated') %> - <% end %> -
- <% end %> -
- <%= render :partial => 'rule_tags', :locals => {:rule => rule} -%> -
- - -
- - -
- <%= render :partial => 'rule_note', :locals => {:rule => rule} %> -
- - <% if profiles_administrator? %> - - - <% end %> - - - <% - parent_active_rule = Internal.quality_profiles.parentProfileRule(rule) if (rule.inherited? || rule.overrides?) - if parent_active_rule || !rule.params.empty? - %> - - <% - if parent_active_rule - parent_active_rule_link = link_to parent_profile.name, :controller => 'rules_configuration', :action => 'index', - :id => parent_profile.id, :rule_id => rule.id, :anchor => 'rule' + rule.id.to_s - %> - - - - <% end %> - <% - rule.params.to_a.sort_by { |parameter| parameter.key}.each do |parameter| - %> - - <%= render :partial => 'rule_param', :object => nil, - :locals => {:parameter => parameter, :profile => profile, :rule => rule, :parent_active_rule => parent_active_rule} %> - - <% - end - %> -
- <%= message(rule.inherited? ? 'rules_configuration.rule_inherited_from_profile_x' : 'rules_configuration.rule_overriding_from_profile_x', :params => parent_active_rule_link) -%> - <% if parent_active_rule.severity != rule.severity %> - Overrides parent definition - <%= message('rules_configuration.original_severity') -%>: <%= parent_active_rule.severity -%> - <% end %> - <% if profiles_administrator? && rule.overrides? %> -
- -
- <% end %> -
- <% end %> - - <% if profiles_administrator? %> - <% if rule.template? %> - <%= link_to message('rules_configuration.copy_rule'), {:action => 'new', :id => profile.id, :rule_id => rule.id}, :id => "copy-#{u rule_key(rule)}", :class => 'link-action spacer-right' %> - <% end %> - <% if rule.editable? %> - <%= link_to message('rules_configuration.edit_rule'), {:action => 'edit', :id => profile.id, :rule_id => rule.id}, :class => 'link-action spacer-right' %> - <% end %> - <% end %> - -
- <%= message('rules_configuration.repository') %>: <%= rule.repositoryKey %> -  <%= image_tag 'sep12.png' -%>  - <%= message('key') %>: <%= rule.key %> - - <% if rule.createdAt -%> -  <%= image_tag 'sep12.png' -%>  - <%= message('rules_configuration.available_since') %> <%= human_short_date(Api::Utils.java_to_ruby_datetime(rule.createdAt)) %> - <% end %> -
-
- diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_note.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_note.html.erb deleted file mode 100644 index 7b7c0aa7cdc..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_note.html.erb +++ /dev/null @@ -1,68 +0,0 @@ -<% #locals = rule - note = rule.ruleNote - note_detail_div_id = "nd_" + rule.id.to_s - note_extend_link_id = "nel_" + rule.id.to_s - note_form_div_id = "nf_" + rule.id.to_s - note_textarea_id = "nt_" + rule.id.to_s - submit_note_update_button_id = "snub_" + rule.id.to_s -%> - -
-
- <% unless rule.description.nil? %> - <% if rule.description.strip.start_with?('

') %> - <%= Internal.text.interpretMacros(rule.description) %> - <% else %> -

<%= Internal.text.interpretMacros(rule.description) %>

- <% end %> - <% end %> -
- - <% if rule.ruleNote && !rule.ruleNote.data.strip.blank? %> -

<%= html_text(rule.ruleNote.data) -%>

- <% end %> - - <% if profiles_administrator? %> - - <% end %> - -
- -<% if profiles_administrator? %> - -<% end %> diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_param.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_param.html.erb deleted file mode 100644 index a92faee7ee1..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_param.html.erb +++ /dev/null @@ -1,47 +0,0 @@ -<% # locals = rule, profile, parameter, parent_active_rule - param_id = "#{rule.id}#{parameter.key}" - # Display default value only for inactive rules - param_value = parameter.default_value if !rule.activeRuleId - param_value = parameter.value if !param_value - active_rule_id = rule.activeRuleId - read_only = rule.activeRuleId.nil? || !profiles_administrator? -%> - -<%= parameter.key -%> - - -
- - - - <%= param_value_input(rule, parameter, param_value, :disabled => read_only) -%> - - <% unless read_only %> - <%= submit_tag(message('update_verb'), :id => 'submit_' + param_id.to_s) %> - - <% end %> - - <% if !rule.nil? && rule.overrides? && parent_active_rule - ancestor_param = parent_active_rule.params.to_a.find {|param| param.key() == parameter.key} - ancestor_value = ancestor_param && ancestor_param.value ? ancestor_param.value : '' - %> - <% if ancestor_value != param_value %> - Overrides parent definition - - <%= message('rules_configuration.original_value') -%>: <%= ancestor_value.blank? ? '(' + message('rules_configuration.parent_parameter.empty') + ')' : ancestor_value -%> - - <% end %> - <% end %> - -
<%= h(parameter.description || "") -%> <%= ('(' + readable_type(parameter.type) + ')') if !readable_type(parameter.type).empty? -%>
- -
- diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_tags.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_tags.html.erb deleted file mode 100644 index 9fc754da471..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_rule_tags.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -<% #locals = rule -%> -<% unless rule.systemTags.isEmpty && rule.adminTags.isEmpty %> - <% ([] + rule.systemTags + rule.adminTags).each do |tag| %> - - <%= link_to tag, url_for( params.merge({ 'tags[]' => tag, 'searchtext' => '' }) ) -%> - - <% end %> -<% end %> diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_select_tags.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_select_tags.html.erb deleted file mode 100644 index 1066ff7103e..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/views/rules_configuration/_select_tags.html.erb +++ /dev/null @@ -1,54 +0,0 @@ -<% #locals = rule, tags, profile_id -%> - - -
- <%= hidden_field_tag :rule_id, rule.id -%> - <%= hidden_field_tag :profile_id, profile_id -%> -
- - -
-
- -