CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-net-sourceforge-pmd--pmd-core

PMD Core - The foundational library module providing essential infrastructure for PMD static code analysis including AST handling, rule execution, configuration management, and reporting mechanisms.

Pending
Overview
Eval results
Files

core-analysis.mddocs/

Core PMD Analysis

The Core PMD Analysis module provides the main entry point and configuration management for PMD static code analysis. It orchestrates the complete analysis workflow from configuration setup through rule execution to report generation.

Capabilities

PmdAnalysis

Main programmatic API for executing PMD analysis with comprehensive lifecycle management and resource handling.

/**
 * Main programmatic API for PMD analysis execution.
 * Implements AutoCloseable for proper resource management.
 */
public final class PmdAnalysis implements AutoCloseable {
    
    /**
     * Create analysis instance from configuration
     * @param config PMD configuration with analysis settings
     * @return New PmdAnalysis instance ready for execution
     */
    static PmdAnalysis create(PMDConfiguration config);
    
    /**
     * Get file collector for specifying analyzed sources
     * @return FileCollector for adding files and directories
     */
    FileCollector files();
    
    /**
     * Create new ruleset loader for loading rules from various sources
     * @return RuleSetLoader configured with current settings
     */
    RuleSetLoader newRuleSetLoader();
    
    /**
     * Add report renderer for output formatting
     * @param renderer Renderer instance for specific output format
     */
    void addRenderer(Renderer renderer);
    
    /**
     * Add multiple report renderers
     * @param renderers Collection of renderer instances
     */
    void addRenderers(Collection<Renderer> renderers);
    
    /**
     * Add analysis listener for custom event processing
     * @param listener GlobalAnalysisListener for receiving events
     */
    void addListener(GlobalAnalysisListener listener);
    
    /**
     * Add multiple analysis listeners
     * @param listeners Collection of listener instances
     */
    void addListeners(Collection<? extends GlobalAnalysisListener> listeners);
    
    /**
     * Add ruleset for analysis
     * @param ruleSet RuleSet containing analysis rules
     */
    void addRuleSet(RuleSet ruleSet);
    
    /**
     * Add multiple rulesets for analysis
     * @param ruleSets Collection of RuleSet instances
     */
    void addRuleSets(Collection<RuleSet> ruleSets);
    
    /**
     * Get unmodifiable view of currently loaded rulesets
     * @return List of RuleSet instances
     */
    List<RuleSet> getRulesets();
    
    /**
     * Get language-specific property bundle
     * @param language Target language for properties
     * @return LanguagePropertyBundle with language-specific settings
     */
    LanguagePropertyBundle getLanguageProperties(Language language);
    
    /**
     * Get configurable file name renderer
     * @return ConfigurableFileNameRenderer for customizing file path display
     */
    ConfigurableFileNameRenderer fileNameRenderer();
    
    /**
     * Execute analysis without collecting results
     * Results are sent to registered renderers and listeners
     */
    void performAnalysis();
    
    /**
     * Execute analysis and return collected report
     * @return Report containing all violations and errors
     */
    Report performAnalysisAndCollectReport();
    
    /**
     * Get message reporter for logging and diagnostics
     * @return PmdReporter for handling messages
     */
    PmdReporter getReporter();
    
    /**
     * Run analysis and return statistics
     * @return ReportStats with violation and error counts
     */
    ReportStats runAndReturnStats();
    
    /**
     * Close analysis instance and cleanup resources
     */
    void close();
}

Usage Examples:

import net.sourceforge.pmd.*;
import net.sourceforge.pmd.lang.rule.*;
import java.nio.file.Paths;

// Basic analysis setup
PMDConfiguration config = new PMDConfiguration();
config.addInputPath(Paths.get("src/main/java"));

try (PmdAnalysis analysis = PmdAnalysis.create(config)) {
    // Add files for analysis
    analysis.files().addDirectory(Paths.get("src/main/java"));
    
    // Load and add rules
    RuleSetLoader loader = analysis.newRuleSetLoader();
    RuleSet javaRules = loader.loadFromResource("rulesets/java/quickstart.xml");
    analysis.addRuleSet(javaRules);
    
    // Execute and get report
    Report report = analysis.performAnalysisAndCollectReport();
    
    System.out.printf("Found %d violations%n", report.getViolations().size());
}

