Search in sources :

Example 41 with RuleContext

use of net.sourceforge.pmd.RuleContext in project pmd by pmd.

the class JavaRuleViolationTest method testPackageAndMultipleClassesName.

@Test
public void testPackageAndMultipleClassesName() {
    ASTCompilationUnit ast = parse("package pkg; import java.util.List; class Foo { } public class Bar { }");
    ASTImportDeclaration importNode = ast.getFirstDescendantOfType(ASTImportDeclaration.class);
    JavaRuleViolation violation = new JavaRuleViolation(null, new RuleContext(), importNode, null);
    assertEquals("pkg", violation.getPackageName());
    assertEquals("Bar", violation.getClassName());
}
Also used : ASTImportDeclaration(net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration) ASTCompilationUnit(net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit) RuleContext(net.sourceforge.pmd.RuleContext) Test(org.junit.Test)

Example 42 with RuleContext

use of net.sourceforge.pmd.RuleContext in project pmd by pmd.

the class JavaRuleViolationTest method testDefaultPackageAndClassName.

@Test
public void testDefaultPackageAndClassName() {
    ASTCompilationUnit ast = parse("import java.util.List; public class Foo { }");
    ASTImportDeclaration importNode = ast.getFirstDescendantOfType(ASTImportDeclaration.class);
    JavaRuleViolation violation = new JavaRuleViolation(null, new RuleContext(), importNode, null);
    assertEquals("", violation.getPackageName());
    assertEquals("Foo", violation.getClassName());
}
Also used : ASTImportDeclaration(net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration) ASTCompilationUnit(net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit) RuleContext(net.sourceforge.pmd.RuleContext) Test(org.junit.Test)

Example 43 with RuleContext

use of net.sourceforge.pmd.RuleContext in project pmd by pmd.

the class XPathRuleTest method testFollowingSibling.

/**
 * Following sibling check: See https://sourceforge.net/p/pmd/bugs/1209/
 *
 * @throws Exception
 *             any error
 */
@Test
public void testFollowingSibling() throws Exception {
    final String SOURCE = "public class dummy {\n" + "  public String toString() {\n" + "    String test = \"bad example\";\n" + "    test = \"a\";\n" + "    return test;\n" + "  }\n" + "}";
    LanguageVersion language = LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getDefaultVersion();
    ParserOptions parserOptions = language.getLanguageVersionHandler().getDefaultParserOptions();
    Parser parser = language.getLanguageVersionHandler().getParser(parserOptions);
    ASTCompilationUnit cu = (ASTCompilationUnit) parser.parse("test", new StringReader(SOURCE));
    RuleContext ruleContext = new RuleContext();
    ruleContext.setLanguageVersion(language);
    String xpath = "//Block/BlockStatement/following-sibling::BlockStatement";
    // XPATH version 1.0
    XPathRuleQuery xpathRuleQuery = new JaxenXPathRuleQuery();
    xpathRuleQuery.setXPath(xpath);
    xpathRuleQuery.setProperties(new HashMap<PropertyDescriptor<?>, Object>());
    xpathRuleQuery.setVersion(XPathRuleQuery.XPATH_1_0);
    List<Node> nodes = xpathRuleQuery.evaluate(cu, ruleContext);
    assertEquals(2, nodes.size());
    assertEquals(4, nodes.get(0).getBeginLine());
    assertEquals(5, nodes.get(1).getBeginLine());
    // XPATH version 2.0
    xpathRuleQuery = new SaxonXPathRuleQuery();
    xpathRuleQuery.setXPath(xpath);
    xpathRuleQuery.setProperties(new HashMap<PropertyDescriptor<?>, Object>());
    xpathRuleQuery.setVersion(XPathRuleQuery.XPATH_2_0);
    nodes = xpathRuleQuery.evaluate(cu, ruleContext);
    assertEquals(2, nodes.size());
    assertEquals(4, nodes.get(0).getBeginLine());
    assertEquals(5, nodes.get(1).getBeginLine());
}
Also used : ParserOptions(net.sourceforge.pmd.lang.ParserOptions) ASTCompilationUnit(net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit) RuleContext(net.sourceforge.pmd.RuleContext) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) SaxonXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.SaxonXPathRuleQuery) Node(net.sourceforge.pmd.lang.ast.Node) Parser(net.sourceforge.pmd.lang.Parser) JaxenXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.JaxenXPathRuleQuery) StringReader(java.io.StringReader) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) XPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery) JaxenXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.JaxenXPathRuleQuery) SaxonXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.SaxonXPathRuleQuery) Test(org.junit.Test)

