Search code examples
javapmd

How can I get PMD result report as java object from code?


I'm writing something like PMD wrapper (the goal is to check the java code with PMD, but with certain features), pmd-core and pmd-java included to my project like external libraries and I'm executing PMD such way:

int violations = PMD.doPMD(configuration);

doPMD returns number of violations found. By configuring reportFormat in PMDConfiguration we can set output to System.out or to file with one of the available report formats (like xml, html, text, etc.), but...

How can I get PMD result (of all source files were processed) report as java object? Perhaps, it is possible to get a list<> of all RuleViolations or something else.


Solution

  • You can use a custom Renderer.

    1. Create a custom implementation of net.sourceforge.pmd.renderers.Renderer
    2. On your configuration call setReportFormat passing the fully quallified name of your custom renderer (ie: "my.organization.package.InMemoryRenderer")
    3. run the analysis, just as you are doing

    During the analysis process, your renderer will be instantiated exactly once, and renderFileReport(Report) method will be called for each file's results. The Report has method's to obtain and iterate over violations, config and execution errors.

    These are provided as POJOs, as you intend.

    You won't have access to the Renderer instance, but you can store data in a static member (make sure to keep thread-safety as PMD runs multithreaded analysis!) and provide a static getter.