// Analysis with custom renderer
try (PmdAnalysis analysis = PmdAnalysis.create(config)) {
    // Add custom XML renderer
    XMLRenderer xmlRenderer = new XMLRenderer();
    xmlRenderer.setWriter(new FileWriter("report.xml"));
    analysis.addRenderer(xmlRenderer);
    
    // Add files and rules
    analysis.files().addDirectory(Paths.get("src"));
    analysis.addRuleSets(loader.loadFromResources(Arrays.asList(
        "rulesets/java/quickstart.xml",
        "rulesets/java/design.xml"
    )));
    
    // Execute analysis (results go to renderer)
    analysis.performAnalysis();
}

PMDConfiguration

Runtime configuration class for PMD analysis with comprehensive settings for threading, rulesets, reporting, and caching.

/**
 * Runtime configuration for PMD analysis.
 * Extends AbstractConfiguration with PMD-specific settings.
 */
public class PMDConfiguration extends AbstractConfiguration {
    
    /** Default violation suppress marker */
    public static final String DEFAULT_SUPPRESS_MARKER = "NOPMD";
    
    /**
     * Default constructor with PMD language registry
     */
    PMDConfiguration();
    
    /**
     * Constructor with custom language registry
     * @param languageRegistry Registry of supported languages
     */
    PMDConfiguration(LanguageRegistry languageRegistry);
    
    /**
     * Get violation suppress marker (default "NOPMD")
     * @return String used to suppress violations in comments
     */
    String getSuppressMarker();
    
    /**
     * Set violation suppress marker
     * @param suppressMarker String to use for suppressing violations
     */
    void setSuppressMarker(String suppressMarker);
    
    /**
     * Get number of processing threads
     * @return Number of threads for parallel analysis
     */
    int getThreads();
    
    /**
     * Set number of processing threads
     * @param threads Number of threads (must be positive)
     */
    void setThreads(int threads);
    
    /**
     * Get ClassLoader for rule processing
     * @return ClassLoader used for loading rules and dependencies
     */
    ClassLoader getClassLoader();
    
    /**
     * Set ClassLoader for rule processing
     * @param classLoader ClassLoader to use for rule loading
     */
    void setClassLoader(ClassLoader classLoader);
    
    /**
     * Prepend auxiliary classpath for type resolution
     * @param classpath Classpath string to prepend
     */
    void prependAuxClasspath(String classpath);
    
    /**
     * Get ruleset paths
     * @return List of ruleset reference paths
     */
    @NonNull List<@NonNull String> getRuleSetPaths();
    
    /**
     * Set ruleset paths
     * @param ruleSetPaths List of ruleset references (files, resources, URLs)
     */
    void setRuleSets(@NonNull List<@NonNull String> ruleSetPaths);
    
    /**
     * Add single ruleset path
     * @param rulesetPath Path to ruleset (file, resource, or URL)
     */
    void addRuleSet(@NonNull String rulesetPath);
    
    /**
     * Get minimum rule priority threshold
     * @return Minimum RulePriority for violations
     */
    RulePriority getMinimumPriority();
    
    /**
     * Set minimum rule priority threshold
     * @param minimumPriority Minimum priority for reporting violations
     */
    void setMinimumPriority(RulePriority minimumPriority);
    
    /**
     * Create renderer without writer
     * @return Renderer instance based on report format setting
     */
    Renderer createRenderer();
    
    /**
     * Create renderer with optional writer
     * @param withReportWriter Whether to configure writer from reportFile setting
     * @return Configured renderer instance
     */
    Renderer createRenderer(boolean withReportWriter);
    
    /**
     * Get report format name
     * @return String identifier for output format (xml, html, text, etc.)
     */
    String getReportFormat();
    
    /**
     * Set report format name
     * @param reportFormat Format identifier (xml, html, json, text, etc.)
     */
    void setReportFormat(String reportFormat);
    
    /**
     * Check if suppressed violations are shown in reports
     * @return true if suppressed violations are included in output
     */
    boolean isShowSuppressedViolations();
    
    /**
     * Set whether to show suppressed violations in reports
     * @param show true to include suppressed violations in output
     */
    void setShowSuppressedViolations(boolean show);
    
    /**
     * Get renderer configuration properties
     * @return Properties for configuring renderer behavior
     */
    Properties getReportProperties();
    
    /**
     * Set renderer configuration properties
     * @param reportProperties Properties for renderer configuration
     */
    void setReportProperties(Properties reportProperties);
    
    /**
     * Set analysis cache file location
     * @param cacheLocation Path to cache file for incremental analysis
     */
    void setAnalysisCacheLocation(String cacheLocation);
    
    /**
     * Disable incremental analysis caching
     * @param noCache true to disable caching, false to enable
     */
    void setIgnoreIncrementalAnalysis(boolean noCache);
    
    /**
     * Check if incremental analysis is disabled
     * @return true if caching is disabled
     */
    boolean isIgnoreIncrementalAnalysis();
}

