Search in sources :

Example 16 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class RuleSetFactoryTest method testReferenceToDeprecatedRule.

@Test
public void testReferenceToDeprecatedRule() throws RuleSetNotFoundException {
    Rule r = loadFirstRule(REFERENCE_TO_DEPRECATED_RULE);
    assertNotNull("Reference to Deprecated Rule", r);
    assertTrue("Rule Reference", r instanceof RuleReference);
    assertFalse("Not deprecated", r.isDeprecated());
    assertTrue("Original Rule Deprecated", ((RuleReference) r).getRule().isDeprecated());
    assertEquals("Rule name", r.getName(), DEPRECATED_RULE_NAME);
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) JavaUtilLoggingRule(net.sourceforge.pmd.junit.JavaUtilLoggingRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) Test(org.junit.Test)

Example 17 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class RuleSetFactory method parseRuleReferenceNode.

/**
 * Parse a rule node as a RuleReference. A RuleReference is a single Rule
 * which comes from another RuleSet with some of it's attributes potentially
 * overridden.
 *
 * @param ruleSetReferenceId
 *            The RuleSetReferenceId of the RuleSet being parsed.
 * @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, RuleSetBuilder ruleSetBuilder, Node ruleNode, String ref, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException {
    Element ruleElement = (Element) ruleNode;
    // it.
    if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) {
        return;
    }
    // load the ruleset with minimum priority low, so that we get all rules, to be able to exclude any rule
    // minimum priority will be applied again, before constructing the final ruleset
    RuleSetFactory ruleSetFactory = new RuleSetFactory(resourceLoader, RulePriority.LOW, warnDeprecated, this.compatibilityFilter != null);
    boolean isSameRuleSet = false;
    RuleSetReferenceId otherRuleSetReferenceId = RuleSetReferenceId.parse(ref).get(0);
    if (!otherRuleSetReferenceId.isExternal() && containsRule(ruleSetReferenceId, otherRuleSetReferenceId.getRuleName())) {
        otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId);
        isSameRuleSet = true;
    }
    // do not ignore deprecated rule references
    Rule referencedRule = ruleSetFactory.createRule(otherRuleSetReferenceId, true);
    if (referencedRule == null) {
        throw new IllegalArgumentException("Unable to find referenced rule " + otherRuleSetReferenceId.getRuleName() + "; perhaps the rule name is mispelled?");
    }
    if (warnDeprecated && referencedRule.isDeprecated()) {
        if (referencedRule instanceof RuleReference) {
            RuleReference ruleReference = (RuleReference) referencedRule;
            if (LOG.isLoggable(Level.WARNING)) {
                LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + '/' + ruleReference.getOriginalName() + " instead of the deprecated Rule name " + otherRuleSetReferenceId + ". PMD " + PMDVersion.getNextMajorRelease() + " will remove support for this deprecated Rule name usage.");
            }
        } else if (referencedRule instanceof MockRule) {
            if (LOG.isLoggable(Level.WARNING)) {
                LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId + " as it has been removed from PMD and no longer functions." + " PMD " + PMDVersion.getNextMajorRelease() + " will remove support for this Rule.");
            }
        } else {
            if (LOG.isLoggable(Level.WARNING)) {
                LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId + " as it is scheduled for removal from PMD." + " PMD " + PMDVersion.getNextMajorRelease() + " will remove support for this Rule.");
            }
        }
    }
    RuleSetReference ruleSetReference = new RuleSetReference(otherRuleSetReferenceId.getRuleSetFileName(), false);
    RuleReference ruleReference = new RuleFactory().decorateRule(referencedRule, ruleSetReference, ruleElement);
    if (warnDeprecated && ruleReference.isDeprecated()) {
        if (LOG.isLoggable(Level.WARNING)) {
            LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + '/' + ruleReference.getOriginalName() + " instead of the deprecated Rule name " + ruleSetReferenceId.getRuleSetFileName() + '/' + ruleReference.getName() + ". PMD " + PMDVersion.getNextMajorRelease() + " will remove support for this deprecated Rule name usage.");
        }
    }
    if (withDeprecatedRuleReferences || !isSameRuleSet || !ruleReference.isDeprecated()) {
        ruleSetBuilder.addRuleReplaceIfExists(ruleReference);
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) RuleFactory(net.sourceforge.pmd.rules.RuleFactory) Element(org.w3c.dom.Element) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule)

Example 18 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class RuleSetWriter method createRuleElement.

private Element createRuleElement(Rule rule) {
    if (rule instanceof RuleReference) {
        RuleReference ruleReference = (RuleReference) rule;
        RuleSetReference ruleSetReference = ruleReference.getRuleSetReference();
        if (ruleSetReference.isAllRules()) {
            if (!ruleSetFileNames.contains(ruleSetReference.getRuleSetFileName())) {
                ruleSetFileNames.add(ruleSetReference.getRuleSetFileName());
                return createRuleSetReferenceElement(ruleSetReference);
            } else {
                return null;
            }
        } else {
            Language language = ruleReference.getOverriddenLanguage();
            LanguageVersion minimumLanguageVersion = ruleReference.getOverriddenMinimumLanguageVersion();
            LanguageVersion maximumLanguageVersion = ruleReference.getOverriddenMaximumLanguageVersion();
            Boolean deprecated = ruleReference.isOverriddenDeprecated();
            String name = ruleReference.getOverriddenName();
            String ref = ruleReference.getRuleSetReference().getRuleSetFileName() + '/' + ruleReference.getRule().getName();
            String message = ruleReference.getOverriddenMessage();
            String externalInfoUrl = ruleReference.getOverriddenExternalInfoUrl();
            String description = ruleReference.getOverriddenDescription();
            RulePriority priority = ruleReference.getOverriddenPriority();
            List<PropertyDescriptor<?>> propertyDescriptors = ruleReference.getOverriddenPropertyDescriptors();
            Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor = ruleReference.getOverriddenPropertiesByPropertyDescriptor();
            List<String> examples = ruleReference.getOverriddenExamples();
            return createSingleRuleElement(language, minimumLanguageVersion, maximumLanguageVersion, deprecated, name, null, ref, message, externalInfoUrl, null, null, null, null, description, priority, propertyDescriptors, propertiesByPropertyDescriptor, examples);
        }
    } else {
        return createSingleRuleElement(rule instanceof ImmutableLanguage ? null : rule.getLanguage(), rule.getMinimumLanguageVersion(), rule.getMaximumLanguageVersion(), rule.isDeprecated(), rule.getName(), rule.getSince(), null, rule.getMessage(), rule.getExternalInfoUrl(), rule.getRuleClass(), rule.isDfa(), rule.isTypeResolution(), rule.isMultifile(), rule.getDescription(), rule.getPriority(), rule.getPropertyDescriptors(), rule.getPropertiesByPropertyDescriptor(), rule.getExamples());
    }
}
Also used : ImmutableLanguage(net.sourceforge.pmd.lang.rule.ImmutableLanguage) RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) ImmutableLanguage(net.sourceforge.pmd.lang.rule.ImmutableLanguage) Language(net.sourceforge.pmd.lang.Language) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion)

Example 19 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class AbstractRuleSetFactoryTest method testAllPMDBuiltInRulesMeetConventions.

/**
 * Checks all rulesets of all languages on the classpath and verifies that
 * all required attributes for all rules are specified.
 *
 * @throws Exception
 *             any error
 */
