diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index 88b06b3760..30e5d9ffc5 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -7,15 +7,16 @@ import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import net.sourceforge.pmd.benchmark.Benchmark; import net.sourceforge.pmd.benchmark.Benchmarker; +import net.sourceforge.pmd.cache.ChecksumAware; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.Node; @@ -32,56 +33,301 @@ import net.sourceforge.pmd.util.filter.Filters; * @see Rule */ // FUTURE Implement Cloneable and clone() -public class RuleSet { +public class RuleSet implements ChecksumAware { private static final Logger LOG = Logger.getLogger(RuleSet.class.getName()); private static final String MISSING_RULE = "Missing rule"; private final long checksum; - private List rules = new ArrayList<>(); - private String fileName; - private String name = ""; - private String description = ""; + private final List rules; + private final String fileName; + private final String name; + private final String description; // TODO should these not be Sets or is their order important? - private List excludePatterns = new ArrayList<>(0); - private List includePatterns = new ArrayList<>(0); + private final List excludePatterns; + private final List includePatterns; - private Filter filter; + private final Filter filter; /** * Creates a new RuleSet with the given checksum. * @param checksum A checksum of the ruleset, should change * only if the ruleset was configured differently + * @param rules The rules to be applied as part of this ruleset */ - public RuleSet(final long checksum) { - this.checksum = checksum; - } - - /** - * Creates a new RuleSet with a random checksum. - * Notice this means the results for this analysis will not be cached. - */ - public RuleSet() { - this(new Random().nextLong()); + private RuleSet(final RuleSetBuilder builder) { + checksum = builder.checksum; + fileName = builder.fileName; + name = builder.name; + description = builder.description ; + rules = builder.rules; + excludePatterns = Collections.unmodifiableList(builder.excludePatterns); + includePatterns = Collections.unmodifiableList(builder.includePatterns); + + final Filter regexFilter = Filters.buildRegexFilterIncludeOverExclude(includePatterns, excludePatterns); + filter = Filters.toNormalizedFileFilter(regexFilter); } - /** - * A convenience constructor - * - * @param name the rule set name - * @param theRules the rules to add to the rule set - * @return a new rule set with the given rules added - */ - public static RuleSet createFor(String name, Rule... theRules) { - - RuleSet rs = new RuleSet(); - rs.setName(name); - for (Rule rule : theRules) { - rs.addRule(rule); + /* package */ static class RuleSetBuilder { + public String description = ""; + public String name = ""; + public String fileName; + private final List rules = new ArrayList<>(); + private final List excludePatterns = new ArrayList<>(0); + private final List includePatterns = new ArrayList<>(0); + private final long checksum; + + /* package */ RuleSetBuilder(final long checksum) { + this.checksum = checksum; + } + + /** + * Add a new rule to this ruleset. Note that this method does not check for + * duplicates. + * + * @param rule the rule to be added + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRule(final Rule rule) { + if (rule == null) { + throw new IllegalArgumentException(MISSING_RULE); + } + rules.add(rule); + return this; + } + + /** + * Adds a rule. If a rule with the same name and language already existed + * before in the ruleset, then the new rule will replace it. This makes sure + * that the rule configured is overridden. + * + * @param rule the new rule to add + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleReplaceIfExists(final Rule rule) { + if (rule == null) { + throw new IllegalArgumentException(MISSING_RULE); + } + + for (final Iterator it = rules.iterator(); it.hasNext();) { + final Rule r = it.next(); + if (r.getName().equals(rule.getName()) && r.getLanguage() == rule.getLanguage()) { + it.remove(); + } + } + addRule(rule); + return this; + } + + /** + * Only adds a rule to the ruleset if no rule with the same name for the + * same language was added before, so that the existent rule configuration + * won't be overridden. + * + * @param rule the new rule to add + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleIfNotExists(final Rule rule) { + if (rule == null) { + throw new IllegalArgumentException(MISSING_RULE); + } + + boolean exists = false; + for (final Rule r : rules) { + if (r.getName().equals(rule.getName()) && r.getLanguage() == rule.getLanguage()) { + exists = true; + break; + } + } + if (!exists) { + addRule(rule); + } + return this; + } + + /** + * Add a new rule by reference to this ruleset. + * + * @param ruleSetFileName the ruleset which contains the rule + * @param rule the rule to be added + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleByReference(final String ruleSetFileName, final Rule rule) { + if (StringUtil.isEmpty(ruleSetFileName)) { + throw new RuntimeException("Adding a rule by reference is not allowed with an empty rule set file name."); + } + if (rule == null) { + throw new IllegalArgumentException("Cannot add a null rule reference to a RuleSet"); + } + final RuleReference ruleReference; + if (rule instanceof RuleReference) { + ruleReference = (RuleReference) rule; + } else { + final RuleSetReference ruleSetReference = new RuleSetReference(); + ruleSetReference.setRuleSetFileName(ruleSetFileName); + ruleReference = new RuleReference(); + ruleReference.setRule(rule); + ruleReference.setRuleSetReference(ruleSetReference); + } + rules.add(ruleReference); + return this; + } + + /** + * Add a whole RuleSet to this RuleSet + * + * @param ruleSet the RuleSet to add + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleSet(final RuleSet ruleSet) { + rules.addAll(rules.size(), ruleSet.getRules()); + return this; + } + + /** + * Add all rules by reference from one RuleSet to this RuleSet. The rules + * can be added as individual references, or collectively as an all rule + * reference. + * + * @param ruleSet the RuleSet to add + * @param allRules true if the ruleset should be added + * collectively or false to add individual + * references for each rule. + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleSetByReference(final RuleSet ruleSet, final boolean allRules) { + return addRuleSetByReference(ruleSet, allRules, (String[]) null); + } + + /** + * Add all rules by reference from one RuleSet to this RuleSet. The rules + * can be added as individual references, or collectively as an all rule + * reference. + * + * @param ruleSet the RuleSet to add + * @param allRules true if the ruleset should be added + * collectively or false to add individual + * references for each rule. + * @param excludes names of the rules that should be excluded. + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addRuleSetByReference(final RuleSet ruleSet, final boolean allRules, + final String... excludes) { + if (StringUtil.isEmpty(ruleSet.getFileName())) { + throw new RuntimeException("Adding a rule by reference is not allowed with an empty rule set file name."); + } + final RuleSetReference ruleSetReference = new RuleSetReference(ruleSet.getFileName()); + ruleSetReference.setAllRules(allRules); + if (excludes != null) { + ruleSetReference.setExcludes(new HashSet<>(Arrays.asList(excludes))); + } + for (final Rule rule : ruleSet.getRules()) { + final RuleReference ruleReference = new RuleReference(rule, ruleSetReference); + rules.add(ruleReference); + } + return this; + } + + /** + * Adds a new file exclusion pattern. + * + * @param aPattern the pattern + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addExcludePattern(final String aPattern) { + if (!excludePatterns.contains(aPattern)) { + excludePatterns.add(aPattern); + } + return this; + } + + /** + * Adds new file exclusion patterns. + * + * @param someExcludePatterns the patterns + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addExcludePatterns(final Collection someExcludePatterns) { + CollectionUtil.addWithoutDuplicates(someExcludePatterns, excludePatterns); + return this; + } + + /** + * Replaces the existing exclusion patterns with the given patterns. + * + * @param theExcludePatterns the new patterns + */ + public RuleSetBuilder setExcludePatterns(final Collection theExcludePatterns) { + if (!excludePatterns.equals(theExcludePatterns)) { + excludePatterns.clear(); + CollectionUtil.addWithoutDuplicates(theExcludePatterns, excludePatterns); + } + return this; + } + + /** + * Adds new inclusion patterns. + * + * @param someIncludePatterns the patterns + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addIncludePatterns(final Collection someIncludePatterns) { + CollectionUtil.addWithoutDuplicates(someIncludePatterns, includePatterns); + return this; + } + + /** + * Replaces the existing inclusion patterns with the given patterns. + * + * @param theIncludePatterns the new patterns + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder setIncludePatterns(final Collection theIncludePatterns) { + if (!includePatterns.equals(theIncludePatterns)) { + includePatterns.clear(); + CollectionUtil.addWithoutDuplicates(theIncludePatterns, includePatterns); + } + + return this; + } + + /** + * Adds a new inclusion pattern. + * + * @param aPattern the pattern + * @return The same builder, for a fluid programming interface + */ + public RuleSetBuilder addIncludePattern(final String aPattern) { + if (!includePatterns.contains(aPattern)) { + includePatterns.add(aPattern); + } + return this; + } + + public RuleSetBuilder withFileName(final String fileName) { + this.fileName = fileName; + return this; + } + + public RuleSetBuilder withName(final String name) { + this.name = name; + return this; + } + + public RuleSetBuilder withDescription(final String description) { + this.description = description; + return this; + } + + public String getName() { + return name; + } + + public RuleSet build() { + return new RuleSet(this); } - return rs; } /** @@ -93,98 +339,6 @@ public class RuleSet { return rules.size(); } - /** - * Add a new rule to this ruleset. Note that this method does not check for - * duplicates. - * - * @param rule the rule to be added - */ - public void addRule(Rule rule) { - if (rule == null) { - throw new IllegalArgumentException(MISSING_RULE); - } - rules.add(rule); - } - - /** - * Adds a rule. If a rule with the same name and language already existed - * before in the ruleset, then the new rule will replace it. This makes sure - * that the rule configured is overridden. - * - * @param rule the new rule to add - * @return true if the new rule replaced an existing one, - * otherwise false. - */ - public boolean addRuleReplaceIfExists(Rule rule) { - if (rule == null) { - throw new IllegalArgumentException(MISSING_RULE); - } - - boolean replaced = false; - for (Iterator it = rules.iterator(); it.hasNext();) { - Rule r = it.next(); - if (r.getName().equals(rule.getName()) && r.getLanguage() == rule.getLanguage()) { - it.remove(); - replaced = true; - } - } - addRule(rule); - return replaced; - } - - /** - * Only adds a rule to the ruleset if no rule with the same name for the - * same language was added before, so that the existent rule configuration - * won't be overridden. - * - * @param rule the new rule to add - * @return true if the rule was added, false - * otherwise - */ - public boolean addRuleIfNotExists(Rule rule) { - if (rule == null) { - throw new IllegalArgumentException(MISSING_RULE); - } - - boolean exists = false; - for (Rule r : rules) { - if (r.getName().equals(rule.getName()) && r.getLanguage() == rule.getLanguage()) { - exists = true; - break; - } - } - if (!exists) { - addRule(rule); - } - return !exists; - } - - /** - * Add a new rule by reference to this ruleset. - * - * @param ruleSetFileName the ruleset which contains the rule - * @param rule the rule to be added - */ - public void addRuleByReference(String ruleSetFileName, Rule rule) { - if (StringUtil.isEmpty(ruleSetFileName)) { - throw new RuntimeException("Adding a rule by reference is not allowed with an empty rule set file name."); - } - if (rule == null) { - throw new IllegalArgumentException("Cannot add a null rule reference to a RuleSet"); - } - RuleReference ruleReference; - if (rule instanceof RuleReference) { - ruleReference = (RuleReference) rule; - } else { - RuleSetReference ruleSetReference = new RuleSetReference(); - ruleSetReference.setRuleSetFileName(ruleSetFileName); - ruleReference = new RuleReference(); - ruleReference.setRule(rule); - ruleReference.setRuleSetReference(ruleSetReference); - } - rules.add(ruleReference); - } - /** * Returns the actual Collection of rules in this ruleset * @@ -229,55 +383,6 @@ public class RuleSet { return null; } - /** - * Add a whole RuleSet to this RuleSet - * - * @param ruleSet the RuleSet to add - */ - public void addRuleSet(RuleSet ruleSet) { - rules.addAll(rules.size(), ruleSet.getRules()); - } - - /** - * Add all rules by reference from one RuleSet to this RuleSet. The rules - * can be added as individual references, or collectively as an all rule - * reference. - * - * @param ruleSet the RuleSet to add - * @param allRules true if the ruleset should be added - * collectively or false to add individual - * references for each rule. - */ - public void addRuleSetByReference(RuleSet ruleSet, boolean allRules) { - addRuleSetByReference(ruleSet, allRules, (String[]) null); - } - - /** - * Add all rules by reference from one RuleSet to this RuleSet. The rules - * can be added as individual references, or collectively as an all rule - * reference. - * - * @param ruleSet the RuleSet to add - * @param allRules true if the ruleset should be added - * collectively or false to add individual - * references for each rule. - * @param excludes names of the rules that should be excluded. - */ - public void addRuleSetByReference(RuleSet ruleSet, boolean allRules, String... excludes) { - if (StringUtil.isEmpty(ruleSet.getFileName())) { - throw new RuntimeException("Adding a rule by reference is not allowed with an empty rule set file name."); - } - RuleSetReference ruleSetReference = new RuleSetReference(ruleSet.getFileName()); - ruleSetReference.setAllRules(allRules); - if (excludes != null) { - ruleSetReference.setExcludes(new HashSet<>(Arrays.asList(excludes))); - } - for (Rule rule : ruleSet.getRules()) { - RuleReference ruleReference = new RuleReference(rule, ruleSetReference); - rules.add(ruleReference); - } - } - /** * Check if a given source file should be checked by rules in this RuleSet. * A file should not be checked if there is an exclude pattern @@ -290,12 +395,6 @@ public class RuleSet { * false otherwise */ public boolean applies(File file) { - // Initialize filter based on patterns - if (filter == null) { - Filter regexFilter = Filters.buildRegexFilterIncludeOverExclude(includePatterns, excludePatterns); - filter = Filters.toNormalizedFileFilter(regexFilter); - } - return file != null ? filter.filter(file) : true; } @@ -404,121 +503,22 @@ public class RuleSet { return fileName; } - public void setFileName(String fileName) { - this.fileName = fileName; - } - public String getName() { return name; } - public void setName(String name) { - this.name = name; - } - public String getDescription() { return description; } - public void setDescription(String description) { - this.description = description; - } - public List getExcludePatterns() { return excludePatterns; } - /** - * Adds a new file exclusion pattern. - * - * @param aPattern the pattern - */ - public void addExcludePattern(String aPattern) { - if (excludePatterns.contains(aPattern)) { - return; - } - - excludePatterns.add(aPattern); - patternsChanged(); - } - - /** - * Adds new file exclusion patterns. - * - * @param someExcludePatterns the patterns - */ - public void addExcludePatterns(Collection someExcludePatterns) { - int added = CollectionUtil.addWithoutDuplicates(someExcludePatterns, excludePatterns); - if (added > 0) { - patternsChanged(); - } - } - - /** - * Replaces the existing exclusion patterns with the given patterns. - * - * @param theExcludePatterns the new patterns - */ - public void setExcludePatterns(Collection theExcludePatterns) { - if (excludePatterns.equals(theExcludePatterns)) { - return; - } - - excludePatterns.clear(); - CollectionUtil.addWithoutDuplicates(theExcludePatterns, excludePatterns); - patternsChanged(); - } - public List getIncludePatterns() { return includePatterns; } - /** - * Adds a new inclusion pattern. - * - * @param aPattern the pattern - */ - public void addIncludePattern(String aPattern) { - if (includePatterns.contains(aPattern)) { - return; - } - - includePatterns.add(aPattern); - patternsChanged(); - } - - /** - * Adds new inclusion patterns. - * - * @param someIncludePatterns the patterns - */ - public void addIncludePatterns(Collection someIncludePatterns) { - int added = CollectionUtil.addWithoutDuplicates(someIncludePatterns, includePatterns); - if (added > 0) { - patternsChanged(); - } - } - - /** - * Replaces the existing inclusion patterns with the given patterns. - * - * @param theIncludePatterns the new patterns - */ - public void setIncludePatterns(Collection theIncludePatterns) { - if (includePatterns.equals(theIncludePatterns)) { - return; - } - - includePatterns.clear(); - CollectionUtil.addWithoutDuplicates(theIncludePatterns, includePatterns); - patternsChanged(); - } - - private void patternsChanged() { - filter = null; // ensure we start with one that reflects the current - // patterns - } - /** * Does any Rule for the given Language use Type Resolution? * @@ -552,12 +552,7 @@ public class RuleSet { } } - /** - * Retrieves a checksum for this ruleset. Should take into account all - * rules and configuration, any changes should trigger a fingerprint change - * - * @return The ruleset's checksum - */ + @Override public long getChecksum() { return checksum; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java index db05119414..f2be1c68d8 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java @@ -29,11 +29,13 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import net.sourceforge.pmd.RuleSet.RuleSetBuilder; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.RuleReference; +import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.lang.rule.properties.PropertyDescriptorWrapper; import net.sourceforge.pmd.lang.rule.properties.factories.PropertyDescriptorUtil; import net.sourceforge.pmd.util.ResourceLoader; @@ -194,6 +196,25 @@ public class RuleSetFactory { return parseRuleSetNode(ruleSetReferenceId, withDeprecatedRuleReferences); } + /** + * Creates a new RuleSet for a single rule + * @param rule The rule being created + * @return The newly created RuleSet + */ + public RuleSet createSingleRuleRuleSet(final Rule rule) { + final long checksum; + if (rule instanceof XPathRule) { + checksum = rule.getProperty(XPathRule.XPATH_DESCRIPTOR).hashCode(); + } else { + // TODO : Is this good enough? all properties' values + rule name + checksum = rule.getPropertiesByPropertyDescriptor().values().hashCode() * 31 + rule.getName().hashCode(); + } + + final RuleSetBuilder builder = new RuleSetBuilder(checksum); + builder.addRule(rule); + return builder.build(); + } + /** * Create a Rule from a RuleSet created from a file name resource. The * currently configured ClassLoader is used. @@ -248,9 +269,9 @@ public class RuleSetFactory { Document document = builder.parse(inputSource); Element ruleSetElement = document.getDocumentElement(); - RuleSet ruleSet = new RuleSet(inputStream.getChecksum().getValue()); - ruleSet.setFileName(ruleSetReferenceId.getRuleSetFileName()); - ruleSet.setName(ruleSetElement.getAttribute("name")); + RuleSetBuilder ruleSetBuilder = new RuleSetBuilder(inputStream.getChecksum().getValue()) + .withFileName(ruleSetReferenceId.getRuleSetFileName()) + .withName(ruleSetElement.getAttribute("name")); NodeList nodeList = ruleSetElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { @@ -258,13 +279,13 @@ public class RuleSetFactory { if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = node.getNodeName(); if (DESCRIPTION.equals(nodeName)) { - ruleSet.setDescription(parseTextNode(node)); + ruleSetBuilder.withDescription(parseTextNode(node)); } else if ("include-pattern".equals(nodeName)) { - ruleSet.addIncludePattern(parseTextNode(node)); + ruleSetBuilder.addIncludePattern(parseTextNode(node)); } else if ("exclude-pattern".equals(nodeName)) { - ruleSet.addExcludePattern(parseTextNode(node)); + ruleSetBuilder.addExcludePattern(parseTextNode(node)); } else if ("rule".equals(nodeName)) { - parseRuleNode(ruleSetReferenceId, ruleSet, node, withDeprecatedRuleReferences); + parseRuleNode(ruleSetReferenceId, ruleSetBuilder, node, withDeprecatedRuleReferences); } else { throw new IllegalArgumentException(UNEXPECTED_ELEMENT + node.getNodeName() + "> encountered as child of element."); @@ -272,7 +293,7 @@ public class RuleSetFactory { } } - return ruleSet; + return ruleSetBuilder.build(); } catch (ClassNotFoundException cnfe) { return classNotFoundProblem(cnfe); } catch (InstantiationException ie) { @@ -298,22 +319,22 @@ public class RuleSetFactory { * * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being * parsed. - * @param ruleSet The RuleSet being constructed. + * @param ruleSetBuilder The RuleSet being constructed. * @param ruleNode Must be a rule element node. * @param withDeprecatedRuleReferences whether rule references that are * deprecated should be ignored or not */ - private void parseRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, + private void parseRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode, boolean withDeprecatedRuleReferences) throws ClassNotFoundException, InstantiationException, IllegalAccessException, RuleSetNotFoundException { Element ruleElement = (Element) ruleNode; String ref = ruleElement.getAttribute("ref"); if (ref.endsWith("xml")) { - parseRuleSetReferenceNode(ruleSetReferenceId, ruleSet, ruleElement, ref); + parseRuleSetReferenceNode(ruleSetReferenceId, ruleSetBuilder, ruleElement, ref); } else if (StringUtil.isEmpty(ref)) { - parseSingleRuleNode(ruleSetReferenceId, ruleSet, ruleNode); + parseSingleRuleNode(ruleSetReferenceId, ruleSetBuilder, ruleNode); } else { - parseRuleReferenceNode(ruleSetReferenceId, ruleSet, ruleNode, ref, withDeprecatedRuleReferences); + parseRuleReferenceNode(ruleSetReferenceId, ruleSetBuilder, ruleNode, ref, withDeprecatedRuleReferences); } } @@ -325,11 +346,11 @@ public class RuleSetFactory { * * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being * parsed. - * @param ruleSet The RuleSet being constructed. + * @param ruleSetBuilder The RuleSet being constructed. * @param ruleElement Must be a rule element node. * @param ref The RuleSet reference. */ - private void parseRuleSetReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Element ruleElement, + private void parseRuleSetReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Element ruleElement, String ref) throws RuleSetNotFoundException { RuleSetReference ruleSetReference = new RuleSetReference(); ruleSetReference.setAllRules(true); @@ -357,7 +378,7 @@ public class RuleSetFactory { RuleReference ruleReference = new RuleReference(); ruleReference.setRuleSetReference(ruleSetReference); ruleReference.setRule(rule); - ruleSet.addRuleIfNotExists(ruleReference); + ruleSetBuilder.addRuleIfNotExists(ruleReference); // override the priority if (priority != null) { @@ -377,10 +398,10 @@ public class RuleSetFactory { * * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being * parsed. - * @param ruleSet The RuleSet being constructed. + * @param ruleSetBuilder The RuleSet being constructed. * @param ruleNode Must be a rule element node. */ - private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode) + private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; @@ -452,7 +473,7 @@ public class RuleSetFactory { rule.setSince(since); } rule.setMessage(ruleElement.getAttribute(MESSAGE)); - rule.setRuleSetName(ruleSet.getName()); + rule.setRuleSetName(ruleSetBuilder.getName()); rule.setExternalInfoUrl(ruleElement.getAttribute(EXTERNAL_INFO_URL)); if (hasAttributeSetTrue(ruleElement, "dfa")) { @@ -486,7 +507,7 @@ public class RuleSetFactory { } if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) || rule.getPriority().compareTo(minimumPriority) <= 0) { - ruleSet.addRule(rule); + ruleSetBuilder.addRule(rule); } } @@ -501,13 +522,13 @@ public class RuleSetFactory { * * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being * parsed. - * @param ruleSet The RuleSet being constructed. + * @param ruleSetBuilder The RuleSet being constructed. * @param ruleNode Must be a rule element node. * @param ref A reference to a Rule. * @param withDeprecatedRuleReferences whether rule references that are * deprecated should be ignored or not */ - private void parseRuleReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, + private void parseRuleReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode, String ref, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { Element ruleElement = (Element) ruleNode; @@ -603,7 +624,7 @@ public class RuleSetFactory { if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) || referencedRule.getPriority().compareTo(minimumPriority) <= 0) { if (withDeprecatedRuleReferences || !isSameRuleSet || !ruleReference.isDeprecated()) { - ruleSet.addRuleReplaceIfExists(ruleReference); + ruleSetBuilder.addRuleReplaceIfExists(ruleReference); } } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java index 21ce4aea4c..eb55f84882 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java @@ -159,13 +159,13 @@ public class Benchmarker { */ private static void stress(LanguageVersion languageVersion, RuleSet ruleSet, List dataSources, Set results, boolean debug) throws PMDException, IOException { + final RuleSetFactory factory = new RuleSetFactory(); for (Rule rule: ruleSet.getRules()) { if (debug) { System.out.println("Starting " + rule.getName()); } - RuleSet working = new RuleSet(); - working.addRule(rule); + final RuleSet working = factory.createSingleRuleRuleSet(rule); RuleSets ruleSets = new RuleSets(working); PMDConfiguration config = new PMDConfiguration(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/ChecksumAware.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/ChecksumAware.java new file mode 100644 index 0000000000..acd2e1d2c6 --- /dev/null +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/ChecksumAware.java @@ -0,0 +1,19 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ +package net.sourceforge.pmd.cache; + +/** + * Interface defining an object that has a checksum + * The checksum is a fingerprint of the object's configuration, + * and *MUST* change if anything changed on the object. + * It differs from a {@code hashCode()} in that a {@code hashCode()} may not + * take all fields into account, but a checksum must do so. + */ +public interface ChecksumAware { + /** + * Retrieves the current instance checksum + * @return The current checksum + */ + long getChecksum(); +} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cli/XPathCLI.java b/pmd-core/src/main/java/net/sourceforge/pmd/cli/XPathCLI.java deleted file mode 100644 index 91a91978fd..0000000000 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cli/XPathCLI.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ -package net.sourceforge.pmd.cli; - -import java.io.File; -import java.io.FileReader; -import java.util.Iterator; - -import net.sourceforge.pmd.PMD; -import net.sourceforge.pmd.PMDConfiguration; -import net.sourceforge.pmd.Rule; -import net.sourceforge.pmd.RuleContext; -import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSets; -import net.sourceforge.pmd.RuleViolation; -import net.sourceforge.pmd.SourceCodeProcessor; -import net.sourceforge.pmd.lang.Language; -import net.sourceforge.pmd.lang.LanguageRegistry; -import net.sourceforge.pmd.lang.rule.XPathRule; -import net.sourceforge.pmd.util.StringUtil; - -/** - * To use this, do this: - * - * $ cat ~/tmp/Test.java - * package foo; - * public class Test { - * private int x; - * } - * $ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration" -filename "/home/tom/tmp/Test.java" - * Match at line 3 column 11; package name 'foo'; variable name 'x' - */ -public class XPathCLI { - - private static final Language LANGUAGE = LanguageRegistry.getLanguage("Java"); - - public static void main(String[] args) throws Exception { - if (args.length != 4) { - System.err.println("Wrong arguments.\n"); - System.err.println("Example:"); - System.err.println("java " + XPathCLI.class.getName() + " -xpath \"//FieldDeclaration\" -filename \"/home/user/Test.java\""); - System.exit(1); - } - - String xpath = args[0].equals("-xpath") ? args[1] : args[3]; - String filename = args[0].equals("-file") ? args[1] : args[3]; - - Rule rule = new XPathRule(xpath); - rule.setMessage("Got one!"); - rule.setLanguage(LANGUAGE); - RuleSet ruleSet = RuleSet.createFor("", rule); - - RuleContext ctx = PMD.newRuleContext(filename, new File(filename)); - ctx.setLanguageVersion(LANGUAGE.getDefaultVersion()); - - PMDConfiguration config = new PMDConfiguration(); - config.setDefaultLanguageVersion(LANGUAGE.getDefaultVersion()); - - new SourceCodeProcessor(config).processSourceCode(new FileReader(filename), new RuleSets(ruleSet), ctx); - - for (Iterator i = ctx.getReport().iterator(); i.hasNext();) { - RuleViolation rv = i.next(); - StringBuilder sb = new StringBuilder(60) - .append("Match at line ").append(rv.getBeginLine()) - .append(" column ").append(rv.getBeginColumn()); - if (StringUtil.isNotEmpty(rv.getPackageName())) { - sb.append("; package name '" + rv.getPackageName() + "'"); - } - if (StringUtil.isNotEmpty(rv.getMethodName())) { - sb.append("; method name '" + rv.getMethodName() + "'"); - } - if (StringUtil.isNotEmpty(rv.getVariableName())) { - sb.append("; variable name '" + rv.getVariableName() + "'"); - } - System.out.println(sb.toString()); - } - } -} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/designer/Designer.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/designer/Designer.java index 722f5a8562..d4c25d9642 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/designer/Designer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/designer/Designer.java @@ -101,6 +101,7 @@ import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.SourceCodeProcessor; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -560,25 +561,22 @@ public class Designer implements ClipboardOwner { LanguageVersion languageVersion = getLanguageVersion(); DFAGraphRule dfaGraphRule = languageVersion.getLanguageVersionHandler().getDFAGraphRule(); - RuleSet rs = new RuleSet(); if (dfaGraphRule != null) { - rs.addRule(dfaGraphRule); - } - RuleContext ctx = new RuleContext(); - ctx.setSourceCodeFilename("[no filename]." + languageVersion.getLanguage().getExtensions().get(0)); - StringReader reader = new StringReader(codeEditorPane.getText()); - PMDConfiguration config = new PMDConfiguration(); - config.setDefaultLanguageVersion(languageVersion); + final RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(dfaGraphRule); + RuleContext ctx = new RuleContext(); + ctx.setSourceCodeFilename("[no filename]." + languageVersion.getLanguage().getExtensions().get(0)); + StringReader reader = new StringReader(codeEditorPane.getText()); + PMDConfiguration config = new PMDConfiguration(); + config.setDefaultLanguageVersion(languageVersion); + + try { + new SourceCodeProcessor(config).processSourceCode(reader, new RuleSets(rs), ctx); + // } catch (PMDException pmde) { + // loadTreeData(new ExceptionNode(pmde)); + } catch (Exception e) { + e.printStackTrace(); + } - try { - new SourceCodeProcessor(config).processSourceCode(reader, new RuleSets(rs), ctx); - // } catch (PMDException pmde) { - // loadTreeData(new ExceptionNode(pmde)); - } catch (Exception e) { - e.printStackTrace(); - } - - if (dfaGraphRule != null) { List methods = dfaGraphRule.getMethods(); if (methods != null && !methods.isEmpty()) { dfaPanel.resetTo(methods, codeEditorPane); @@ -611,8 +609,7 @@ public class Designer implements ClipboardOwner { xpathRule.setXPath(xpathQueryArea.getText()); xpathRule.setVersion(xpathVersionButtonGroup.getSelection().getActionCommand()); - RuleSet ruleSet = new RuleSet(); - ruleSet.addRule(xpathRule); + final RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(xpathRule); RuleSets ruleSets = new RuleSets(ruleSet); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java index f6ca1b89d1..e8c5118a06 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java @@ -15,8 +15,12 @@ import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Random; import java.util.Set; +import org.junit.Test; + +import net.sourceforge.pmd.RuleSet.RuleSetBuilder; import net.sourceforge.pmd.lang.Dummy2LanguageModule; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -25,355 +29,389 @@ import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.RuleReference; -import org.junit.Test; - - public class RuleSetTest { private String javaCode = "public class Test { }"; @Test public void testNoDFA() { - RuleSet rs = new RuleSet(); - MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - rs.addRule(mock); - assertFalse(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); + MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); + mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); + RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + assertFalse(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); } @Test public void testIncludesRuleWithDFA() { - RuleSet rs = new RuleSet(); - MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - mock.setUsesDFA(); - rs.addRule(mock); - assertTrue(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); + MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); + mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); + mock.setUsesDFA(); + RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + assertTrue(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); } @Test public void testAccessors() { - RuleSet rs = new RuleSet(); - rs.setFileName("baz"); - assertEquals("file name mismatch", "baz", rs.getFileName()); - rs.setName("foo"); - assertEquals("name mismatch", "foo", rs.getName()); - rs.setDescription("bar"); - assertEquals("description mismatch", "bar", rs.getDescription()); + RuleSet rs = new RuleSetBuilder(new Random().nextLong()) + .withFileName("baz") + .withName("foo") + .withDescription("bar") + .build(); + assertEquals("file name mismatch", "baz", rs.getFileName()); + assertEquals("name mismatch", "foo", rs.getName()); + assertEquals("description mismatch", "bar", rs.getDescription()); } @Test public void testGetRuleByName() { - RuleSet rs = new RuleSet(); - MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - rs.addRule(mock); - assertEquals("unable to fetch rule by name", mock, rs.getRuleByName("name")); + MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); + RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + assertEquals("unable to fetch rule by name", mock, rs.getRuleByName("name")); } @Test public void testGetRuleByName2() { - RuleSet rs = new RuleSet(); - MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - rs.addRule(mock); - assertNull("the rule FooRule must not be found!", rs.getRuleByName("FooRule")); + MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); + RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + assertNull("the rule FooRule must not be found!", rs.getRuleByName("FooRule")); } @Test public void testRuleList() { - RuleSet IUT = new RuleSet(); + MockRule rule = new MockRule("name", "desc", "msg", "rulesetname"); + RuleSet IUT = new RuleSetFactory().createSingleRuleRuleSet(rule); - assertEquals("Size of RuleSet isn't zero.", 0, IUT.size()); + assertEquals("Size of RuleSet isn't one.", 1, IUT.size()); - MockRule rule = new MockRule("name", "desc", "msg", "rulesetname"); - IUT.addRule(rule); + Collection rules = IUT.getRules(); - assertEquals("Size of RuleSet isn't one.", 1, IUT.size()); - - Collection rules = IUT.getRules(); - - Iterator i = rules.iterator(); - assertTrue("Empty Set", i.hasNext()); - assertEquals("Returned set of wrong size.", 1, rules.size()); - assertEquals("Rule isn't in ruleset.", rule, i.next()); + Iterator i = rules.iterator(); + assertTrue("Empty Set", i.hasNext()); + assertEquals("Returned set of wrong size.", 1, rules.size()); + assertEquals("Rule isn't in ruleset.", rule, i.next()); } @Test public void testAddRuleSet() { - RuleSet set1 = new RuleSet(); - set1.addRule(new MockRule("name", "desc", "msg", "rulesetname")); - RuleSet set2 = new RuleSet(); - set2.addRule(new MockRule("name2", "desc", "msg", "rulesetname")); - set1.addRuleSet(set2); - assertEquals("ruleset size wrong", 2, set1.size()); + RuleSet set1 = new RuleSetBuilder(new Random().nextLong()) + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); + RuleSet set2 = new RuleSetBuilder(new Random().nextLong()) + .addRule(new MockRule("name2", "desc", "msg", "rulesetname")) + .addRuleSet(set1) + .build(); + assertEquals("ruleset size wrong", 2, set2.size()); } @Test(expected = RuntimeException.class) public void testAddRuleSetByReferenceBad() { - RuleSet set1 = new RuleSet(); - set1.addRule(new MockRule("name", "desc", "msg", "rulesetname")); - RuleSet set2 = new RuleSet(); - set2.addRule(new MockRule("name2", "desc", "msg", "rulesetname")); - set1.addRuleSetByReference(set2, false); + RuleSet set1 = new RuleSetBuilder(new Random().nextLong()) + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); + RuleSet set2 = new RuleSetBuilder(new Random().nextLong()) + .addRule(new MockRule("name2", "desc", "msg", "rulesetname")) + .addRuleSetByReference(set1, false) + .build(); } @Test public void testAddRuleSetByReferenceAllRule() { - RuleSet set1 = new RuleSet(); - RuleSet set2 = new RuleSet(); - set2.setFileName("foo"); - set2.addRule(new MockRule("name", "desc", "msg", "rulesetname")); - set2.addRule(new MockRule("name2", "desc", "msg", "rulesetname")); - set1.addRuleSetByReference(set2, true); - assertEquals("wrong rule size", 2, set1.getRules().size()); - for (Rule rule : set1.getRules()) { - assertTrue("not a rule reference", rule instanceof RuleReference); - RuleReference ruleReference = (RuleReference) rule; - assertEquals("wrong ruleset file name", "foo", ruleReference.getRuleSetReference().getRuleSetFileName()); - assertTrue("not all rule reference", ruleReference.getRuleSetReference().isAllRules()); - } + RuleSet set2 = new RuleSetBuilder(new Random().nextLong()) + .withFileName("foo") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .addRule(new MockRule("name2", "desc", "msg", "rulesetname")) + .build(); + RuleSet set1 = new RuleSetBuilder(new Random().nextLong()) + .addRuleSetByReference(set2, true) + .build(); + assertEquals("wrong rule size", 2, set1.getRules().size()); + for (Rule rule : set1.getRules()) { + assertTrue("not a rule reference", rule instanceof RuleReference); + RuleReference ruleReference = (RuleReference) rule; + assertEquals("wrong ruleset file name", "foo", ruleReference.getRuleSetReference().getRuleSetFileName()); + assertTrue("not all rule reference", ruleReference.getRuleSetReference().isAllRules()); + } } @Test public void testAddRuleSetByReferenceSingleRule() { - RuleSet set1 = new RuleSet(); - RuleSet set2 = new RuleSet(); - set2.setFileName("foo"); - set2.addRule(new MockRule("name", "desc", "msg", "rulesetname")); - set2.addRule(new MockRule("name2", "desc", "msg", "rulesetname")); - set1.addRuleSetByReference(set2, false); - assertEquals("wrong rule size", 2, set1.getRules().size()); - for (Rule rule : set1.getRules()) { - assertTrue("not a rule reference", rule instanceof RuleReference); - RuleReference ruleReference = (RuleReference) rule; - assertEquals("wrong ruleset file name", "foo", ruleReference.getRuleSetReference().getRuleSetFileName()); - assertFalse("should not be all rule reference", ruleReference.getRuleSetReference().isAllRules()); - } + RuleSet set2 = new RuleSetBuilder(new Random().nextLong()) + .withFileName("foo") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .addRule(new MockRule("name2", "desc", "msg", "rulesetname")) + .build(); + RuleSet set1 = new RuleSetBuilder(new Random().nextLong()) + .addRuleSetByReference(set2, false) + .build(); + assertEquals("wrong rule size", 2, set1.getRules().size()); + for (Rule rule : set1.getRules()) { + assertTrue("not a rule reference", rule instanceof RuleReference); + RuleReference ruleReference = (RuleReference) rule; + assertEquals("wrong ruleset file name", "foo", ruleReference.getRuleSetReference().getRuleSetFileName()); + assertFalse("should not be all rule reference", ruleReference.getRuleSetReference().isAllRules()); + } } @Test public void testApply0Rules() throws Throwable { - RuleSet IUT = new RuleSet(); - verifyRuleSet(IUT, 0, new HashSet()); + RuleSet IUT = new RuleSetBuilder(new Random().nextLong()).build(); + verifyRuleSet(IUT, 0, new HashSet()); } @Test public void testEquals1() { - RuleSet s = new RuleSet(); - assertFalse("A ruleset cannot be equals to null", s.equals(null)); + RuleSet s = new RuleSetBuilder(new Random().nextLong()).build(); + assertFalse("A ruleset cannot be equals to null", s.equals(null)); } @Test @SuppressWarnings("PMD.UseAssertEqualsInsteadOfAssertTrue") public void testEquals2() { - RuleSet s = new RuleSet(); - assertTrue("A rulset must be equals to itself", s.equals(s)); + RuleSet s = new RuleSetBuilder(new Random().nextLong()).build(); + assertTrue("A rulset must be equals to itself", s.equals(s)); } @Test public void testEquals3() { - RuleSet s = new RuleSet(); - s.setName("basic rules"); - assertFalse("A ruleset cannot be equals to another kind of object", s.equals("basic rules")); + RuleSet s = new RuleSetBuilder(new Random().nextLong()) + .withName("basic rules") + .build(); + assertFalse("A ruleset cannot be equals to another kind of object", s.equals("basic rules")); } @Test public void testEquals4() { - RuleSet s1 = new RuleSet(); - s1.setName("my ruleset"); - s1.addRule(new MockRule("name", "desc", "msg", "rulesetname")); + RuleSet s1 = new RuleSetBuilder(new Random().nextLong()) + .withName("my ruleset") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); - RuleSet s2 = new RuleSet(); - s2.setName("my ruleset"); - s2.addRule(new MockRule("name", "desc", "msg", "rulesetname")); + RuleSet s2 = new RuleSetBuilder(new Random().nextLong()) + .withName("my ruleset") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); - assertEquals("2 rulesets with same name and rules must be equals", s1, s2); - assertEquals("Equals rulesets must have the same hashcode", s1.hashCode(), s2.hashCode()); + assertEquals("2 rulesets with same name and rules must be equals", s1, s2); + assertEquals("Equals rulesets must have the same hashcode", s1.hashCode(), s2.hashCode()); } @Test public void testEquals5() { - RuleSet s1 = new RuleSet(); - s1.setName("my ruleset"); - s1.addRule(new MockRule("name", "desc", "msg", "rulesetname")); + RuleSet s1 = new RuleSetBuilder(new Random().nextLong()) + .withName("my ruleset") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); - RuleSet s2 = new RuleSet(); - s2.setName("my other ruleset"); - s2.addRule(new MockRule("name", "desc", "msg", "rulesetname")); + RuleSet s2 = new RuleSetBuilder(new Random().nextLong()) + .withName("my other ruleset") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); - assertFalse("2 rulesets with different name but same rules must not be equals", s1.equals(s2)); + assertFalse("2 rulesets with different name but same rules must not be equals", s1.equals(s2)); } @Test public void testEquals6() { - RuleSet s1 = new RuleSet(); - s1.setName("my ruleset"); - s1.addRule(new MockRule("name", "desc", "msg", "rulesetname")); + RuleSet s1 = new RuleSetBuilder(new Random().nextLong()) + .withName("my ruleset") + .addRule(new MockRule("name", "desc", "msg", "rulesetname")) + .build(); - RuleSet s2 = new RuleSet(); - s2.setName("my ruleset"); - s2.addRule(new MockRule("other rule", "desc", "msg", "rulesetname")); + RuleSet s2 = new RuleSetBuilder(new Random().nextLong()) + .withName("my ruleset") + .addRule(new MockRule("other rule", "desc", "msg", "rulesetname")) + .build(); - assertFalse("2 rulesets with same name but different rules must not be equals", s1.equals(s2)); + assertFalse("2 rulesets with same name but different rules must not be equals", s1.equals(s2)); } - + @Test public void testLanguageApplies() { - Rule rule = new MockRule(); + Rule rule = new MockRule(); - rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - assertFalse("Different languages should not apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getDefaultVersion())); + rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); + assertFalse("Different languages should not apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getDefaultVersion())); - rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - assertTrue("Same language with no min/max should apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); + rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); + assertTrue("Same language with no min/max should apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); - rule.setMinimumLanguageVersion(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5")); - assertTrue("Same language with valid min only should apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); + rule.setMinimumLanguageVersion(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5")); + assertTrue("Same language with valid min only should apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); - rule.setMaximumLanguageVersion(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.6")); - assertTrue("Same language with valid min and max should apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); - assertFalse("Same language with outside range of min/max should not apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.4"))); - assertFalse("Same language with outside range of min/max should not apply", RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"))); + rule.setMaximumLanguageVersion(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.6")); + assertTrue("Same language with valid min and max should apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.5"))); + assertFalse("Same language with outside range of min/max should not apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.4"))); + assertFalse("Same language with outside range of min/max should not apply", + RuleSet.applies(rule, LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"))); } @Test public void testAddExcludePattern() { - RuleSet ruleSet = new RuleSet(); - ruleSet.addExcludePattern("*"); - assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); - assertEquals("Invalid number of patterns", 1, ruleSet.getExcludePatterns().size()); - ruleSet.addExcludePattern("*"); // try to create a duplicate - assertEquals("Invalid number of patterns", 1, ruleSet.getExcludePatterns().size()); - assertEquals("Exclude pattern", "*", ruleSet.getExcludePatterns().get(0)); - assertNotNull("Include patterns", ruleSet.getIncludePatterns()); - assertEquals("Invalid number of include patterns", 0, ruleSet.getIncludePatterns().size()); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("*") + .build(); + assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); + assertEquals("Invalid number of patterns", 1, ruleSet.getExcludePatterns().size()); + + RuleSet ruleSet2 = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("*") + .addExcludePattern("*") // try to create a duplicate + .build(); + assertEquals("Invalid number of patterns", 1, ruleSet2.getExcludePatterns().size()); + assertEquals("Exclude pattern", "*", ruleSet2.getExcludePatterns().get(0)); + assertNotNull("Include patterns", ruleSet2.getIncludePatterns()); + assertEquals("Invalid number of include patterns", 0, ruleSet2.getIncludePatterns().size()); } @Test public void testAddExcludePatterns() { - RuleSet ruleSet = new RuleSet(); - ruleSet.addExcludePattern("*"); - ruleSet.addExcludePattern(".*"); - RuleSet ruleSet2 = new RuleSet(); - ruleSet2.addExcludePatterns(ruleSet.getExcludePatterns()); - assertNotNull("Exclude patterns", ruleSet2.getExcludePatterns()); - assertEquals("Invalid number of patterns", 2, ruleSet2.getExcludePatterns().size()); - ruleSet.addExcludePattern(".*"); // try to create a duplicate - assertEquals("Invalid number of patterns", 2, ruleSet2.getExcludePatterns().size()); - assertEquals("Exclude pattern", "*", ruleSet2.getExcludePatterns().get(0)); - assertEquals("Exclude pattern", ".*", ruleSet2.getExcludePatterns().get(1)); - assertNotNull("Include patterns", ruleSet2.getIncludePatterns()); - assertEquals("Invalid number of include patterns", 0, ruleSet2.getIncludePatterns().size()); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("*") + .addExcludePattern(".*") + .build(); + RuleSet ruleSet2 = new RuleSetBuilder(new Random().nextLong()) + .addExcludePatterns(ruleSet.getExcludePatterns()) + .build(); + assertNotNull("Exclude patterns", ruleSet2.getExcludePatterns()); + assertEquals("Invalid number of patterns", 2, ruleSet2.getExcludePatterns().size()); + + RuleSet ruleSet3 = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("*") + .addExcludePattern(".*") + .addExcludePattern(".*") // try to create a duplicate + .build(); + assertEquals("Invalid number of patterns", 2, ruleSet3.getExcludePatterns().size()); + assertEquals("Exclude pattern", "*", ruleSet3.getExcludePatterns().get(0)); + assertEquals("Exclude pattern", ".*", ruleSet3.getExcludePatterns().get(1)); + assertNotNull("Include patterns", ruleSet3.getIncludePatterns()); + assertEquals("Invalid number of include patterns", 0, ruleSet3.getIncludePatterns().size()); } @Test public void testSetExcludePatterns() { - List excludePatterns = new ArrayList<>(); - excludePatterns.add("*"); - excludePatterns.add(".*"); - RuleSet ruleSet = new RuleSet(); - ruleSet.setExcludePatterns(excludePatterns); - assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); - assertEquals("Invalid number of exclude patterns", 2, ruleSet.getExcludePatterns().size()); - assertEquals("Exclude pattern", "*", ruleSet.getExcludePatterns().get(0)); - assertEquals("Exclude pattern", ".*", ruleSet.getExcludePatterns().get(1)); - assertNotNull("Include patterns", ruleSet.getIncludePatterns()); - assertEquals("Invalid number of include patterns", 0, ruleSet.getIncludePatterns().size()); + List excludePatterns = new ArrayList<>(); + excludePatterns.add("*"); + excludePatterns.add(".*"); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .setExcludePatterns(excludePatterns) + .build(); + assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); + assertEquals("Invalid number of exclude patterns", 2, ruleSet.getExcludePatterns().size()); + assertEquals("Exclude pattern", "*", ruleSet.getExcludePatterns().get(0)); + assertEquals("Exclude pattern", ".*", ruleSet.getExcludePatterns().get(1)); + assertNotNull("Include patterns", ruleSet.getIncludePatterns()); + assertEquals("Invalid number of include patterns", 0, ruleSet.getIncludePatterns().size()); } @Test public void testAddIncludePattern() { - RuleSet ruleSet = new RuleSet(); - ruleSet.addIncludePattern("*"); - assertNotNull("Include patterns", ruleSet.getIncludePatterns()); - assertEquals("Invalid number of patterns", 1, ruleSet.getIncludePatterns().size()); - assertEquals("Include pattern", "*", ruleSet.getIncludePatterns().get(0)); - assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); - assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addIncludePattern("*") + .build(); + assertNotNull("Include patterns", ruleSet.getIncludePatterns()); + assertEquals("Invalid number of patterns", 1, ruleSet.getIncludePatterns().size()); + assertEquals("Include pattern", "*", ruleSet.getIncludePatterns().get(0)); + assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); + assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); } @Test public void testAddIncludePatterns() { - RuleSet ruleSet = new RuleSet(); - ruleSet.addIncludePattern("*"); - ruleSet.addIncludePattern(".*"); - RuleSet ruleSet2 = new RuleSet(); - ruleSet2.addIncludePatterns(ruleSet.getIncludePatterns()); - assertNotNull("Include patterns", ruleSet2.getIncludePatterns()); - assertEquals("Invalid number of patterns", 2, ruleSet2.getIncludePatterns().size()); - assertEquals("Include pattern", "*", ruleSet2.getIncludePatterns().get(0)); - assertEquals("Include pattern", ".*", ruleSet2.getIncludePatterns().get(1)); - assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); - assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addIncludePattern("*") + .addIncludePattern(".*") + .build(); + RuleSet ruleSet2 = new RuleSetBuilder(new Random().nextLong()) + .addIncludePatterns(ruleSet.getIncludePatterns()) + .build(); + assertNotNull("Include patterns", ruleSet2.getIncludePatterns()); + assertEquals("Invalid number of patterns", 2, ruleSet2.getIncludePatterns().size()); + assertEquals("Include pattern", "*", ruleSet2.getIncludePatterns().get(0)); + assertEquals("Include pattern", ".*", ruleSet2.getIncludePatterns().get(1)); + assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); + assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); } @Test public void testSetIncludePatterns() { - List includePatterns = new ArrayList<>(); - includePatterns.add("*"); - includePatterns.add(".*"); - RuleSet ruleSet = new RuleSet(); - ruleSet.setIncludePatterns(includePatterns); - assertNotNull("Include patterns", ruleSet.getIncludePatterns()); - assertEquals("Invalid number of include patterns", 2, ruleSet.getIncludePatterns().size()); - assertEquals("Include pattern", "*", ruleSet.getIncludePatterns().get(0)); - assertEquals("Include pattern", ".*", ruleSet.getIncludePatterns().get(1)); - assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); - assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); + List includePatterns = new ArrayList<>(); + includePatterns.add("*"); + includePatterns.add(".*"); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .setIncludePatterns(includePatterns) + .build(); + assertNotNull("Include patterns", ruleSet.getIncludePatterns()); + assertEquals("Invalid number of include patterns", 2, ruleSet.getIncludePatterns().size()); + assertEquals("Include pattern", "*", ruleSet.getIncludePatterns().get(0)); + assertEquals("Include pattern", ".*", ruleSet.getIncludePatterns().get(1)); + assertNotNull("Exclude patterns", ruleSet.getExcludePatterns()); + assertEquals("Invalid number of exclude patterns", 0, ruleSet.getExcludePatterns().size()); } @Test public void testIncludeExcludeApplies() { - File file = new File("C:\\myworkspace\\project\\some\\random\\package\\RandomClass.java"); + File file = new File("C:\\myworkspace\\project\\some\\random\\package\\RandomClass.java"); - RuleSet ruleSet = new RuleSet(); - assertTrue("No patterns", ruleSet.applies(file)); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()).build(); + assertTrue("No patterns", ruleSet.applies(file)); - ruleSet = new RuleSet(); - ruleSet.addExcludePattern("nomatch"); - assertTrue("Non-matching exclude", ruleSet.applies(file)); + ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("nomatch") + .build(); + assertTrue("Non-matching exclude", ruleSet.applies(file)); - ruleSet = new RuleSet(); - ruleSet.addExcludePattern("nomatch"); - ruleSet.addExcludePattern(".*/package/.*"); - assertFalse("Matching exclude", ruleSet.applies(file)); + ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("nomatch") + .addExcludePattern(".*/package/.*") + .build(); + assertFalse("Matching exclude", ruleSet.applies(file)); - ruleSet = new RuleSet(); - ruleSet.addExcludePattern("nomatch"); - ruleSet.addExcludePattern(".*/package/.*"); - ruleSet.addIncludePattern(".*/randomX/.*"); - assertFalse("Non-matching include", ruleSet.applies(file)); + ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("nomatch") + .addExcludePattern(".*/package/.*") + .addIncludePattern(".*/randomX/.*") + .build(); + assertFalse("Non-matching include", ruleSet.applies(file)); - ruleSet = new RuleSet(); - ruleSet.addExcludePattern("nomatch"); - ruleSet.addExcludePattern(".*/package/.*"); - ruleSet.addIncludePattern(".*/randomX/.*"); - ruleSet.addIncludePattern(".*/random/.*"); - assertTrue("Matching include", ruleSet.applies(file)); + ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addExcludePattern("nomatch") + .addExcludePattern(".*/package/.*") + .addIncludePattern(".*/randomX/.*") + .addIncludePattern(".*/random/.*") + .build(); + assertTrue("Matching include", ruleSet.applies(file)); } @Test public void testIncludeExcludeMultipleRuleSetWithRuleChainApplies() throws PMDException { - File file = new File("C:\\myworkspace\\project\\some\\random\\package\\RandomClass.java"); + File file = new File("C:\\myworkspace\\project\\some\\random\\package\\RandomClass.java"); - RuleSet ruleSet1 = new RuleSet(); - ruleSet1.setName("RuleSet1"); - Rule rule = new FooRule(); - rule.setName("FooRule1"); - rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - rule.addRuleChainVisit("dummyNode"); - assertTrue("RuleChain rule", rule.usesRuleChain()); - ruleSet1.addRule(rule); + Rule rule = new FooRule(); + rule.setName("FooRule1"); + rule.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); + rule.addRuleChainVisit("dummyNode"); + assertTrue("RuleChain rule", rule.usesRuleChain()); + RuleSet ruleSet1 = new RuleSetBuilder(new Random().nextLong()) + .withName("RuleSet1") + .addRule(rule) + .build(); - RuleSet ruleSet2 = new RuleSet(); - ruleSet2.setName("RuleSet2"); - ruleSet2.addRule(rule); + RuleSet ruleSet2 = new RuleSetBuilder(new Random().nextLong()) + .withName("RuleSet2") + .addRule(rule) + .build(); - RuleSets ruleSets = new RuleSets(); - ruleSets.addRuleSet(ruleSet1); - ruleSets.addRuleSet(ruleSet2); + RuleSets ruleSets = new RuleSets(); + ruleSets.addRuleSet(ruleSet1); + ruleSets.addRuleSet(ruleSet2); - // Two violations + // Two violations PMD p = new PMD(); RuleContext ctx = new RuleContext(); Report r = new Report(); @@ -385,14 +423,15 @@ public class RuleSetTest { assertEquals("Violations", 2, r.size()); // One violation - ruleSet1 = new RuleSet(); - ruleSet1.setName("RuleSet1"); - ruleSet1.addExcludePattern(".*/package/.*"); - ruleSet1.addRule(rule); + ruleSet1 = new RuleSetBuilder(new Random().nextLong()) + .withName("RuleSet1") + .addExcludePattern(".*/package/.*") + .addRule(rule) + .build(); - ruleSets = new RuleSets(); - ruleSets.addRuleSet(ruleSet1); - ruleSets.addRuleSet(ruleSet2); + ruleSets = new RuleSets(); + ruleSets.addRuleSet(ruleSet1); + ruleSets.addRuleSet(ruleSet2); r = new Report(); ctx.setReport(r); @@ -402,26 +441,26 @@ public class RuleSetTest { private void verifyRuleSet(RuleSet IUT, int size, Set values) throws Throwable { - RuleContext context = new RuleContext(); - Set reportedValues = new HashSet<>(); - context.setReport(new Report()); - IUT.apply(makeCompilationUnits(), context); + RuleContext context = new RuleContext(); + Set reportedValues = new HashSet<>(); + context.setReport(new Report()); + IUT.apply(makeCompilationUnits(), context); - assertEquals("Invalid number of Violations Reported", size, context.getReport().size()); + assertEquals("Invalid number of Violations Reported", size, context.getReport().size()); - Iterator violations = context.getReport().iterator(); - while (violations.hasNext()) { - RuleViolation violation = (RuleViolation) violations.next(); + Iterator violations = context.getReport().iterator(); + while (violations.hasNext()) { + RuleViolation violation = (RuleViolation) violations.next(); - reportedValues.add(violation); - assertTrue("Unexpected Violation Returned: " + violation, values.contains(violation)); - } + reportedValues.add(violation); + assertTrue("Unexpected Violation Returned: " + violation, values.contains(violation)); + } - Iterator expected = values.iterator(); - while (expected.hasNext()) { - RuleViolation violation = (RuleViolation) expected.next(); - assertTrue("Expected Violation not Returned: " + violation, reportedValues.contains(violation)); - } + Iterator expected = values.iterator(); + while (expected.hasNext()) { + RuleViolation violation = (RuleViolation) expected.next(); + assertTrue("Expected Violation not Returned: " + violation, reportedValues.contains(violation)); + } } private List makeCompilationUnits() { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java index fe1b4567b1..ed323c4024 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java @@ -4,8 +4,10 @@ package net.sourceforge.pmd; import java.io.ByteArrayOutputStream; +import java.util.Random; import net.sourceforge.pmd.lang.rule.RuleReference; +import net.sourceforge.pmd.RuleSet.RuleSetBuilder; import org.junit.After; import org.junit.Assert; @@ -46,9 +48,10 @@ public class RuleSetWriterTest { */ @Test public void testWrite() throws Exception { - RuleSet ruleSet = new RuleSet(); RuleSet braces = new RuleSetFactory().createRuleSet("net/sourceforge/pmd/TestRuleset1.xml"); - ruleSet.addRuleSetByReference(braces, true, "MockRule2"); + RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) + .addRuleSetByReference(braces, true, "MockRule2") + .build(); writer.write(ruleSet); @@ -72,8 +75,7 @@ public class RuleSetWriterTest { ruleRef.setRuleSetReference(ruleSetReference); ruleRef.setName("Foo"); // override the name - RuleSet ruleSet = new RuleSet(); - ruleSet.addRule(ruleRef); + RuleSet ruleSet = ruleSetFactory.createSingleRuleRuleSet(ruleRef); writer.write(ruleSet); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java index 7526e7807c..3d4e85f8df 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java @@ -8,15 +8,15 @@ import static org.junit.Assert.assertTrue; import java.io.StringReader; +import org.junit.Before; +import org.junit.Test; + import junit.framework.JUnit4TestAdapter; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.java.JavaLanguageModule; import net.sourceforge.pmd.testframework.RuleTst; import net.sourceforge.pmd.testframework.TestDescriptor; -import org.junit.Before; -import org.junit.Test; - public class ExcludeLinesTest extends RuleTst { private Rule rule; @@ -41,8 +41,7 @@ import org.junit.Test; ctx.setReport(r); ctx.setSourceCodeFilename("n/a"); ctx.setLanguageVersion(LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getDefaultVersion()); - RuleSet rules = new RuleSet(); - rules.addRule(rule); + RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(TEST3), new RuleSets(rules), ctx); assertTrue(r.isEmpty()); assertEquals(r.getSuppressedRuleViolations().size(), 1); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/cli/XPathCLITest.java b/pmd-java/src/test/java/net/sourceforge/pmd/cli/XPathCLITest.java deleted file mode 100644 index ffa0d62edc..0000000000 --- a/pmd-java/src/test/java/net/sourceforge/pmd/cli/XPathCLITest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ -package net.sourceforge.pmd.cli; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import org.junit.Assert; -import org.junit.Test; - -public class XPathCLITest { - - @Test - public void runXPath() throws Exception { - PrintStream oldOut = System.out; - ByteArrayOutputStream output = new ByteArrayOutputStream(); - System.setOut(new PrintStream(output)); - - try { - XPathCLI.main(new String[] { - "-xpath", - "//ClassOrInterfaceDeclaration", - "-filename", - "src/test/java/net/sourceforge/pmd/cli/XPathCLITest.java" - }); - System.out.flush(); - } finally { - System.setOut(oldOut); - } - - Assert.assertTrue(output.toString("UTF-8").startsWith("Match at line ")); - } -} diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java index db328dfcea..1998227455 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java @@ -9,11 +9,15 @@ import java.io.StringReader; import java.util.HashMap; import java.util.List; +import org.junit.Before; +import org.junit.Test; + import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PropertyDescriptor; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -30,9 +34,6 @@ import net.sourceforge.pmd.lang.rule.xpath.SaxonXPathRuleQuery; import net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery; import net.sourceforge.pmd.testframework.RuleTst; -import org.junit.Before; -import org.junit.Test; - /** * @author daniels */ @@ -56,8 +57,7 @@ import org.junit.Test; Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFilename("n/a"); - RuleSet rules = new RuleSet(); - rules.addRule(rule); + RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(TEST1), new RuleSets(rules), ctx); RuleViolation rv = report.iterator().next(); assertEquals("a", rv.getDescription()); @@ -75,8 +75,7 @@ import org.junit.Test; Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFilename("n/a"); - RuleSet rules = new RuleSet(); - rules.addRule(rule); + RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(TEST2), new RuleSets(rules), ctx); RuleViolation rv = report.iterator().next(); assertEquals(3, rv.getBeginLine()); diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java index 09954701b5..bd94614db1 100644 --- a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java +++ b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java @@ -12,6 +12,7 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -34,8 +35,7 @@ public class XPathJspRuleTest extends RuleTst { Rule rule = new XPathRule(XPATH_EXPRESSION); rule.setMessage("Test"); rule.setLanguage(LanguageRegistry.getLanguage(JspLanguageModule.NAME)); - RuleSet rules = new RuleSet(); - rules.addRule(rule); + RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); RuleContext ctx = new RuleContext(); Report report = new Report(); diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java index b3a066cfb2..3df49a41ae 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java @@ -214,8 +214,7 @@ public abstract class RuleTst { ctx.setSourceCodeFilename("n/a"); ctx.setLanguageVersion(languageVersion); ctx.setIgnoreExceptions(false); - RuleSet rules = new RuleSet(); - rules.addRule(rule); + RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); rules.start(ctx); p.getSourceCodeProcessor().processSourceCode(new StringReader(code), new RuleSets(rules), ctx); rules.end(ctx); diff --git a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java b/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java index 0b28df31fa..75c36bcc78 100644 --- a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java +++ b/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java @@ -41,7 +41,8 @@ public class RuleTstTest { verify(rule).getMinimumLanguageVersion(); verify(rule).getMaximumLanguageVersion(); verify(rule).apply(anyList(), any(RuleContext.class)); - verify(rule).getName(); + verify(rule, times(2)).getName(); + verify(rule).getPropertiesByPropertyDescriptor(); verifyNoMoreInteractions(rule); } }