Example 44 with RuleContext

use of net.sourceforge.pmd.RuleContext in project pmd by pmd.

the class XPathRuleTest method testImageOfPrimarySuffix.

/**
 * Test for problem reported in bug #1219 PrimarySuffix/@Image does not work
 * in some cases in xpath 2.0
 *
 * @throws Exception
 *             any error
 */
@Test
public void testImageOfPrimarySuffix() throws Exception {
    final String SUFFIX = "import java.io.File;\n" + "\n" + "public class TestSuffix {\n" + "    public static void main(String args[]) {\n" + "        new File(\"subdirectory\").list();\n" + "    }\n" + "}";
    LanguageVersion language = LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getDefaultVersion();
    ParserOptions parserOptions = language.getLanguageVersionHandler().getDefaultParserOptions();
    Parser parser = language.getLanguageVersionHandler().getParser(parserOptions);
    ASTCompilationUnit cu = (ASTCompilationUnit) parser.parse("test", new StringReader(SUFFIX));
    RuleContext ruleContext = new RuleContext();
    ruleContext.setLanguageVersion(language);
    String xpath = "//PrimarySuffix[@Image='list']";
    // XPATH version 1.0
    XPathRuleQuery xpathRuleQuery = new JaxenXPathRuleQuery();
    xpathRuleQuery.setXPath(xpath);
    xpathRuleQuery.setProperties(new HashMap<PropertyDescriptor<?>, Object>());
    xpathRuleQuery.setVersion(XPathRuleQuery.XPATH_1_0);
    List<Node> nodes = xpathRuleQuery.evaluate(cu, ruleContext);
    assertEquals(1, nodes.size());
    // XPATH version 1.0 Compatibility
    xpathRuleQuery = new SaxonXPathRuleQuery();
    xpathRuleQuery.setXPath(xpath);
    xpathRuleQuery.setProperties(new HashMap<PropertyDescriptor<?>, Object>());
    xpathRuleQuery.setVersion(XPathRuleQuery.XPATH_1_0_COMPATIBILITY);
    nodes = xpathRuleQuery.evaluate(cu, ruleContext);
    assertEquals(1, nodes.size());
    // XPATH version 2.0
    xpathRuleQuery = new SaxonXPathRuleQuery();
    xpathRuleQuery.setXPath(xpath);
    xpathRuleQuery.setProperties(new HashMap<PropertyDescriptor<?>, Object>());
    xpathRuleQuery.setVersion(XPathRuleQuery.XPATH_2_0);
    nodes = xpathRuleQuery.evaluate(cu, ruleContext);
    assertEquals(1, nodes.size());
}
Also used : ParserOptions(net.sourceforge.pmd.lang.ParserOptions) ASTCompilationUnit(net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit) RuleContext(net.sourceforge.pmd.RuleContext) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) SaxonXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.SaxonXPathRuleQuery) Node(net.sourceforge.pmd.lang.ast.Node) Parser(net.sourceforge.pmd.lang.Parser) JaxenXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.JaxenXPathRuleQuery) StringReader(java.io.StringReader) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) XPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery) JaxenXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.JaxenXPathRuleQuery) SaxonXPathRuleQuery(net.sourceforge.pmd.lang.rule.xpath.SaxonXPathRuleQuery) Test(org.junit.Test)

Example 45 with RuleContext

use of net.sourceforge.pmd.RuleContext in project pmd by pmd.

the class PMDTaskImpl method doTask.

