Search in sources :

Example 6 with PropertyDescriptor

use of net.sourceforge.pmd.properties.PropertyDescriptor in project pmd by pmd.

the class SaxonXPathRuleQuery method createDynamicContext.

/**
 * Attempt to create a dynamic context on which to evaluate the {@link #xpathExpression}.
 *
 * @param elementNode the node on which to create the context; generally this node is the root node of the Saxon
 *                    Tree
 * @return the dynamic context on which to run the query
 * @throws XPathException if the supplied value does not conform to the required type of the
 * variable, when setting up the dynamic context; or if the supplied value contains a node that does not belong to
 * this Configuration (or another Configuration that shares the same namePool)
 */
private XPathDynamicContext createDynamicContext(final ElementNode elementNode) throws XPathException {
    final XPathDynamicContext dynamicContext = xpathExpression.createDynamicContext(elementNode);
    // Set variable values on the dynamic context
    for (final XPathVariable xpathVariable : xpathVariables) {
        final String variableName = xpathVariable.getVariableQName().getLocalName();
        for (final Map.Entry<PropertyDescriptor<?>, Object> entry : super.properties.entrySet()) {
            if (variableName.equals(entry.getKey().name())) {
                final ValueRepresentation valueRepresentation = getRepresentation(entry.getKey(), entry.getValue());
                dynamicContext.setVariable(xpathVariable, valueRepresentation);
            }
        }
    }
    return dynamicContext;
}
Also used : XPathVariable(net.sf.saxon.sxpath.XPathVariable) ValueRepresentation(net.sf.saxon.om.ValueRepresentation) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) XPathDynamicContext(net.sf.saxon.sxpath.XPathDynamicContext) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 7 with PropertyDescriptor

use of net.sourceforge.pmd.properties.PropertyDescriptor in project pmd by pmd.

the class AbstractRule method deepCopy.

@SuppressWarnings("unchecked")
@Override
public Rule deepCopy() {
    Rule rule = null;
    try {
        rule = getClass().newInstance();
    } catch (InstantiationException | IllegalAccessException ignored) {
        // in case it happens anyway, something is really wrong...
        throw new RuntimeException(ignored);
    }
    rule.setName(getName());
    rule.setLanguage(getLanguage());
    rule.setMinimumLanguageVersion(getMinimumLanguageVersion());
    rule.setMaximumLanguageVersion(getMaximumLanguageVersion());
    rule.setSince(getSince());
    rule.setMessage(getMessage());
    rule.setRuleSetName(getRuleSetName());
    rule.setExternalInfoUrl(getExternalInfoUrl());
    rule.setDfa(isDfa());
    rule.setTypeResolution(isTypeResolution());
    rule.setMultifile(isMultifile());
    rule.setDescription(getDescription());
    for (final String example : getExamples()) {
        rule.addExample(example);
    }
    rule.setPriority(getPriority());
    for (final PropertyDescriptor<?> prop : getPropertyDescriptors()) {
        if (rule.getPropertyDescriptor(prop.name()) == null) {
            // Property descriptors are immutable, and can be freely shared
            rule.definePropertyDescriptor(prop);
        }
        rule.setProperty((PropertyDescriptor<Object>) prop, getProperty((PropertyDescriptor<Object>) prop));
    }
    return rule;
}
Also used : PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) Rule(net.sourceforge.pmd.Rule)

Example 8 with PropertyDescriptor

use of net.sourceforge.pmd.properties.PropertyDescriptor 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 PropertyDescriptor

use of net.sourceforge.pmd.properties.PropertyDescriptor in project pmd by pmd.

the class RuleSetFactoryTest method testStringMultiPropertyDefaultDelimiter.

@Test
public void testStringMultiPropertyDefaultDelimiter() throws Exception {
    Rule r = loadFirstRule("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ruleset name=\"the ruleset\">\n  <description>Desc</description>\n" + "     <rule name=\"myRule\" message=\"Do not place to this package. Move to \n{0} package/s instead.\" \n" + "class=\"net.sourceforge.pmd.lang.rule.XPathRule\" language=\"dummy\">\n" + "         <description>Please move your class to the right folder(rest \nfolder)</description>\n" + "         <priority>2</priority>\n         <properties>\n             <property name=\"packageRegEx\"" + " value=\"com.aptsssss|com.abc\" \ntype=\"List[String]\" " + "description=\"valid packages\"/>\n         </properties></rule></ruleset>");
    PropertyDescriptor<List<String>> prop = (PropertyDescriptor<List<String>>) r.getPropertyDescriptor("packageRegEx");
    List<String> values = r.getProperty(prop);
    assertEquals(Arrays.asList("com.aptsssss", "com.abc"), values);
}
Also used : PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) ArrayList(java.util.ArrayList) List(java.util.List) JavaUtilLoggingRule(net.sourceforge.pmd.junit.JavaUtilLoggingRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) Test(org.junit.Test)

Example 10 with PropertyDescriptor

use of net.sourceforge.pmd.properties.PropertyDescriptor in project pmd by pmd.

the class RuleSetFactoryTest method testXPath.

@Test
@SuppressWarnings("unchecked")
public void testXPath() throws RuleSetNotFoundException {
    Rule r = loadFirstRule(XPATH);
    PropertyDescriptor<String> xpathProperty = (PropertyDescriptor<String>) r.getPropertyDescriptor("xpath");
    assertNotNull("xpath property descriptor", xpathProperty);
    assertNotSame(r.getProperty(xpathProperty).indexOf(" //Block "), -1);
}
Also used : PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) JavaUtilLoggingRule(net.sourceforge.pmd.junit.JavaUtilLoggingRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) Test(org.junit.Test)

Aggregations

PropertyDescriptor (net.sourceforge.pmd.properties.PropertyDescriptor)18 Test (org.junit.Test)6 Map (java.util.Map)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 JavaUtilLoggingRule (net.sourceforge.pmd.junit.JavaUtilLoggingRule)4 MockRule (net.sourceforge.pmd.lang.rule.MockRule)4 Rule (net.sourceforge.pmd.Rule)3 LanguageVersion (net.sourceforge.pmd.lang.LanguageVersion)3 RuleReference (net.sourceforge.pmd.lang.rule.RuleReference)3 StringReader (java.io.StringReader)2 Properties (java.util.Properties)2 RuleContext (net.sourceforge.pmd.RuleContext)2 Language (net.sourceforge.pmd.lang.Language)2 Parser (net.sourceforge.pmd.lang.Parser)2 ParserOptions (net.sourceforge.pmd.lang.ParserOptions)2 Node (net.sourceforge.pmd.lang.ast.Node)2 ASTCompilationUnit (net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit)2 XPathRule (net.sourceforge.pmd.lang.rule.XPathRule)2 JaxenXPathRuleQuery (net.sourceforge.pmd.lang.rule.xpath.JaxenXPathRuleQuery)2