@Test
public void testAllPMDBuiltInRulesMeetConventions() throws Exception {
    int invalidSinceAttributes = 0;
    int invalidExternalInfoURL = 0;
    int invalidClassName = 0;
    int invalidRegexSuppress = 0;
    int invalidXPathSuppress = 0;
    String messages = "";
    List<String> ruleSetFileNames = getRuleSetFileNames();
    for (String fileName : ruleSetFileNames) {
        RuleSet ruleSet = loadRuleSetByFileName(fileName);
        for (Rule rule : ruleSet.getRules()) {
            // Skip references
            if (rule instanceof RuleReference) {
                continue;
            }
            Language language = rule.getLanguage();
            String group = fileName.substring(fileName.lastIndexOf('/') + 1);
            group = group.substring(0, group.indexOf(".xml"));
            if (group.indexOf('-') >= 0) {
                group = group.substring(0, group.indexOf('-'));
            }
            // Is since missing ?
            if (rule.getSince() == null) {
                invalidSinceAttributes++;
                messages += "Rule " + fileName + "/" + rule.getName() + " is missing 'since' attribute" + PMD.EOL;
            }
            // Is URL valid ?
            if (rule.getExternalInfoUrl() == null || "".equalsIgnoreCase(rule.getExternalInfoUrl())) {
                invalidExternalInfoURL++;
                messages += "Rule " + fileName + "/" + rule.getName() + " is missing 'externalInfoURL' attribute" + PMD.EOL;
            } else {
                String expectedExternalInfoURL = "https?://pmd.(sourceforge.net|github.io)/.+/pmd_rules_" + language.getTerseName() + "_" + FilenameUtils.getBaseName(fileName) + ".html#" + rule.getName().toLowerCase(Locale.ROOT);
                if (rule.getExternalInfoUrl() == null || !rule.getExternalInfoUrl().matches(expectedExternalInfoURL)) {
                    invalidExternalInfoURL++;
                    messages += "Rule " + fileName + "/" + rule.getName() + " seems to have an invalid 'externalInfoURL' value (" + rule.getExternalInfoUrl() + "), it should be:" + expectedExternalInfoURL + PMD.EOL;
                }
            }
            // Proper class name/packaging?
            String expectedClassName = "net.sourceforge.pmd.lang." + language.getTerseName() + ".rule." + group + "." + rule.getName() + "Rule";
            if (!rule.getRuleClass().equals(expectedClassName) && !validXPathClassNames.contains(rule.getRuleClass())) {
                invalidClassName++;
                messages += "Rule " + fileName + "/" + rule.getName() + " seems to have an invalid 'class' value (" + rule.getRuleClass() + "), it should be:" + expectedClassName + PMD.EOL;
            }
            // Should not have violation suppress regex property
            if (rule.getProperty(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR) != null) {
                invalidRegexSuppress++;
                messages += "Rule " + fileName + "/" + rule.getName() + " should not have '" + Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR.name() + "', this is intended for end user customization only." + PMD.EOL;
            }
            // Should not have violation suppress xpath property
            if (rule.getProperty(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR) != null) {
                invalidXPathSuppress++;
                messages += "Rule " + fileName + "/" + rule.getName() + " should not have '" + Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR.name() + "', this is intended for end user customization only." + PMD.EOL;
            }
        }
    }
    // the test
    if (invalidSinceAttributes > 0 || invalidExternalInfoURL > 0 || invalidClassName > 0 || invalidRegexSuppress > 0 || invalidXPathSuppress > 0) {
        fail("All built-in PMD rules need 'since' attribute (" + invalidSinceAttributes + " are missing), a proper ExternalURLInfo (" + invalidExternalInfoURL + " are invalid), a class name meeting conventions (" + invalidClassName + " are invalid), no '" + Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR.name() + "' property (" + invalidRegexSuppress + " are invalid), and no '" + Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR.name() + "' property (" + invalidXPathSuppress + " are invalid)" + PMD.EOL + messages);
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) Language(net.sourceforge.pmd.lang.Language) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) Test(org.junit.Test)

