Search in sources :

Example 6 with XPathRule

use of net.sourceforge.pmd.lang.rule.XPathRule in project pmd-eclipse-plugin by pmd.

the class XPathEvaluator method evaluate.

/**
 * Builds a temporary XPathRule using the query provided and executes it
 * against the source. Returns a list of nodes detailing any issues found
 * with it.
 *
 * @param source
 * @param xpathQuery
 * @param xpathVersion
 * @return
 * @throws ParseException
 */
public List<Node> evaluate(String source, String xpathQuery, String xpathVersion) throws ParseException {
    Node c = getCompilationUnit(source);
    final List<Node> results = new ArrayList<Node>();
    XPathRule xpathRule = new XPathRule() {

        public void addViolation(Object data, Node node, String arg) {
            results.add(node);
        }
    };
    xpathRule.setMessage("");
    xpathRule.setLanguage(getLanguageVersion().getLanguage());
    xpathRule.setProperty(XPathRule.XPATH_DESCRIPTOR, xpathQuery);
    xpathRule.setProperty(XPathRule.VERSION_DESCRIPTOR, xpathVersion);
    RuleSet ruleSet = RuleSetUtil.newSingle(xpathRule);
    RuleSets ruleSets = new RuleSets(ruleSet);
    RuleContext ruleContext = new RuleContext();
    ruleContext.setLanguageVersion(getLanguageVersion());
    List<Node> nodes = new ArrayList<Node>(1);
    nodes.add(c);
    ruleSets.apply(nodes, ruleContext, xpathRule.getLanguage());
    return results;
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) RuleSets(net.sourceforge.pmd.RuleSets) Node(net.sourceforge.pmd.lang.ast.Node) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule)

Example 7 with XPathRule

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

the class RegexpAcceptanceTest method testSimple.

@Test
public void testSimple() {
    Rule r = new XPathRule(XPATH);
    r.setLanguage(LanguageRegistry.getLanguage(JavaLanguageModule.NAME));
    r.setMessage("");
    TestDescriptor[] testDescriptors = extractTestsFromXml(r, "RegexpAcceptance");
    for (TestDescriptor testDescriptor : testDescriptors) {
        testDescriptor.setReinitializeRule(false);
    }
    runTests(testDescriptors);
}
Also used : XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) Rule(net.sourceforge.pmd.Rule) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) TestDescriptor(net.sourceforge.pmd.testframework.TestDescriptor) Test(org.junit.Test)

Example 8 with XPathRule

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

the class RuleDocGenerator method generateRuleSetIndex.

/**
 * Generates for each ruleset a page. The page contains the details for each rule.
 *
 * @param rulesets all rulesets
 * @throws IOException
 */
