diff options
author | simonbrandhof <simon.brandhof@gmail.com> | 2010-09-14 13:00:25 +0000 |
---|---|---|
committer | simonbrandhof <simon.brandhof@gmail.com> | 2010-09-14 13:00:25 +0000 |
commit | ddcc6272a62c245618d7797712062c96ff7ad3d4 (patch) | |
tree | 2465df13f82cbc664a51b4b7439c570b50e2146e /sonar-deprecated | |
parent | 2f54216f77f9580f56891d662e56a5d151ce1a2a (diff) | |
download | sonarqube-ddcc6272a62c245618d7797712062c96ff7ad3d4.tar.gz sonarqube-ddcc6272a62c245618d7797712062c96ff7ad3d4.zip |
move deprecated rule API to sonar-deprecated
Diffstat (limited to 'sonar-deprecated')
28 files changed, 1978 insertions, 0 deletions
diff --git a/sonar-deprecated/src/main/java/org/sonar/api/batch/AbstractViolationsStaxParser.java b/sonar-deprecated/src/main/java/org/sonar/api/batch/AbstractViolationsStaxParser.java new file mode 100644 index 00000000000..9a7432f16b1 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/batch/AbstractViolationsStaxParser.java @@ -0,0 +1,194 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.batch; + +import static org.apache.commons.lang.StringUtils.isNotBlank; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.text.ParseException; + +import javax.xml.stream.XMLStreamException; + +import org.apache.commons.io.IOUtils; +import org.codehaus.staxmate.in.SMEvent; +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.codehaus.staxmate.in.SMInputCursor; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Resource; +import org.sonar.api.rules.Rule; +import org.sonar.api.rules.RulesManager; +import org.sonar.api.rules.Violation; +import org.sonar.api.utils.ParsingUtils; +import org.sonar.api.utils.StaxParser; + +/** + * @since 1.10 + * @deprecated since 2.3. Too much "black-box". + */ +@Deprecated +public abstract class AbstractViolationsStaxParser { + + protected RulesManager rulesManager; + protected SensorContext context; + protected boolean doSaveViolationsOnUnexistedResource = true; + + /** + * @deprecated since 1.11. + */ + @Deprecated + protected AbstractViolationsStaxParser(SensorContext context, RulesManager rulesManager, RulesProfile profile) { + this.rulesManager = rulesManager; + this.context = context; + } + + protected AbstractViolationsStaxParser(SensorContext context, RulesManager rulesManager) { + this.rulesManager = rulesManager; + this.context = context; + } + + /** + * Cursor for child resources to parse, the returned input cursor should be filtered on SMEvent.START_ELEMENT for optimal perfs + * + * @param rootCursor + * the root xml doc cursor + * @return a cursor with child resources elements to parse + */ + protected abstract SMInputCursor cursorForResources(SMInputCursor rootCursor) throws XMLStreamException; + + /** + * Cursor for violations to parse for a given resource, the returned input cursor should be filtered on SMEvent.START_ELEMENT for optimal + * perfs + * + * @param resourcesCursor + * the current resource cursor + * @return a cursor with child violations elements to parse + */ + protected abstract SMInputCursor cursorForViolations(SMInputCursor resourcesCursor) throws XMLStreamException; + + /** + * Transforms a given xml resource to a resource Object + */ + protected abstract Resource toResource(SMInputCursor resourceCursor) throws XMLStreamException; + + protected abstract String messageFor(SMInputCursor violationCursor) throws XMLStreamException; + + protected abstract String ruleKey(SMInputCursor violationCursor) throws XMLStreamException; + + protected abstract String keyForPlugin(); + + protected abstract String lineNumberForViolation(SMInputCursor violationCursor) throws XMLStreamException; + + /** + * Specify if violations must be saved even if when the Resource associated to a violation doesn't yet exist. + * In that case the Resource is automatically created. + * + * @param doSaveViolationsOnUnexistedResource by default, the value is true + */ + public final void setDoSaveViolationsOnUnexistedResource(boolean doSaveViolationsOnUnexistedResource) { + this.doSaveViolationsOnUnexistedResource = doSaveViolationsOnUnexistedResource; + } + + public void parse(File violationsXMLFile) throws XMLStreamException { + if (violationsXMLFile != null && violationsXMLFile.exists()) { + InputStream input = null; + try { + input = new FileInputStream(violationsXMLFile); + parse(input); + + } catch (FileNotFoundException e) { + throw new XMLStreamException(e); + + } finally { + IOUtils.closeQuietly(input); + } + } + } + + public final void parse(InputStream input) throws XMLStreamException { + if (input != null) { + StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() { + + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + parseResources(rootCursor.advance()); + } + }, true); + parser.parse(input); + } + } + + private void parseResources(SMInputCursor rootCursor) throws XMLStreamException { + SMInputCursor resourcesCursor = cursorForResources(rootCursor); + SMEvent event; + while ((event = resourcesCursor.getNext()) != null) { + if (event.compareTo(SMEvent.START_ELEMENT) == 0) { + parseViolations(resourcesCursor); + } + } + } + + private void parseViolations(SMInputCursor resourcesCursor) throws XMLStreamException { + Resource resource = toResource(resourcesCursor); + if ( !doSaveViolationsOnUnexistedResource && context.getResource(resource) == null) { + return; + } + SMInputCursor violationsCursor = cursorForViolations(resourcesCursor); + SMEvent event; + while ((event = violationsCursor.getNext()) != null) { + if (event.compareTo(SMEvent.START_ELEMENT) == 0) { + createViolationFor(resource, violationsCursor); + } + } + } + + private void createViolationFor(Resource resource, SMInputCursor violationCursor) throws XMLStreamException { + Rule rule = getRule(violationCursor); + Integer line = getLineIndex(violationCursor); + if (rule != null && resource != null) { + Violation violation = new Violation(rule, resource) + .setLineId(line) + .setMessage(messageFor(violationCursor)); + context.saveViolation(violation); + } + } + + private Rule getRule(SMInputCursor violationCursor) throws XMLStreamException { + return rulesManager.getPluginRule(keyForPlugin(), ruleKey(violationCursor)); + } + + private Integer getLineIndex(SMInputCursor violationCursor) throws XMLStreamException { + String line = lineNumberForViolation(violationCursor); + return parseLineIndex(line); + } + + protected static Integer parseLineIndex(String line) { + if ( !isNotBlank(line) || line.indexOf('-') != -1) { + return null; + } + try { + return (int) ParsingUtils.parseNumber(line); + } catch (ParseException ignore) { + return null; + } + } + +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractImportableRulesRepository.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractImportableRulesRepository.java new file mode 100644 index 00000000000..9926a33081e --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractImportableRulesRepository.java @@ -0,0 +1,75 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.CharEncoding; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Language; +import org.sonar.api.utils.SonarException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +@Deprecated +public abstract class AbstractImportableRulesRepository<LANG extends Language, MAPPER extends RulePriorityMapper<?, ?>> extends AbstractRulesRepository<LANG, MAPPER> implements ConfigurationImportable { + + public AbstractImportableRulesRepository(LANG language, MAPPER mapper) { + super(language, mapper); + } + + /** + * A map a of profiles to import, The profile name as key, and the xml profile file name in the classpath + * + * @return + */ + public abstract Map<String, String> getBuiltInProfiles(); + + public final List<RulesProfile> getProvidedProfiles() { + List<RulesProfile> profiles = new ArrayList<RulesProfile>(); + + Map<String, String> defaultProfiles = new TreeMap<String, String>(getBuiltInProfiles()); + for (Map.Entry<String, String> entry : defaultProfiles.entrySet()) { + profiles.add(loadProvidedProfile(entry.getKey(), getCheckResourcesBase() + entry.getValue())); + } + return profiles; + } + + public final RulesProfile loadProvidedProfile(String name, String fileName) { + InputStream input = null; + try { + input = getClass().getResourceAsStream(fileName); + RulesProfile profile = new RulesProfile(name, getLanguage().getKey()); + profile.setActiveRules(importConfiguration(IOUtils.toString(input, CharEncoding.UTF_8), getInitialReferential())); + return profile; + + } catch (IOException e) { + throw new SonarException("Configuration file not found for the profile : " + name, e); + + } finally { + IOUtils.closeQuietly(input); + } + } + +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractRulesRepository.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractRulesRepository.java new file mode 100644 index 00000000000..ec69f047174 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/AbstractRulesRepository.java @@ -0,0 +1,76 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.apache.commons.io.IOUtils; +import org.sonar.api.resources.Language; +import org.sonar.api.utils.SonarException; + +import java.io.InputStream; +import java.util.List; + +@Deprecated +public abstract class AbstractRulesRepository<LANG extends Language, MAPPER extends RulePriorityMapper<?, ?>> implements RulesRepository<LANG> { + + private MAPPER priorityMapper; + private LANG language; + + public AbstractRulesRepository(LANG language, MAPPER priorityMapper) { + super(); + this.priorityMapper = priorityMapper; + this.language = language; + } + + public LANG getLanguage() { + return language; + } + + public abstract String getRepositoryResourcesBase(); + + public final List<Rule> getInitialReferential() { + String baseCP = getCheckResourcesBase(); + InputStream input = getClass().getResourceAsStream(baseCP + "rules.xml"); + if (input == null) { + throw new SonarException("Resource not found : " + baseCP + "rules.xml"); + } + try { + return new StandardRulesXmlParser().parse(input); + } + finally { + IOUtils.closeQuietly(input); + } + } + + public List<Rule> parseReferential(String fileContent) { + return new StandardRulesXmlParser().parse(fileContent); + } + + public MAPPER getRulePriorityMapper() { + return priorityMapper; + } + + protected String getCheckResourcesBase() { + String base = getRepositoryResourcesBase(); + base = base.startsWith("/") ? base : "/" + base; + base = base.endsWith("/") ? base : base + "/"; + return base; + } + +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationExportable.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationExportable.java new file mode 100644 index 00000000000..3a853a6ab3f --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationExportable.java @@ -0,0 +1,29 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.rules;
+
+import org.sonar.api.profiles.RulesProfile;
+
+@Deprecated
+public interface ConfigurationExportable {
+
+ String exportConfiguration(RulesProfile profile);
+
+}
diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationImportable.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationImportable.java new file mode 100644 index 00000000000..c16337875e3 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/ConfigurationImportable.java @@ -0,0 +1,30 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.rules;
+
+import java.util.List;
+import org.sonar.api.rules.Rule;
+
+@Deprecated
+public interface ConfigurationImportable {
+
+ List<ActiveRule> importConfiguration(String configuration, List<Rule> rules);
+
+}
diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/RulePriorityMapper.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulePriorityMapper.java new file mode 100644 index 00000000000..c8a382ecd89 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulePriorityMapper.java @@ -0,0 +1,29 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +@Deprecated +public interface RulePriorityMapper<IN_TYPE, OUT_TYPE> { + + RulePriority from(IN_TYPE priority); + + OUT_TYPE to(RulePriority priority); + +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesManager.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesManager.java new file mode 100644 index 00000000000..374f2241cf3 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesManager.java @@ -0,0 +1,96 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.sonar.api.Plugin; +import org.sonar.api.resources.Language; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @deprecated since 2.3 + */ +@Deprecated +public abstract class RulesManager { + + /** + * Returns the list of languages for which there is a rule repository + * + * @return a Set of languages + */ + public abstract Set<Language> getLanguages(); + + /** + * Gets the list of Rules Repositories available for a language + * + * @param language the language + * @return the list of rules repositories + */ + public abstract List<RulesRepository<?>> getRulesRepositories(Language language); + + /** + * Gets the complete list of Rules Repositories in the Sonar instance + * + * @return the list of rules repositories + */ + public abstract List<RulesRepository<?>> getRulesRepositories(); + + /** + * Gets the list of rules plugins for a given language + * @param language the language + * @return the list of plugins + */ + public abstract List<Plugin> getPlugins(Language language); + + /** + * Get the list of rules plugin that implement a mechanism of import for a given language + * + * @param language the language + * @return the list of plugins + */ + public abstract List<Plugin> getImportablePlugins(Language language); + + /** + * Gets a list of rules indexed by their key for a given plugin + * @param pluginKey the plugin key + * @return a Map with the rule key and the rule + */ + public abstract Map<String, Rule> getPluginRulesIndexedByKey(String pluginKey); + + /** + * Gets a collection of rules belonging to a plugin + * + * @param pluginKey the plugin key + * @return the collection of rules + */ + public abstract Collection<Rule> getPluginRules(String pluginKey); + + /** + * Gets a rule belonging to a defined plugin based on its key + * + * @param pluginKey the plugin key + * @param ruleKey the rule key + * @return the rule + */ + public abstract Rule getPluginRule(String pluginKey, String ruleKey); +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesRepository.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesRepository.java new file mode 100644 index 00000000000..8156cac9723 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/RulesRepository.java @@ -0,0 +1,58 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.rules;
+
+import org.sonar.api.BatchExtension;
+import org.sonar.api.ServerExtension;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.resources.Language;
+
+import java.util.List;
+
+/**
+ * @deprecated since 2.3
+ */
+@Deprecated
+public interface RulesRepository<LANG extends Language> extends BatchExtension, ServerExtension {
+
+ /**
+ * @return the language the repository is associated
+ */
+ LANG getLanguage();
+
+ /**
+ * @return the list of rules of the repository
+ */
+ List<Rule> getInitialReferential();
+
+ /**
+ * The method to parse the base referential of rules and return a list of rules
+ *
+ * @param fileContent the initial referential
+ * @return a list of rules
+ */
+ List<Rule> parseReferential(String fileContent);
+
+ /**
+ * @return a list of profiles that are provided with the referential
+ */
+ List<RulesProfile> getProvidedProfiles();
+
+}
diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardProfileXmlParser.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardProfileXmlParser.java new file mode 100644 index 00000000000..272b9642889 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardProfileXmlParser.java @@ -0,0 +1,119 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import com.thoughtworks.xstream.XStream; +import org.apache.commons.lang.StringUtils; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.rules.xml.Profile; +import org.sonar.api.rules.xml.Property; +import org.sonar.api.utils.SonarException; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class StandardProfileXmlParser { + + private final List<Rule> rules; + + public StandardProfileXmlParser() { + rules = new ArrayList<Rule>(); + } + + public StandardProfileXmlParser(List<Rule> rules) { + this.rules = rules; + } + + /** + * see the XML format into the unit test src/test/java/.../StandardProfileXmlParserTest + */ + public Profile parse(String xml) { + return (Profile) getXStream().fromXML(xml); + } + + private XStream getXStream() { + XStream xstream = new XStream(); + xstream.processAnnotations(Profile.class); + xstream.processAnnotations(Rule.class); + xstream.processAnnotations(Property.class); + return xstream; + } + + public RulesProfile importConfiguration(String configuration) { + RulesProfile rulesProfile = new RulesProfile(); + List<ActiveRule> activeRules = new ArrayList<ActiveRule>(); + Profile profile = buildProfileFromXml(configuration); + + rulesProfile.setName(profile.getName()); + rulesProfile.setLanguage(profile.getLanguage()); + + if (StringUtils.isBlank(rulesProfile.getName())) { + throw new SonarException("Profile name can't be null or empty"); + } + + buildActiveRulesFromProfile(profile, activeRules); + rulesProfile.setActiveRules(activeRules); + return rulesProfile; + } + + protected Profile buildProfileFromXml(String configuration) { + StandardProfileXmlParser xstream = new StandardProfileXmlParser(); + return xstream.parse(configuration); + } + + protected void buildActiveRulesFromProfile(Profile profile, List<ActiveRule> activeRules) { + if (profile.getRules() != null && !profile.getRules().isEmpty()) { + for (org.sonar.api.rules.xml.Rule module : profile.getRules()) { + String ref = module.getKey(); + for (Rule rule : rules) { + if (rule.getConfigKey().equals(ref)) { + RulePriority rulePriority = getRulePriority(module); + ActiveRule activeRule = new ActiveRule(null, rule, rulePriority); + activeRule.setActiveRuleParams(getActiveRuleParams(module, rule, activeRule)); + activeRules.add(activeRule); + break; + } + } + } + } + } + + private RulePriority getRulePriority(org.sonar.api.rules.xml.Rule module) { + return StringUtils.isBlank(module.getPriority()) ? null : RulePriority.valueOfString(module.getPriority()); + } + + private List<ActiveRuleParam> getActiveRuleParams(org.sonar.api.rules.xml.Rule module, Rule rule, ActiveRule activeRule) { + List<ActiveRuleParam> activeRuleParams = new ArrayList<ActiveRuleParam>(); + if (module.getProperties() != null) { + for (Property property : module.getProperties()) { + if (rule.getParams() != null) { + for (RuleParam ruleParam : rule.getParams()) { + if (ruleParam.getKey().equals(property.getName())) { + activeRuleParams.add(new ActiveRuleParam(activeRule, ruleParam, property.getValue())); + } + } + } + } + } + return activeRuleParams; + } + +}
\ No newline at end of file diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardRulesXmlParser.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardRulesXmlParser.java new file mode 100644 index 00000000000..e532df1d040 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/StandardRulesXmlParser.java @@ -0,0 +1,160 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter; +import com.thoughtworks.xstream.core.util.QuickWriter; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; +import com.thoughtworks.xstream.io.xml.XppDriver; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.CharEncoding; +import org.apache.commons.lang.StringUtils; +import org.sonar.api.utils.SonarException; + +import java.io.*; +import java.lang.ref.WeakReference; +import java.util.*; + +@Deprecated +public class StandardRulesXmlParser { + + /** + * see the XML format into the unit test src/test/java/.../StandardRulesXmlParserTest + */ + public List<Rule> parse(String xml) { + InputStream inputStream = null; + try { + inputStream = IOUtils.toInputStream(xml, CharEncoding.UTF_8); + return setDefaultRulePriorities((List<Rule>) getXStream().fromXML(inputStream)); + + } catch (IOException e) { + throw new SonarException("Can't parse xml file", e); + + } finally { + IOUtils.closeQuietly(inputStream); + } + } + + public List<Rule> parse(Reader reader) { + return setDefaultRulePriorities((List<Rule>) getXStream().fromXML(reader)); + } + + public List<Rule> parse(InputStream input) { + try { + return setDefaultRulePriorities((List<Rule>) getXStream().fromXML(new InputStreamReader(input, CharEncoding.UTF_8))); + + } catch (UnsupportedEncodingException e) { + throw new SonarException("Can't parse xml file", e); + } + } + + private List<Rule> setDefaultRulePriorities(List<Rule> rules) { + for (Rule rule : rules) { + if (rule.getPriority() == null) { + rule.setPriority(RulePriority.MAJOR); + } + } + return rules; + } + + public String toXml(List<Rule> rules) { + return getXStream().toXML(rules); + } + + private static class CDataXppDriver extends XppDriver { + @Override + public HierarchicalStreamWriter createWriter(Writer out) { + return new XDataPrintWriter(out); + } + } + + private static class XDataPrintWriter extends PrettyPrintWriter { + public XDataPrintWriter(Writer writer) { + super(writer); + } + + @Override + protected void writeText(QuickWriter writer, String text) { + writer.write("<![CDATA["); + writer.write(text); + writer.write("]]>"); + } + } + + private XStream getXStream() { + XStream xstream = new XStream(new CDataXppDriver()); + xstream.registerConverter(new TrimStringConverter()); + xstream.alias("rules", ArrayList.class); + + xstream.alias("categ", RulesCategory.class); + xstream.useAttributeFor(RulesCategory.class, "name"); + xstream.aliasField("category", Rule.class, "rulesCategory"); + + xstream.alias("rule", Rule.class); + xstream.useAttributeFor(Rule.class, "key"); + xstream.useAttributeFor("priority", RulePriority.class); + + xstream.addImplicitCollection(Rule.class, "params"); + + xstream.alias("param", RuleParam.class); + xstream.useAttributeFor(RuleParam.class, "key"); + xstream.useAttributeFor(RuleParam.class, "type"); + + // only for backward compatibility with sonar 1.4. + xstream.omitField(RuleParam.class, "defaultValue"); + return xstream; + } + + /** + * See http://svn.codehaus.org/xstream/trunk/xstream/src/java/com/thoughtworks/xstream/converters/basic/StringConverter.java + */ + public static class TrimStringConverter extends AbstractSingleValueConverter { + + private final Map cache; + + public TrimStringConverter(final Map map) { + cache = map; + } + + public TrimStringConverter() { + this(Collections.synchronizedMap(new WeakHashMap())); + } + + public boolean canConvert(final Class type) { + return type.equals(String.class); + } + + public Object fromString(final String str) { + String trim = StringUtils.trim(str); + final WeakReference ref = (WeakReference) cache.get(trim); + String s = (String) (ref == null ? null : ref.get()); + + if (s == null) { + // fill cache + cache.put(str, new WeakReference(trim)); + s = trim; + } + + return s; + } + } +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Profile.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Profile.java new file mode 100644 index 00000000000..cd40e8a1f0e --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Profile.java @@ -0,0 +1,65 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules.xml; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +@XStreamAlias("profile") +public class Profile { + + @XStreamAsAttribute + private String language; + + @XStreamAsAttribute + private String name; + + @XStreamImplicit + private List<Rule> rules = new ArrayList<Rule>(); + + public List<Rule> getRules() { + return rules; + } + + public void setRules(List<Rule> rules) { + this.rules = rules; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Property.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Property.java new file mode 100644 index 00000000000..8e6dbec7670 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Property.java @@ -0,0 +1,47 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.rules.xml;
+
+import com.thoughtworks.xstream.annotations.XStreamAlias;
+import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
+
+@Deprecated
+@XStreamAlias("property")
+public class Property {
+
+ @XStreamAsAttribute
+ private String name;
+
+ @XStreamAsAttribute
+ private String value;
+
+ public Property(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+}
\ No newline at end of file diff --git a/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Rule.java b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Rule.java new file mode 100644 index 00000000000..e424d1466a6 --- /dev/null +++ b/sonar-deprecated/src/main/java/org/sonar/api/rules/xml/Rule.java @@ -0,0 +1,82 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.rules.xml;
+
+import com.thoughtworks.xstream.annotations.XStreamAlias;
+import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
+import com.thoughtworks.xstream.annotations.XStreamImplicit;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Deprecated
+@XStreamAlias("rule")
+public class Rule implements Comparable<String> {
+
+ @XStreamAsAttribute
+ private String key;
+
+ @XStreamAsAttribute
+ private String priority;
+
+ @XStreamImplicit
+ private List<Property> properties;
+
+ public Rule(String ref) {
+ this(ref, null);
+ }
+
+ public Rule(String ref, String priority) {
+ this.key = ref;
+ this.priority = priority;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setProperties(List<Property> properties) {
+ this.properties = properties;
+ }
+
+ public List<Property> getProperties() {
+ return properties;
+ }
+
+ public int compareTo(String o) {
+ return o.compareTo(key);
+ }
+
+ public String getPriority() {
+ return priority;
+ }
+
+ public void setPriority(String priority) {
+ this.priority = priority;
+ }
+
+ public void addProperty(Property property) {
+ if (properties == null) {
+ properties = new ArrayList<Property>();
+ }
+ properties.add(property);
+ }
+
+}
\ No newline at end of file diff --git a/sonar-deprecated/src/test/java/org/sonar/api/batch/AbstractViolationsStaxParserTest.java b/sonar-deprecated/src/test/java/org/sonar/api/batch/AbstractViolationsStaxParserTest.java new file mode 100644 index 00000000000..d1f91f1b4d3 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/batch/AbstractViolationsStaxParserTest.java @@ -0,0 +1,103 @@ +/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar 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 Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+
+package org.sonar.api.batch;
+
+import static junit.framework.Assert.assertNull;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.mockito.Mockito.mock;
+
+import java.io.StringReader;
+
+import javax.xml.stream.XMLStreamException;
+
+import org.codehaus.staxmate.in.SMInputCursor;
+import org.hibernate.lob.ReaderInputStream;
+import org.junit.Test;
+import org.sonar.api.resources.JavaFile;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.rules.RulesManager;
+
+public class AbstractViolationsStaxParserTest {
+
+ @Test
+ public void testParseLineIndex() {
+
+ assertThat(AbstractViolationsStaxParser.parseLineIndex("4"), is(4));
+ assertNull(AbstractViolationsStaxParser.parseLineIndex("toto"));
+ assertNull(AbstractViolationsStaxParser.parseLineIndex(""));
+ assertNull(AbstractViolationsStaxParser.parseLineIndex(null));
+ assertNull(AbstractViolationsStaxParser.parseLineIndex("-1"));
+ }
+
+ @Test
+ public void testDoNotSaveViolationsOnUnexistedResource() throws XMLStreamException {
+ SensorContext context = mock(SensorContext.class);
+ MyViolationParser violationParser = new MyViolationParser(context, null);
+ violationParser.setDoSaveViolationsOnUnexistedResource(false);
+ violationParser.parse(new ReaderInputStream(new StringReader("<root><file/></root>")));
+ }
+
+ @Test(expected = CursorForViolationsMethodHasBeenCalled.class)
+ public void testDoSaveViolationsOnUnexistedResource() throws XMLStreamException {
+ SensorContext context = mock(SensorContext.class);
+ MyViolationParser violationParser = new MyViolationParser(context, null);
+ violationParser.parse(new ReaderInputStream(new StringReader("<root><file/></root>")));
+ }
+
+ private class MyViolationParser extends AbstractViolationsStaxParser {
+
+ protected MyViolationParser(SensorContext context, RulesManager rulesManager) {
+ super(context, rulesManager);
+ }
+
+ protected SMInputCursor cursorForResources(SMInputCursor rootCursor) throws XMLStreamException {
+ return rootCursor.descendantElementCursor("file");
+ }
+
+ protected SMInputCursor cursorForViolations(SMInputCursor resourcesCursor) throws XMLStreamException {
+ throw new CursorForViolationsMethodHasBeenCalled();
+ }
+
+ protected Resource toResource(SMInputCursor resourceCursor) throws XMLStreamException {
+ return new JavaFile("org.sonar.MyClass");
+ }
+
+ protected String messageFor(SMInputCursor violationCursor) throws XMLStreamException {
+ return null;
+ }
+
+ protected String ruleKey(SMInputCursor violationCursor) throws XMLStreamException {
+ return null;
+ }
+
+ protected String keyForPlugin() {
+ return null;
+ }
+
+ protected String lineNumberForViolation(SMInputCursor violationCursor) throws XMLStreamException {
+ return null;
+ }
+ }
+
+ private class CursorForViolationsMethodHasBeenCalled extends RuntimeException {
+ }
+}
diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheck.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheck.java new file mode 100644 index 00000000000..da01fb10904 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheck.java @@ -0,0 +1,27 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.sonar.check.Check; +import org.sonar.check.IsoCategory; + +@Check(title ="Annotated Check", description = "Description", isoCategory = IsoCategory.Reliability) +public class AnnotatedCheck { +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java new file mode 100644 index 00000000000..cd487c3d0a0 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java @@ -0,0 +1,44 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.sonar.check.Check; +import org.sonar.check.CheckProperty; +import org.sonar.check.IsoCategory; + +@Check(key = "overriden_key",title ="Check with parameters", description = "Has parameters", isoCategory = IsoCategory.Efficiency) +public class AnnotatedCheckWithParameters { + + @CheckProperty(description ="Maximum value") + private String max; + + @CheckProperty(key = "overidden_min", description ="Minimum value") + protected String min; + + private int nonConfigurableProperty; + + public String getMax() { + return max; + } + + public void setMax(String max) { + this.max = max; + } +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java new file mode 100644 index 00000000000..98d05bbd1f4 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java @@ -0,0 +1,64 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.hamcrest.core.Is; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +public class RuleAnnotationUtilsTest { + + @Test + public void readAnnotatedClassWithoutParameters() { + Rule rule = RuleAnnotationUtils.readAnnotatedClass(AnnotatedCheck.class); + assertNotNull(rule); + assertThat(rule.getKey(), is(AnnotatedCheck.class.getName())); + assertThat(rule.getName(), is("Annotated Check")); + assertThat(rule.getConfigKey(), nullValue()); + assertThat(rule.getParams().size(), is(0)); + assertThat(rule.getDescription(), is("Description")); + assertThat(rule.getCardinality(), Is.is(Rule.Cardinality.SINGLE)); + assertThat(rule.getRulesCategory().getName(), Is.is(Iso9126RulesCategories.RELIABILITY.getName())); + } + + @Test + public void ruleKeyCanBeOverridden() { + Rule rule = RuleAnnotationUtils.readAnnotatedClass(AnnotatedCheckWithParameters.class); + assertNotNull(rule); + assertThat(rule.getKey(), is("overriden_key")); + } + @Test + public void readAnnotatedClassWithParameters() { + Rule rule = RuleAnnotationUtils.readAnnotatedClass(AnnotatedCheckWithParameters.class); + assertNotNull(rule); + assertThat(rule.getParams().size(), is(2)); + assertThat(rule.getParam("max"), not(nullValue())); + assertThat(rule.getParam("max").getDescription(), is("Maximum value")); + + assertThat(rule.getParam("min"), nullValue()); + assertThat(rule.getParam("overidden_min"), not(nullValue())); + assertThat(rule.getParam("overidden_min").getDescription(), is("Minimum value")); + } +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/RulePriorityTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/RulePriorityTest.java new file mode 100644 index 00000000000..a3ed40321b8 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/RulePriorityTest.java @@ -0,0 +1,44 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import static junit.framework.Assert.assertEquals; + +import junit.framework.Assert; +import org.junit.Test; + +public class RulePriorityTest { + + @Test + public void testValueOfString() { + Assert.assertEquals(RulePriority.INFO, RulePriority.valueOfString("info")); + Assert.assertEquals(RulePriority.MAJOR, RulePriority.valueOfString("MAJOR")); + Assert.assertEquals(RulePriority.MAJOR, RulePriority.valueOfString("ERROR")); + Assert.assertEquals(RulePriority.INFO, RulePriority.valueOfString("WARNING")); + Assert.assertEquals(RulePriority.MAJOR, RulePriority.valueOfString("ErRor")); + Assert.assertEquals(RulePriority.INFO, RulePriority.valueOfString("WaRnInG")); + } + + @Test(expected = IllegalArgumentException.class) + public void testUnknownValueOfString() { + RulePriority.valueOfString("make me crash"); + } + +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleTest.java new file mode 100644 index 00000000000..c0767fda0ad --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleTest.java @@ -0,0 +1,95 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + +import org.hamcrest.core.Is; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +public class RuleTest { + + @Test + public void descriptionShouldBeCleaned() { + Rule rule = new Rule(); + rule.setDescription(" my description "); + Assert.assertEquals("my description", rule.getDescription()); + + rule.setDescription(null); + assertNull(rule.getDescription()); + } + + @Test + public void shouldRemoveNewLineCharactersInNameWithSetter() { + Rule rule = new Rule(); + for (String example : getExamplesContainingNewLineCharacter()) { + rule.setName(example); + assertThat(rule.getName(), is("test")); + } + } + + @Test + public void shouldRemoveNewLineCharactersInNameWithfirstConstructor() { + Rule rule; + for (String example : getExamplesContainingNewLineCharacter()) { + rule = new Rule(null, null, example, (RulesCategory) null, null); + assertThat(rule.getName(), is("test")); + } + } + + @Test + public void shouldRemoveNewLineCharactersInNameWithSecondConstructor() { + Rule rule; + for (String example : getExamplesContainingNewLineCharacter()) { + rule = new Rule(null, null, example, (RulesCategory)null, null); + assertThat(rule.getName(), is("test")); + } + } + + @Test + public void defaultPriorityIsMajor() { + Rule rule = new Rule(); + assertThat(rule.getPriority(), Is.is(RulePriority.MAJOR)); + + rule = new Rule("name", "key"); + assertThat(rule.getPriority(), Is.is(RulePriority.MAJOR)); + + rule = new Rule("pkey", "key", "name", Iso9126RulesCategories.EFFICIENCY, null, null); + assertThat(rule.getPriority(), Is.is(RulePriority.MAJOR)); + + rule.setPriority(RulePriority.BLOCKER); + assertThat(rule.getPriority(), Is.is(RulePriority.BLOCKER)); + + rule.setPriority(null); + assertThat(rule.getPriority(), Is.is(RulePriority.MAJOR)); + } + + + private List<String> getExamplesContainingNewLineCharacter() { + return Arrays.asList("te\nst", "te\ns\nt", "te\rst", "te\n\rst", "te\r\nst"); + } + + +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleUtilsTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleUtilsTest.java new file mode 100644 index 00000000000..c60a5fdf604 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/RuleUtilsTest.java @@ -0,0 +1,66 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.apache.commons.configuration.Configuration; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import org.junit.Test; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.mockito.Matchers; +import org.sonar.api.CoreProperties; + +import java.util.Map; + +public class RuleUtilsTest { + + @Test + public void getPriorityWeights() { + Configuration conf = mock(Configuration.class); + when(conf.getString(Matchers.eq(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY), anyString())).thenReturn("info=0;minor=1;major=2;critical=5;blocker=10"); + + final Map<RulePriority, Integer> map = RuleUtils.getPriorityWeights(conf); + + assertThat(map.get(RulePriority.BLOCKER), is(10)); + assertThat(map.get(RulePriority.CRITICAL), is(5)); + assertThat(map.get(RulePriority.MAJOR), is(2)); + assertThat(map.get(RulePriority.MINOR), is(1)); + assertThat(map.get(RulePriority.INFO), is(0)); + } + + @Test + public void loadMissingWeights() { + Configuration conf = mock(Configuration.class); + when(conf.getString(Matchers.eq(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY), anyString())).thenReturn("foo=0;bar=1;CRITICAL=5"); + + final Map<RulePriority, Integer> map = RuleUtils.getPriorityWeights(conf); + + assertThat(map.get(RulePriority.BLOCKER), is(1)); + assertThat(map.get(RulePriority.CRITICAL), is(5)); + assertThat(map.get(RulePriority.MAJOR), is(1)); + assertThat(map.get(RulePriority.MINOR), is(1)); + assertThat(map.get(RulePriority.INFO), is(1)); + } + +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardProfileXmlParserTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardProfileXmlParserTest.java new file mode 100644 index 00000000000..2f20bd096ca --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardProfileXmlParserTest.java @@ -0,0 +1,172 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.apache.commons.io.IOUtils; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.rules.xml.Profile; +import org.sonar.api.rules.xml.Property; +import org.sonar.api.utils.SonarException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class StandardProfileXmlParserTest { + + @Test + public void checkAllFields() { + StandardProfileXmlParser parser = new StandardProfileXmlParser(); + String xml = "<profile name='Sonar way' language='java'><rule key=\"2006\" priority=\"warning\" /><rule key=\"2007\" priority=\"error\"><property name=\"toto\" value=\"titi\" /></rule></profile>"; + Profile profile = parser.parse(xml); + + assertEquals(2, profile.getRules().size()); + assertEquals("Sonar way", profile.getName()); + + org.sonar.api.rules.xml.Rule rule1 = profile.getRules().get(0); + assertEquals("2006", rule1.getKey()); + assertEquals("warning", rule1.getPriority()); + assertNull(rule1.getProperties()); + + org.sonar.api.rules.xml.Rule rule2 = profile.getRules().get(1); + assertEquals("2007", rule2.getKey()); + assertEquals("error", rule2.getPriority()); + assertEquals(rule2.getProperties().size(), 1); + + Property property = rule2.getProperties().get(0); + assertEquals("toto", property.getName()); + assertEquals("titi", property.getValue()); + } + + @Test(expected = SonarException.class) + public void shouldProfileNameBeNotNull() throws IOException { + InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile_name_null.xml"); + StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser(); + standardProfileXmlParser.importConfiguration(IOUtils.toString(input)); + } + + @Test + public void shouldBuildProfileFromXml() throws IOException { + StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser(); + InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile.xml"); + Profile profile = standardProfileXmlParser.buildProfileFromXml(IOUtils.toString(input)); + + assertThat("Sonar way", is(profile.getName())); + assertThat(profile.getRules().size(), is(3)); + + org.sonar.api.rules.xml.Rule rule1 = profile.getRules().get(0); + assertThat(rule1.getKey(), is("2006")); + assertThat(rule1.getPriority(), is("warning")); + assertNull(rule1.getProperties()); + + org.sonar.api.rules.xml.Rule rule2 = profile.getRules().get(1); + assertThat(rule2.getKey(), is("2007")); + assertThat(rule2.getPriority(), is("error")); + assertThat(rule2.getProperties().size(), is(1)); + + org.sonar.api.rules.xml.Rule rule3 = profile.getRules().get(2); + assertThat(rule3.getKey(), is("2008")); + assertThat(rule3.getPriority(), is("critical")); + assertNull(rule3.getProperties()); + + Property rule2Property = rule2.getProperties().get(0); + assertThat(rule2Property.getName(), is("toto")); + assertThat(rule2Property.getValue(), is("titi")); + } + + @Test + public void shouldImportConfiguration() throws IOException { + final List<Rule> inputRules = buildRulesFixture(); + List<ActiveRule> activeRulesExpected = buildActiveRulesFixture(inputRules); + + StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser(inputRules); + + InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile.xml"); + RulesProfile profile = standardProfileXmlParser.importConfiguration(IOUtils.toString(input)); + List<ActiveRule> results = profile.getActiveRules(); + + assertThat("Sonar way", CoreMatchers.is(profile.getName())); + assertThat(results.size(), is(activeRulesExpected.size())); + assertActiveRulesAreEquals(results, activeRulesExpected); + } + + private List<Rule> buildRulesFixture() { + List<Rule> rules = new ArrayList<Rule>(); + + Rule rule1 = new Rule("One rule", "2006", + "2006", null, "MYPLUGIN", null); + + Rule rule2 = new Rule("Another rule", "2007", + "2007", null, "MYPLUGIN", null); + RuleParam ruleParam2 = new RuleParam(rule2, "toto", null, "s"); + rule2.setParams(Arrays.asList(ruleParam2)); + + Rule rule3 = new Rule("Third rule", "2008", + "2008", null, "MYPLUGIN", null); + + rules.add(rule1); + rules.add(rule2); + rules.add(rule3); + + return rules; + } + + + private List<ActiveRule> buildActiveRulesFixture(List<Rule> rules) { + List<ActiveRule> activeRules = new ArrayList<ActiveRule>(); + + ActiveRule activeRule1 = new ActiveRule(null, rules.get(0), RulePriority.INFO); + activeRules.add(activeRule1); + + ActiveRule activeRule2 = new ActiveRule(null, rules.get(1), RulePriority.MAJOR); + activeRule2.setActiveRuleParams(Arrays.asList(new ActiveRuleParam(activeRule2, rules.get(1).getParams().get(0), "titi"))); + activeRules.add(activeRule2); + + ActiveRule activeRule3 = new ActiveRule(null, rules.get(2), RulePriority.CRITICAL); + activeRules.add(activeRule3); + + return activeRules; + } + + private void assertActiveRulesAreEquals(List<ActiveRule> activeRules1, List<ActiveRule> activeRules2) { + for (int i = 0; i < activeRules1.size(); i++) { + ActiveRule activeRule1 = activeRules1.get(i); + ActiveRule activeRule2 = activeRules2.get(i); + assertTrue(activeRule1.getRule().equals(activeRule2.getRule()) && activeRule1.getPriority().equals(activeRule2.getPriority())); + + Assert.assertEquals(activeRule1.getActiveRuleParams().size(), (activeRule2.getActiveRuleParams().size())); + for (int j = 0; j < activeRule1.getActiveRuleParams().size(); j++) { + ActiveRuleParam activeRuleParam1 = activeRule1.getActiveRuleParams().get(j); + ActiveRuleParam activeRuleParam2 = activeRule2.getActiveRuleParams().get(j); + assertTrue(activeRuleParam1.getRuleParam().equals(activeRuleParam2.getRuleParam()) + && activeRuleParam1.getValue().equals(activeRuleParam2.getValue())); + } + } + } + +}
\ No newline at end of file diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRuleXmlFormatTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRuleXmlFormatTest.java new file mode 100644 index 00000000000..a1cfb59336c --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRuleXmlFormatTest.java @@ -0,0 +1,91 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.hamcrest.core.Is; +import org.junit.Test; +import org.sonar.api.utils.SonarException; + +import java.io.StringReader; +import java.util.List; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertThat; + +public class StandardRuleXmlFormatTest { + + @Test + public void parseXml() { + List<Rule> rules = StandardRuleXmlFormat.parseXml(getClass().getResourceAsStream("/org/sonar/api/rules/StandardRuleXmlFormatTest/rules.xml")); + assertThat(rules.size(), is(2)); + + Rule rule = rules.get(0); + assertThat(rule.getName(), is("Local Variable Name")); + assertThat(rule.getDescription(), is("Checks that local, non-final variable names conform to a format specified by the format property.")); + assertThat(rule.getPriority(), Is.is(RulePriority.BLOCKER)); + assertThat(rule.getCardinality(), Is.is(Rule.Cardinality.MULTIPLE)); + assertThat(rule.getConfigKey(), is("Checker/TreeWalker/LocalVariableName")); + + assertThat(rule.getParams().size(), is(2)); + RuleParam prop = rule.getParam("ignore"); + assertThat(prop.getKey(), is("ignore")); + assertThat(prop.getDescription(), is("Ignore ?")); + + Rule minimalRule = rules.get(1); + assertThat(minimalRule.getKey(), is("com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheck")); + assertThat(minimalRule.getParams().size(), is(0)); + + } + + @Test(expected = SonarException.class) + public void failIfMissingRuleKey() { + StandardRuleXmlFormat.parseXml(new StringReader("<rules><rule><name>Foo</name></rule></rules>")); + } + + @Test(expected = SonarException.class) + public void failIfMissingPropertyKey() { + StandardRuleXmlFormat.parseXml(new StringReader("<rules><rule><key>foo</key><name>Foo</name><param></param></rule></rules>")); + } + + @Test + public void utf8Encoding() { + List<Rule> rules = StandardRuleXmlFormat.parseXml(getClass().getResourceAsStream("/org/sonar/api/rules/StandardRuleXmlFormatTest/utf8.xml")); + assertThat(rules.size(), is(1)); + Rule rule = rules.get(0); + assertThat(rule.getKey(), is("com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck")); + assertThat(rule.getName(), is("M & M")); + assertThat(rule.getDescription().charAt(0), is('\u00E9')); + assertThat(rule.getDescription().charAt(1), is('\u00E0')); + assertThat(rule.getDescription().charAt(2), is('\u0026')); + } + + @Test + public void supportDeprecatedFormat() { + // the deprecated format uses some attributes instead of nodes + List<Rule> rules = StandardRuleXmlFormat.parseXml(getClass().getResourceAsStream("/org/sonar/api/rules/StandardRuleXmlFormatTest/deprecated.xml")); + assertThat(rules.size(), is(1)); + Rule rule = rules.get(0); + assertThat(rule.getPriority(), Is.is(RulePriority.CRITICAL)); + assertThat(rule.getKey(), is("org.sonar.it.checkstyle.MethodsCountCheck")); + assertThat(rule.getParam("minMethodsCount"), not(nullValue())); + } +} diff --git a/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRulesXmlParserTest.java b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRulesXmlParserTest.java new file mode 100644 index 00000000000..30bc75f9f89 --- /dev/null +++ b/sonar-deprecated/src/test/java/org/sonar/api/rules/StandardRulesXmlParserTest.java @@ -0,0 +1,138 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2009 SonarSource SA + * mailto:contact AT sonarsource DOT com + * + * Sonar 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. + * + * Sonar 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 Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.api.rules; + +import org.apache.commons.io.IOUtils; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.*; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; + +public class StandardRulesXmlParserTest { + @Test + public void checkAllFields() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1'><name>my name</name><configKey>my_config_key</configKey><description>my description</description><param key='param1'><type>s</type><description>param description</description></param><param key='param2'><type>integer</type><description>param description 2</description></param></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertEquals(1, rules.size()); + + Rule rule = rules.get(0); + Assert.assertEquals("key1", rule.getKey()); + Assert.assertEquals("my name", rule.getName()); + Assert.assertEquals("my_config_key", rule.getConfigKey()); + Assert.assertEquals("my description", rule.getDescription()); + Assert.assertEquals(2, rule.getParams().size()); + Assert.assertEquals("param1", rule.getParams().get(0).getKey()); + Assert.assertEquals("s", rule.getParams().get(0).getType()); + Assert.assertEquals("param description", rule.getParams().get(0).getDescription()); + } + + @Test + public void ruleShouldHaveACategory() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule><category name='cat1' /></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertNotNull(rules.get(0).getRulesCategory()); + Assert.assertEquals("cat1", rules.get(0).getRulesCategory().getName()); + assertNull(rules.get(0).getRulesCategory().getId()); + assertNull(rules.get(0).getRulesCategory().getDescription()); + } + + @Test + public void ruleCanHaveALevel() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='1' priority='CRITICAL'><category name='cat1'/></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertNotNull(rules.get(0).getRulesCategory()); + Assert.assertEquals(RulePriority.CRITICAL, rules.get(0).getPriority()); + assertNull(rules.get(0).getRulesCategory().getId()); + assertNull(rules.get(0).getRulesCategory().getDescription()); + } + + @Test + public void ruleShouldHaveADefaultLevel() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='1'><category name='cat1'/></rule></rules>"; + List<Rule> rules = parser.parse(xml); + Assert.assertEquals(RulePriority.MAJOR, rules.get(0).getPriority()); + } + + @Test + public void shouldDefineManyRules() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1' /><rule key='key2' category='cat1' /></rules>"; + List<Rule> rules = parser.parse(xml); + assertEquals(2, rules.size()); + Assert.assertEquals("key1", rules.get(0).getKey()); + Assert.assertEquals("key2", rules.get(1).getKey()); + } + + @Test + public void someFielsShouldBeNull() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1' /></rules>"; + List<Rule> rules = parser.parse(xml); + assertNull(rules.get(0).getDescription()); + assertNull(rules.get(0).getName()); + assertNull(rules.get(0).getConfigKey()); + } + + @Test + public void shouldContainCDataDescription() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1'><description> <![CDATA[<xml> </nodes> and accents Žˆ˜ ]]> </description></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertEquals(1, rules.size()); + Assert.assertEquals("<xml> </nodes> and accents Žˆ˜", rules.get(0).getDescription()); + } + + @Test + public void shouldBeBackwardCompatibleWithDefaultVersionProperty() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1'><name>my name</name><configKey>my_config_key</configKey><param key='param1'><type>s</type><description>param description</description><defaultValue>xxx</defaultValue></param></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertEquals(1, rules.size()); + + Rule rule = rules.get(0); + Assert.assertEquals("key1", rule.getKey()); + Assert.assertEquals(1, rule.getParams().size()); + Assert.assertEquals("param1", rule.getParams().get(0).getKey()); + } + + @Test + public void shouldParseStringInUt8() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1' ><description>\\u00E9</description></rule></rules>"; + List<Rule> rules = parser.parse(xml); + assertThat(rules.get(0).getDescription(), is("\\u00E9")); + } + + @Test + public void shouldParseInputStreamInUt8() { + StandardRulesXmlParser parser = new StandardRulesXmlParser(); + String xml = "<rules><rule key='key1' category='cat1' ><description>\\u00E9</description></rule></rules>"; + List<Rule> rules = parser.parse(IOUtils.toInputStream(xml)); + assertThat(rules.get(0).getDescription(), is("\\u00E9")); + } +} diff --git a/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/deprecated.xml b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/deprecated.xml new file mode 100644 index 00000000000..44cf56d228a --- /dev/null +++ b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/deprecated.xml @@ -0,0 +1,11 @@ +<rules> + <rule key="org.sonar.it.checkstyle.MethodsCountCheck" priority="CRITICAL"> + <name>Methods Count Check</name> + <configKey>Checker/TreeWalker/org.sonar.it.checkstyle.MethodsCountCheck</configKey> + <category name="Usability"/> + <description>Count methods.</description> + <param key="minMethodsCount" type="i"> + <description>Le nombre minimum de méthodes. 10 par défaut.</description> + </param> + </rule> +</rules>
\ No newline at end of file diff --git a/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/rules.xml b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/rules.xml new file mode 100644 index 00000000000..c4038bdf96c --- /dev/null +++ b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/rules.xml @@ -0,0 +1,39 @@ +<rules> + <rule> + <!-- with exhaustive fields --> + <key>com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck</key> + <name>Local Variable Name</name> + <description> + <![CDATA[Checks that local, non-final variable names conform to a format specified by the format property.]]> + </description> + <isoCategory>Efficiency</isoCategory> + <configKey>Checker/TreeWalker/LocalVariableName</configKey> + <priority>BLOCKER</priority> + <cardinality>MULTIPLE</cardinality> + <param> + <key>tokens</key> + <description> + <![CDATA[ + Controls whether the check applies to variable declarations or catch clause parameters + ]]> + </description> + </param> + <param> + <key>ignore</key> + <description> + Ignore ? + </description> + </param> + </rule> + + + <rule> + <!-- with only required fields --> + <key>com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheck</key> + <name>Magic Number</name> + <description> + <![CDATA[Checks for magic numbers.]]> + </description> + <isoCategory>Maintainability</isoCategory> + </rule> +</rules>
\ No newline at end of file diff --git a/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/utf8.xml b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/utf8.xml new file mode 100644 index 00000000000..6197e030057 --- /dev/null +++ b/sonar-deprecated/src/test/resources/org/sonar/api/rules/StandardRuleXmlFormatTest/utf8.xml @@ -0,0 +1,11 @@ +<rules> + <rule> + <key>com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck</key> + <priority>BLOCKER</priority> + <configKey>Checker/TreeWalker/LocalVariableName</configKey> + <name>M & M</name> + <description> + <![CDATA[éà &]]> + </description> + </rule> +</rules> diff --git a/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile.xml b/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile.xml new file mode 100644 index 00000000000..29e2024bf51 --- /dev/null +++ b/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile.xml @@ -0,0 +1,7 @@ +<profile name="Sonar way" language='java'>
+ <rule key="2006" priority="warning"/>
+ <rule key="2007" priority="error">
+ <property name="toto" value="titi"/>
+ </rule>
+ <rule key="2008" priority="critical"/>
+</profile>
\ No newline at end of file diff --git a/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile_name_null.xml b/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile_name_null.xml new file mode 100644 index 00000000000..65d39e70403 --- /dev/null +++ b/sonar-deprecated/src/test/resources/org/sonar/api/rules/test_profile_name_null.xml @@ -0,0 +1,6 @@ +<profile name="" language='java'>
+ <rule key="2006" priority="warning"/>
+ <rule key="2007" priority="error">
+ <property name="toto" value="titi"/>
+ </rule>
+</profile>
\ No newline at end of file |