Example 20 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class AbstractRuleSetFactoryTest method assertEqualsRuleSet.

private void assertEqualsRuleSet(String message, RuleSet ruleSet1, RuleSet ruleSet2) {
    assertEquals(message + ", RuleSet name", ruleSet1.getName(), ruleSet2.getName());
    assertEquals(message + ", RuleSet description", ruleSet1.getDescription(), ruleSet2.getDescription());
    assertEquals(message + ", RuleSet exclude patterns", ruleSet1.getExcludePatterns(), ruleSet2.getExcludePatterns());
    assertEquals(message + ", RuleSet include patterns", ruleSet1.getIncludePatterns(), ruleSet2.getIncludePatterns());
    assertEquals(message + ", RuleSet rule count", ruleSet1.getRules().size(), ruleSet2.getRules().size());
    for (int i = 0; i < ruleSet1.getRules().size(); i++) {
        Rule rule1 = ((List<Rule>) ruleSet1.getRules()).get(i);
        Rule rule2 = ((List<Rule>) ruleSet2.getRules()).get(i);
        assertFalse(message + ", Different RuleReference", rule1 instanceof RuleReference != rule2 instanceof RuleReference);
        if (rule1 instanceof RuleReference) {
            RuleReference ruleReference1 = (RuleReference) rule1;
            RuleReference ruleReference2 = (RuleReference) rule2;
            assertEquals(message + ", RuleReference overridden language", ruleReference1.getOverriddenLanguage(), ruleReference2.getOverriddenLanguage());
            assertEquals(message + ", RuleReference overridden minimum language version", ruleReference1.getOverriddenMinimumLanguageVersion(), ruleReference2.getOverriddenMinimumLanguageVersion());
            assertEquals(message + ", RuleReference overridden maximum language version", ruleReference1.getOverriddenMaximumLanguageVersion(), ruleReference2.getOverriddenMaximumLanguageVersion());
            assertEquals(message + ", RuleReference overridden deprecated", ruleReference1.isOverriddenDeprecated(), ruleReference2.isOverriddenDeprecated());
            assertEquals(message + ", RuleReference overridden name", ruleReference1.getOverriddenName(), ruleReference2.getOverriddenName());
            assertEquals(message + ", RuleReference overridden description", ruleReference1.getOverriddenDescription(), ruleReference2.getOverriddenDescription());
            assertEquals(message + ", RuleReference overridden message", ruleReference1.getOverriddenMessage(), ruleReference2.getOverriddenMessage());
            assertEquals(message + ", RuleReference overridden external info url", ruleReference1.getOverriddenExternalInfoUrl(), ruleReference2.getOverriddenExternalInfoUrl());
            assertEquals(message + ", RuleReference overridden priority", ruleReference1.getOverriddenPriority(), ruleReference2.getOverriddenPriority());
            assertEquals(message + ", RuleReference overridden examples", ruleReference1.getOverriddenExamples(), ruleReference2.getOverriddenExamples());
        }
        assertEquals(message + ", Rule name", rule1.getName(), rule2.getName());
        assertEquals(message + ", Rule class", rule1.getRuleClass(), rule2.getRuleClass());
        assertEquals(message + ", Rule description " + rule1.getName(), rule1.getDescription(), rule2.getDescription());
        assertEquals(message + ", Rule message", rule1.getMessage(), rule2.getMessage());
        assertEquals(message + ", Rule external info url", rule1.getExternalInfoUrl(), rule2.getExternalInfoUrl());
        assertEquals(message + ", Rule priority", rule1.getPriority(), rule2.getPriority());
        assertEquals(message + ", Rule examples", rule1.getExamples(), rule2.getExamples());
        List<PropertyDescriptor<?>> propertyDescriptors1 = rule1.getPropertyDescriptors();
        List<PropertyDescriptor<?>> propertyDescriptors2 = rule2.getPropertyDescriptors();
        assertEquals(message + ", Rule property descriptor ", propertyDescriptors1, propertyDescriptors2);
        for (int j = 0; j < propertyDescriptors1.size(); j++) {
            assertEquals(message + ", Rule property value " + j, rule1.getProperty(propertyDescriptors1.get(j)), rule2.getProperty(propertyDescriptors2.get(j)));
        }
        assertEquals(message + ", Rule property descriptor count", propertyDescriptors1.size(), propertyDescriptors2.size());
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) ArrayList(java.util.ArrayList) List(java.util.List) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule)

Aggregations

RuleReference (net.sourceforge.pmd.lang.rule.RuleReference)23 Test (org.junit.Test)10 MockRule (net.sourceforge.pmd.lang.rule.MockRule)9 Rule (net.sourceforge.pmd.Rule)7 XPathRule (net.sourceforge.pmd.lang.rule.XPathRule)7 ArrayList (java.util.ArrayList)5 Language (net.sourceforge.pmd.lang.Language)4 List (java.util.List)3 PropertyDescriptor (net.sourceforge.pmd.properties.PropertyDescriptor)3 StringProperty (net.sourceforge.pmd.properties.StringProperty)3 Path (java.nio.file.Path)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 SortedMap (java.util.SortedMap)2 TreeMap (java.util.TreeMap)2 RuleSet (net.sourceforge.pmd.RuleSet)2 JavaUtilLoggingRule (net.sourceforge.pmd.junit.JavaUtilLoggingRule)2 Element (org.w3c.dom.Element)2 HashSet (java.util.HashSet)1