private void generateRuleSetIndex(Map<Language, List<RuleSet>> rulesets) throws IOException {
    for (Map.Entry<Language, List<RuleSet>> entry : rulesets.entrySet()) {
        String languageTersename = entry.getKey().getTerseName();
        for (RuleSet ruleset : entry.getValue()) {
            String rulesetFilename = RuleSetUtils.getRuleSetFilename(ruleset);
            String filename = RULESET_INDEX_FILENAME_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", rulesetFilename);
            Path path = getAbsoluteOutputPath(filename);
            String permalink = RULESET_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", rulesetFilename);
            List<String> lines = new LinkedList<>();
            lines.add("---");
            lines.add("title: " + ruleset.getName());
            lines.add("summary: " + getRuleSetDescriptionSingleLine(ruleset));
            lines.add("permalink: " + permalink);
            lines.add("folder: pmd/rules/" + languageTersename);
            lines.add("sidebaractiveurl: /" + LANGUAGE_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename));
            lines.add("editmepath: ../" + getRuleSetSourceFilepath(ruleset));
            lines.add("keywords: " + getRuleSetKeywords(ruleset));
            lines.add("---");
            for (Rule rule : getSortedRules(ruleset)) {
                lines.add("## " + rule.getName());
                lines.add("");
                if (rule instanceof RuleReference) {
                    RuleReference ref = (RuleReference) rule;
                    if (ruleset.getFileName().equals(ref.getRuleSetReference().getRuleSetFileName())) {
                        // rule renamed within same ruleset
                        lines.add(DEPRECATION_LABEL);
                        lines.add("");
                        lines.add("This rule has been renamed. Use instead: [" + ref.getRule().getName() + "](" + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
                        lines.add("");
                    } else {
                        // rule moved to another ruleset
                        String otherLink = RULESET_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", RuleSetUtils.getRuleSetFilename(ref.getRuleSetReference().getRuleSetFileName()));
                        lines.add(DEPRECATION_LABEL);
                        lines.add("");
                        lines.add("The rule has been moved to another ruleset. Use instead: [" + ref.getRule().getName() + "](" + otherLink + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
                        lines.add("");
                    }
                }
                if (rule.isDeprecated()) {
                    lines.add(DEPRECATION_LABEL);
                    lines.add("");
                }
                if (rule.getSince() != null) {
                    lines.add("**Since:** PMD " + rule.getSince());
                    lines.add("");
                }
                lines.add("**Priority:** " + rule.getPriority() + " (" + rule.getPriority().getPriority() + ")");
                lines.add("");
                if (rule.getMinimumLanguageVersion() != null) {
                    lines.add("**Minimum Language Version:** " + rule.getLanguage().getName() + " " + rule.getMinimumLanguageVersion().getVersion());
                    lines.add("");
                }
                lines.addAll(toLines(stripIndentation(rule.getDescription())));
                lines.add("");
                if (rule instanceof XPathRule || rule instanceof RuleReference && ((RuleReference) rule).getRule() instanceof XPathRule) {
                    lines.add("```");
                    lines.addAll(toLines(StringUtils.stripToEmpty(rule.getProperty(XPathRule.XPATH_DESCRIPTOR))));
                    lines.add("```");
                    lines.add("");
                } else {
                    lines.add("**This rule is defined by the following Java class:** " + "[" + rule.getRuleClass() + "](" + GITHUB_SOURCE_LINK + getRuleClassSourceFilepath(rule.getRuleClass()) + ")");
                    lines.add("");
                }
                if (!rule.getExamples().isEmpty()) {
                    lines.add("**Example(s):**");
                    lines.add("");
                    for (String example : rule.getExamples()) {
                        lines.add("``` " + mapLanguageForHighlighting(languageTersename));
                        lines.addAll(toLines(StringUtils.stripToEmpty(example)));
                        lines.add("```");
                        lines.add("");
                    }
                }
                List<PropertyDescriptor<?>> properties = new ArrayList<>(rule.getPropertyDescriptors());
                // filter out standard properties
                properties.remove(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR);
                properties.remove(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR);
                properties.remove(XPathRule.XPATH_DESCRIPTOR);
                properties.remove(XPathRule.VERSION_DESCRIPTOR);
                if (!properties.isEmpty()) {
                    lines.add("**This rule has the following properties:**");
                    lines.add("");
                    lines.add("|Name|Default Value|Description|");
                    lines.add("|----|-------------|-----------|");
                    for (PropertyDescriptor<?> propertyDescriptor : properties) {
                        String description = propertyDescriptor.description();
                        if (description != null && description.toLowerCase(Locale.ROOT).startsWith(DEPRECATED_RULE_PROPERTY_MARKER)) {
                            description = DEPRECATION_LABEL_SMALL + description.substring(DEPRECATED_RULE_PROPERTY_MARKER.length());
                        }
                        lines.add("|" + propertyDescriptor.name() + "|" + (propertyDescriptor.defaultValue() != null ? String.valueOf(propertyDescriptor.defaultValue()) : "") + "|" + description + "|");
                    }
                    lines.add("");
                }
                lines.add("**Use this rule by referencing it:**");
                lines.add("``` xml");
                lines.add("<rule ref=\"category/" + languageTersename + "/" + rulesetFilename + ".xml/" + rule.getName() + "\" />");
                lines.add("```");
                lines.add("");
            }
            writer.write(path, lines);
            System.out.println("Generated " + path);
        }
    }
}
Also used : Path(java.nio.file.Path) RuleSet(net.sourceforge.pmd.RuleSet) RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) LinkedList(java.util.LinkedList) Language(net.sourceforge.pmd.lang.Language) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) Rule(net.sourceforge.pmd.Rule) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap)