Usage Examples:

import net.sourceforge.pmd.*;
import net.sourceforge.pmd.lang.rule.RulePriority;
import java.nio.file.Paths;
import java.util.Properties;

// Basic configuration
PMDConfiguration config = new PMDConfiguration();
config.setThreads(Runtime.getRuntime().availableProcessors());
config.addInputPath(Paths.get("src/main/java"));
config.addRuleSet("rulesets/java/quickstart.xml");
config.setReportFormat("xml");
config.setReportFile(Paths.get("pmd-report.xml"));

// Advanced configuration with custom settings
PMDConfiguration config = new PMDConfiguration();
config.setThreads(4);
config.setSuppressMarker("NOSONAR");  // Use SonarQube-style suppression
config.setMinimumPriority(RulePriority.MEDIUM);  // Only medium+ priority violations

// Add multiple rulesets
config.addRuleSet("rulesets/java/quickstart.xml");
config.addRuleSet("rulesets/java/design.xml");
config.addRuleSet("custom-rules.xml");

// Configure caching for performance
config.setAnalysisCacheLocation("target/pmd-cache");

// Configure HTML renderer with custom properties
config.setReportFormat("html");
Properties htmlProps = new Properties();
htmlProps.setProperty("linkPrefix", "https://github.com/repo/blob/main/");
htmlProps.setProperty("linePrefix", "#L");
config.setReportProperties(htmlProps);

// Show suppressed violations for debugging
config.setShowSuppressedViolations(true);

// Create and configure renderer
Renderer renderer = config.createRenderer(true);  // with writer from reportFile
renderer.start();
// ... analysis execution
renderer.end();

AbstractConfiguration

Base configuration class providing common settings for PMD and CPD with language handling, file management, and reporting options.

/**
 * Base configuration class for PMD and CPD with common settings.
 * Provides language handling, file management, and basic reporting configuration.
 */
public abstract class AbstractConfiguration {
    
    /**
     * Get source file encoding
     * @return Charset used for reading source files
     */
    Charset getSourceEncoding();
    
    /**
     * Set source file encoding
     * @param sourceEncoding Charset for reading source files
     */
    void setSourceEncoding(Charset sourceEncoding);
    
    /**
     * Get language-specific property bundle
     * @param language Target language for properties
     * @return LanguagePropertyBundle with language-specific settings
     */
    @NonNull LanguagePropertyBundle getLanguageProperties(Language language);
    
    /**
     * Get language registry
     * @return LanguageRegistry of supported languages
     */
    LanguageRegistry getLanguageRegistry();
    
    /**
     * Get message reporter for diagnostics and logging
     * @return PmdReporter for handling messages
     */
    @NonNull PmdReporter getReporter();
    
    /**
     * Set message reporter
     * @param reporter PmdReporter for handling messages
     */
    void setReporter(@NonNull PmdReporter reporter);
    
    /**
     * Get language version discoverer for file type detection
     * @return LanguageVersionDiscoverer for automatic language detection
     */
    LanguageVersionDiscoverer getLanguageVersionDiscoverer();
    
    /**
     * Get forced language version (overrides auto-detection)
     * @return LanguageVersion if forced, null for auto-detection
     */
    LanguageVersion getForceLanguageVersion();
    
    /**
     * Check if language version is forced
     * @return true if language version is explicitly set
     */
    boolean isForceLanguageVersion();
    
    /**
     * Force specific language version for all files
     * @param version LanguageVersion to use, or null for auto-detection
     */
    void setForceLanguageVersion(@Nullable LanguageVersion version);
    
    /**
     * Limit analysis to specific language only
     * @param lang Language to restrict analysis to
     */
    void setOnlyRecognizeLanguage(Language lang);
    
    /**
     * Set default language version
     * @param languageVersion Default version for language
     */
    void setDefaultLanguageVersion(LanguageVersion languageVersion);
    
    /**
     * Set multiple default language versions
     * @param versions List of default language versions
     */
    void setDefaultLanguageVersions(List<LanguageVersion> versions);
    
    /**
     * Get language version for specific file
     * @param fileName Name of file to check
     * @return LanguageVersion for file, or null if not recognized
     */
    @Nullable LanguageVersion getLanguageVersionOfFile(String fileName);
    
    /**
     * Add path for relativizing/shortening report paths
     * @param path Root path for making relative paths in reports
     */
    void addRelativizeRoot(Path path);
    
    /**
     * Add multiple relativize root paths
     * @param paths List of root paths for relativizing reports
     */
    void addRelativizeRoots(List<Path> paths);
    
