Search in sources :

Example 1 with AbstractRenderer

use of net.sourceforge.pmd.renderers.AbstractRenderer 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)

Example 2 with AbstractRenderer

use of net.sourceforge.pmd.renderers.AbstractRenderer in project pmd-eclipse-plugin by pmd.

the class BaseVisitor method reviewResource.

/**
 * Run PMD against a resource
 *
 * @param resource
 *            the resource to process
 */
protected final void reviewResource(IResource resource) {
    IFile file = (IFile) resource.getAdapter(IFile.class);
    if (file == null || file.getFileExtension() == null) {
        return;
    }
    Reader input = null;
    try {
        boolean included = isIncluded(file);
        LOG.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles());
        LOG.debug("file " + file.getName() + " is derived: " + file.isDerived());
        LOG.debug("file checked: " + included);
        prepareMarkerAccumulator(file);
        LanguageVersionDiscoverer languageDiscoverer = new LanguageVersionDiscoverer();
        LanguageVersion languageVersion = languageDiscoverer.getDefaultLanguageVersionForFile(file.getName());
        // in case it is java, select the correct java version
        if (languageVersion != null && languageVersion.getLanguage() == LanguageRegistry.getLanguage(JavaLanguageModule.NAME)) {
            languageVersion = PMDPlugin.javaVersionFor(file.getProject());
        }
        if (languageVersion != null) {
            configuration().setDefaultLanguageVersion(languageVersion);
        }
        LOG.debug("discovered language: " + languageVersion);
        PMDPlugin.setJavaClassLoader(configuration(), resource.getProject());
        final File sourceCodeFile = file.getRawLocation().toFile();
        if (included && getRuleSet().applies(sourceCodeFile) && isFileInWorkingSet(file) && languageVersion != null) {
            subTask("PMD checking: " + file.getName());
            Timer timer = new Timer();
            RuleContext context = PMD.newRuleContext(file.getName(), sourceCodeFile);
            context.setLanguageVersion(languageVersion);
            input = new InputStreamReader(file.getContents(), file.getCharset());
            // getPmdEngine().processFile(input, getRuleSet(), context);
            // getPmdEngine().processFile(sourceCodeFile, getRuleSet(),
            // context);
            DataSource dataSource = new ReaderDataSource(input, file.getName());
            RuleSetFactory ruleSetFactory = new RuleSetFactory() {

                @Override
                public synchronized RuleSets createRuleSets(String referenceString) throws RuleSetNotFoundException {
                    return new RuleSets(getRuleSet());
                }
            };
            // need to disable multi threading, as the ruleset is
            // not recreated and shared between threads...
            // but as we anyway have only one file to process, it won't hurt
            // here.
            configuration().setThreads(0);
            LOG.debug("PMD running on file " + file.getName());
            final Report collectingReport = new Report();
            Renderer collectingRenderer = new AbstractRenderer("collectingRenderer", "Renderer that collect violations") {

                @Override
                public void startFileAnalysis(DataSource dataSource) {
                // TODO Auto-generated method stub
                }

                @Override
                public void start() throws IOException {
                // TODO Auto-generated method stub
                }

                @Override
                public void renderFileReport(Report report) throws IOException {
                    for (RuleViolation v : report) {
                        collectingReport.addRuleViolation(v);
                    }
                    for (Iterator<ProcessingError> it = report.errors(); it.hasNext(); ) {
                        collectingReport.addError(it.next());
                    }
                    for (Iterator<ConfigurationError> it = report.configErrors(); it.hasNext(); ) {
                        collectingReport.addConfigError(it.next());
                    }
                }

                @Override
                public void end() throws IOException {
                // TODO Auto-generated method stub
                }

                @Override
                public String defaultFileExtension() {
                    // TODO Auto-generated method stub
                    return null;
                }
            };
            // PMD.processFiles(configuration(), ruleSetFactory,
            // Arrays.asList(dataSource), context,
            // Arrays.asList(collectingRenderer));
            new MonoThreadProcessor(configuration()).processFiles(ruleSetFactory, Arrays.asList(dataSource), context, Arrays.asList(collectingRenderer));
            LOG.debug("PMD run finished.");
            timer.stop();
            pmdDuration += timer.getDuration();
            LOG.debug("PMD found " + collectingReport.size() + " violations for file " + file.getName());
            if (collectingReport.hasConfigErrors()) {
                StringBuilder message = new StringBuilder("There were configuration errors!\n");
                Iterator<ConfigurationError> errors = collectingReport.configErrors();
                while (errors.hasNext()) {
                    ConfigurationError error = errors.next();
                    message.append(error.rule().getName()).append(": ").append(error.issue()).append('\n');
                }
                PMDPlugin.getDefault().logWarn(message.toString());
                LOG.warn(message);
            }
            if (collectingReport.hasErrors()) {
                StringBuilder message = new StringBuilder("There were processing errors!\n");
                Iterator<ProcessingError> errors = collectingReport.errors();
                while (errors.hasNext()) {
                    ProcessingError error = errors.next();
                    message.append(error.getFile()).append(": ").append(error.getMsg()).append(' ').append(error.getDetail()).append("\n");
                }
                PMDPlugin.getDefault().logWarn(message.toString());
                throw new PMDException(message.toString());
            }
            updateMarkers(file, collectingReport.iterator(), isUseTaskMarker());
            worked(1);
            fileCount++;
        } else {
            LOG.debug("The file " + file.getName() + " is not in the working set");
        }
    } catch (CoreException e) {
        // TODO: complete message
        LOG.error("Core exception visiting " + file.getName(), e);
    } catch (PMDException e) {
        // TODO: complete message
        LOG.error("PMD exception visiting " + file.getName(), e);
    } catch (IOException e) {
        // TODO: complete message
        LOG.error("IO exception visiting " + file.getName(), e);
    } catch (PropertiesException e) {
        // TODO: complete message
        LOG.error("Properties exception visiting " + file.getName(), e);
    } catch (IllegalArgumentException e) {
        LOG.error("Illegal argument", e);
    } finally {
        IOUtil.closeQuietly(input);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) RuleContext(net.sourceforge.pmd.RuleContext) PropertiesException(net.sourceforge.pmd.eclipse.runtime.properties.PropertiesException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) RuleViolation(net.sourceforge.pmd.RuleViolation) LanguageVersionDiscoverer(net.sourceforge.pmd.lang.LanguageVersionDiscoverer) ProcessingError(net.sourceforge.pmd.Report.ProcessingError) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSets(net.sourceforge.pmd.RuleSets) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) InputStreamReader(java.io.InputStreamReader) Report(net.sourceforge.pmd.Report) MonoThreadProcessor(net.sourceforge.pmd.processor.MonoThreadProcessor) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) ConfigurationError(net.sourceforge.pmd.Report.ConfigurationError) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) Timer(name.herlin.command.Timer) CoreException(org.eclipse.core.runtime.CoreException) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) Renderer(net.sourceforge.pmd.renderers.Renderer) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) PMDException(net.sourceforge.pmd.PMDException) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Aggregations

File (java.io.File)2 Report (net.sourceforge.pmd.Report)2 RuleContext (net.sourceforge.pmd.RuleContext)2 RuleSetFactory (net.sourceforge.pmd.RuleSetFactory)2 RuleSets (net.sourceforge.pmd.RuleSets)2 AbstractRenderer (net.sourceforge.pmd.renderers.AbstractRenderer)2 Renderer (net.sourceforge.pmd.renderers.Renderer)2 DataSource (net.sourceforge.pmd.util.datasource.DataSource)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Timer (name.herlin.command.Timer)1 PMDException (net.sourceforge.pmd.PMDException)1 ConfigurationError (net.sourceforge.pmd.Report.ConfigurationError)1 ProcessingError (net.sourceforge.pmd.Report.ProcessingError)1 RuleSetNotFoundException (net.sourceforge.pmd.RuleSetNotFoundException)1