Example 9 with XPathRule

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

the class XPathMetricFunctionTest method makeXpathRuleFromXPath.

private Rule makeXpathRuleFromXPath(String xpath) {
    XPathRule rule = new XPathRule();
    rule.setXPath(xpath);
    rule.setMessage(VIOLATION_MESSAGE);
    rule.setLanguage(LanguageRegistry.getLanguage(JavaLanguageModule.NAME));
    return rule;
}
Also used : XPathRule(net.sourceforge.pmd.lang.rule.XPathRule)

Example 10 with XPathRule

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

the class XPathEvaluator method evaluateQuery.

/**
 * Evaluates an XPath query on the compilation unit.
 *
 * @param compilationUnit AST root
 * @param languageVersion language version
 * @param xpathVersion    XPath version
 * @param xpathQuery      XPath query
 * @param properties      Properties of the rule
 *
 * @throws XPathEvaluationException if there was an error during the evaluation. The cause is preserved
 */
public List<Node> evaluateQuery(Node compilationUnit, LanguageVersion languageVersion, String xpathVersion, String xpathQuery, List<PropertyDescriptorSpec> properties) throws XPathEvaluationException {
    if (StringUtils.isBlank(xpathQuery)) {
        return Collections.emptyList();
    }
    try {
        List<Node> results = new ArrayList<>();
        XPathRule xpathRule = new XPathRule() {

            @Override
            public void addViolation(Object data, Node node, String arg) {
                results.add(node);
            }
        };
        xpathRule.setMessage("");
        xpathRule.setLanguage(languageVersion.getLanguage());
        xpathRule.setXPath(xpathQuery);
        xpathRule.setVersion(xpathVersion);
        properties.stream().map(PropertyDescriptorSpec::build).forEach(xpathRule::definePropertyDescriptor);
        final RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(xpathRule);
        RuleSets ruleSets = new RuleSets(ruleSet);
        RuleContext ruleContext = new RuleContext();
        ruleContext.setLanguageVersion(languageVersion);
        List<Node> nodes = new ArrayList<>();
        nodes.add(compilationUnit);
        ruleSets.apply(nodes, ruleContext, xpathRule.getLanguage());
        return results;
    } catch (RuntimeException e) {
        throw new XPathEvaluationException(e);
    }
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) Node(net.sourceforge.pmd.lang.ast.Node) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSets(net.sourceforge.pmd.RuleSets)

Aggregations

XPathRule (net.sourceforge.pmd.lang.rule.XPathRule)13 Test (org.junit.Test)6 RuleContext (net.sourceforge.pmd.RuleContext)4 RuleSet (net.sourceforge.pmd.RuleSet)4 ArrayList (java.util.ArrayList)3 Rule (net.sourceforge.pmd.Rule)3 RuleSets (net.sourceforge.pmd.RuleSets)3 Node (net.sourceforge.pmd.lang.ast.Node)3 Report (net.sourceforge.pmd.Report)2 RuleSetFactory (net.sourceforge.pmd.RuleSetFactory)2 StringReader (java.io.StringReader)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 SortedMap (java.util.SortedMap)1 TreeMap (java.util.TreeMap)1 PMD (net.sourceforge.pmd.PMD)1 ReportTest (net.sourceforge.pmd.ReportTest)1