    /**
     * Get relativize root paths
     * @return List of paths used for shortening report paths
     */
    List<Path> getRelativizeRoots();
    
    /**
     * Get input URI
     * @return URI for input source
     */
    URI getUri();
    
    /**
     * Set input URI
     * @param inputUri URI for input source
     */
    void setInputUri(URI inputUri);
    
    /**
     * Get input paths for analysis
     * @return List of paths to analyze
     */
    @NonNull List<Path> getInputPathList();
    
    /**
     * Set input paths for analysis
     * @param inputPaths List of paths to analyze
     */
    void setInputPathList(List<Path> inputPaths);
    
    /**
     * Add input path for analysis
     * @param inputPath Path to add for analysis
     */
    void addInputPath(@NonNull Path inputPath);
    
    /**
     * Get input file list path (file containing paths to analyze)
     * @return Path to file containing input paths, or null
     */
    @Nullable Path getInputFile();
    
    /**
     * Get ignore file list path (file containing paths to ignore)
     * @return Path to file containing ignore patterns, or null
     */
    @Nullable Path getIgnoreFile();
    
    /**
     * Set input file list path
     * @param inputFilePath Path to file containing input paths
     */
    void setInputFilePath(Path inputFilePath);
    
    /**
     * Set ignore file list path
     * @param ignoreFilePath Path to file containing ignore patterns
     */
    void setIgnoreFilePath(Path ignoreFilePath);
    
    /**
     * Get exclude patterns
     * @return List of paths/patterns to exclude from analysis
     */
    List<Path> getExcludes();
    
    /**
     * Set exclude patterns
     * @param excludes List of paths/patterns to exclude
     */
    void setExcludes(List<Path> excludes);
    
    /**
     * Check if files are collected recursively
     * @return true if directories are processed recursively
     */
    boolean collectFilesRecursively();
    
    /**
     * Set recursive file collection
     * @param collectRecursive true to process directories recursively
     */
    void collectFilesRecursively(boolean collectRecursive);
    
    /**
     * Get report file path
     * @return Path for output report file, or null for stdout
     */
    @Nullable Path getReportFilePath();
    
    /**
     * Set report file path
     * @param reportFile Path for output report file, or null for stdout
     */
    void setReportFile(@Nullable Path reportFile);
    
    /**
     * Check if analysis should fail on violations
     * @return true if violations cause analysis failure
     */
    boolean isFailOnViolation();
    
    /**
     * Set whether to fail analysis on violations
     * @param failOnViolation true to fail analysis on violations
     */
    void setFailOnViolation(boolean failOnViolation);
    
    /**
     * Check if analysis should fail on errors
     * @return true if processing errors cause analysis failure
     */
    boolean isFailOnError();
    
    /**
     * Set whether to fail analysis on processing errors
     * @param failOnError true to fail analysis on processing errors
     */
    void setFailOnError(boolean failOnError);
}

Types

/**
 * File collection interface for managing analysis inputs
 */
interface FileCollector extends AutoCloseable {
    void addFile(Path file);
    void addDirectory(Path dir);
    void addZipFile(Path zipFile);
    void addSourceURI(URI uri);
    List<TextFile> getCollectedFiles();
    void filterLanguages(Set<Language> languages);
    void close();
}

/**
 * Configurable file name renderer for customizing path display
 */
interface ConfigurableFileNameRenderer {
    String getDisplayName(FileId fileId);
    void setRelativizeRoots(List<Path> roots);
}

/**
 * Language property bundle for language-specific settings
 */
interface LanguagePropertyBundle extends PropertySource {
    Language getLanguage();
    LanguagePropertyBundle copyForLanguage(Language language);
}

/**
 * Report statistics summary
 */
interface ReportStats {
    int getNumViolations();
    int getNumErrors();
    int getNumProcessingErrors();
    int getNumConfigErrors();
    Map<String, Integer> getViolationsByRule();
    Map<String, Integer> getViolationsByFile();
}

/**
 * Message reporter for diagnostics and logging
 */
interface PmdReporter {
    void logEx(Level level, String message, Object[] formatArgs, Throwable error);
    void log(Level level, String message, Object... formatArgs);
    void warn(String message, Object... formatArgs);
    void error(String message, Object... formatArgs);
    boolean isLoggable(Level level);
}

Install with Tessl CLI

npx tessl i tessl/maven-net-sourceforge-pmd--pmd-core

docs

ast-processing.md

copy-paste-detection.md

core-analysis.md

index.md

language-framework.md

properties-system.md

rendering-system.md

reporting-system.md

rule-system.md

utilities.md

tile.json