private void doTask() {
    setupClassLoader();
    // Setup RuleSetFactory and validate RuleSets
    final ResourceLoader rl = setupResourceLoader();
    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration, rl);
    try {
        // This is just used to validate and display rules. Each thread will create its own ruleset
        String ruleSets = configuration.getRuleSets();
        if (StringUtils.isNotBlank(ruleSets)) {
            // Substitute env variables/properties
            configuration.setRuleSets(project.replaceProperties(ruleSets));
        }
        RuleSets rules = ruleSetFactory.createRuleSets(configuration.getRuleSets());
        logRulesUsed(rules);
    } catch (RuleSetNotFoundException e) {
        throw new BuildException(e.getMessage(), e);
    }
    if (configuration.getSuppressMarker() != null) {
        project.log("Setting suppress marker to be " + configuration.getSuppressMarker(), Project.MSG_VERBOSE);
    }
    // Start the Formatters
    for (Formatter formatter : formatters) {
        project.log("Sending a report to " + formatter, Project.MSG_VERBOSE);
        formatter.start(project.getBaseDir().toString());
    }
    // log("Setting Language Version " + languageVersion.getShortName(),
    // Project.MSG_VERBOSE);
    // TODO Do we really need all this in a loop over each FileSet? Seems
    // like a lot of redundancy
    RuleContext ctx = new RuleContext();
    Report errorReport = new Report();
    final AtomicInteger reportSize = new AtomicInteger();
    final String separator = System.getProperty("file.separator");
    for (FileSet fs : filesets) {
        List<DataSource> files = new LinkedList<>();
        DirectoryScanner ds = fs.getDirectoryScanner(project);
        String[] srcFiles = ds.getIncludedFiles();
        for (String srcFile : srcFiles) {
            File file = new File(ds.getBasedir() + separator + srcFile);
            files.add(new FileDataSource(file));
        }
        final String inputPaths = ds.getBasedir().getPath();
        configuration.setInputPaths(inputPaths);
        Renderer logRenderer = new AbstractRenderer("log", "Logging renderer") {

            @Override
            public void start() {
            // Nothing to do
            }

            @Override
            public void startFileAnalysis(DataSource dataSource) {
                project.log("Processing file " + dataSource.getNiceFileName(false, inputPaths), Project.MSG_VERBOSE);
            }

            @Override
            public void renderFileReport(Report r) {
                int size = r.size();
                if (size > 0) {
                    reportSize.addAndGet(size);
                }
            }

            @Override
            public void end() {
            // Nothing to do
            }

            @Override
            public String defaultFileExtension() {
                return null;
            }
        };
        List<Renderer> renderers = new ArrayList<>(formatters.size() + 1);
        renderers.add(logRenderer);
        for (Formatter formatter : formatters) {
            renderers.add(formatter.getRenderer());
        }
        try {
            PMD.processFiles(configuration, ruleSetFactory, files, ctx, renderers);
        } catch (RuntimeException pmde) {
            handleError(ctx, errorReport, pmde);
        }
    }
    int problemCount = reportSize.get();
    project.log(problemCount + " problems found", Project.MSG_VERBOSE);
    for (Formatter formatter : formatters) {
        formatter.end(errorReport);
    }
    if (failuresPropertyName != null && problemCount > 0) {
        project.setProperty(failuresPropertyName, String.valueOf(problemCount));
        project.log("Setting property " + failuresPropertyName + " to " + problemCount, Project.MSG_VERBOSE);
    }
    if (failOnRuleViolation && problemCount > maxRuleViolations) {
        throw new BuildException("Stopping build since PMD found " + problemCount + " rule violations in the code");
    }
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) RuleContext(net.sourceforge.pmd.RuleContext) FileSet(org.apache.tools.ant.types.FileSet) Report(net.sourceforge.pmd.Report) Formatter(net.sourceforge.pmd.ant.Formatter) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) DataSource(net.sourceforge.pmd.util.datasource.DataSource) FileDataSource(net.sourceforge.pmd.util.datasource.FileDataSource) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) RuleSets(net.sourceforge.pmd.RuleSets) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) FileDataSource(net.sourceforge.pmd.util.datasource.FileDataSource) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) Renderer(net.sourceforge.pmd.renderers.Renderer) RuleSetNotFoundException(net.sourceforge.pmd.RuleSetNotFoundException) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Aggregations

RuleContext (net.sourceforge.pmd.RuleContext)51 Test (org.junit.Test)19 RuleSets (net.sourceforge.pmd.RuleSets)17 RuleSetFactory (net.sourceforge.pmd.RuleSetFactory)15 Report (net.sourceforge.pmd.Report)14 Node (net.sourceforge.pmd.lang.ast.Node)13 RuleSet (net.sourceforge.pmd.RuleSet)11 StringReader (java.io.StringReader)9 RuleViolation (net.sourceforge.pmd.RuleViolation)9 IOException (java.io.IOException)8 PMDConfiguration (net.sourceforge.pmd.PMDConfiguration)8 PMDException (net.sourceforge.pmd.PMDException)8 ASTCompilationUnit (net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit)8 ArrayList (java.util.ArrayList)7 SourceCodeProcessor (net.sourceforge.pmd.SourceCodeProcessor)7 RuleSetNotFoundException (net.sourceforge.pmd.RuleSetNotFoundException)6 LanguageVersion (net.sourceforge.pmd.lang.LanguageVersion)6 DummyNode (net.sourceforge.pmd.lang.ast.DummyNode)5 FooRule (net.sourceforge.pmd.FooRule)4 Parser (net.sourceforge.pmd.lang.Parser)4