Search in sources :

Example 1 with DataSource

use of net.sourceforge.pmd.util.datasource.DataSource in project maven-plugins by apache.

the class PmdReport method executePmd.

private void executePmd() throws MavenReportException {
    if (renderer != null) {
        // PMD has already been run
        getLog().debug("PMD has already been run - skipping redundant execution.");
        return;
    }
    try {
        excludeFromFile.loadExcludeFromFailuresData(excludeFromFailureFile);
    } catch (MojoExecutionException e) {
        throw new MavenReportException("Unable to load exclusions", e);
    }
    // configure ResourceManager
    locator.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());
    locator.addSearchPath("url", "");
    locator.setOutputDirectory(targetDirectory);
    renderer = new PmdCollectingRenderer();
    PMDConfiguration pmdConfiguration = getPMDConfiguration();
    String[] sets = new String[rulesets.length];
    try {
        for (int idx = 0; idx < rulesets.length; idx++) {
            String set = rulesets[idx];
            getLog().debug("Preparing ruleset: " + set);
            RuleSetReferenceId id = new RuleSetReferenceId(set);
            File ruleset = locator.getResourceAsFile(id.getRuleSetFileName(), getLocationTemp(set));
            if (null == ruleset) {
                throw new MavenReportException("Could not resolve " + set);
            }
            sets[idx] = ruleset.getAbsolutePath();
        }
    } catch (ResourceNotFoundException e) {
        throw new MavenReportException(e.getMessage(), e);
    } catch (FileResourceCreationException e) {
        throw new MavenReportException(e.getMessage(), e);
    }
    pmdConfiguration.setRuleSets(StringUtils.join(sets, ","));
    try {
        if (filesToProcess == null) {
            filesToProcess = getFilesToProcess();
        }
        if (filesToProcess.isEmpty() && !"java".equals(language)) {
            getLog().warn("No files found to process. Did you add your additional source folders like javascript?" + " (see also build-helper-maven-plugin)");
        }
    } catch (IOException e) {
        throw new MavenReportException("Can't get file list", e);
    }
    String encoding = getSourceEncoding();
    if (StringUtils.isEmpty(encoding) && !filesToProcess.isEmpty()) {
        getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!");
        encoding = ReaderFactory.FILE_ENCODING;
    }
    pmdConfiguration.setSourceEncoding(encoding);
    List<DataSource> dataSources = new ArrayList<>(filesToProcess.size());
    for (File f : filesToProcess.keySet()) {
        dataSources.add(new FileDataSource(f));
    }
    if (sets.length > 0) {
        processFilesWithPMD(pmdConfiguration, dataSources);
    } else {
        getLog().debug("Skipping PMD execution as no rulesets are defined.");
    }
    if (renderer.hasErrors()) {
        if (!skipPmdError) {
            getLog().error("PMD processing errors:");
            getLog().error(renderer.getErrorsAsString());
            throw new MavenReportException("Found " + renderer.getErrors().size() + " PMD processing errors");
        }
        getLog().warn("There are " + renderer.getErrors().size() + " PMD processing errors:");
        getLog().warn(renderer.getErrorsAsString());
    }
    removeExcludedViolations(renderer.getViolations());
    // so the "check" goals can check for violations
    if (isXml() && renderer != null) {
        writeNonHtml(renderer.asReport());
    }
    if (benchmark) {
        try (PrintStream benchmarkFileStream = new PrintStream(benchmarkOutputFilename)) {
            (new TextReport()).generate(Benchmarker.values(), benchmarkFileStream);
        } catch (FileNotFoundException fnfe) {
            getLog().error("Unable to generate benchmark file: " + benchmarkOutputFilename, fnfe);
        }
    }
}
Also used : PrintStream(java.io.PrintStream) RuleSetReferenceId(net.sourceforge.pmd.RuleSetReferenceId) FileResourceCreationException(org.codehaus.plexus.resource.loader.FileResourceCreationException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) TextReport(net.sourceforge.pmd.benchmark.TextReport) DataSource(net.sourceforge.pmd.util.datasource.DataSource) FileDataSource(net.sourceforge.pmd.util.datasource.FileDataSource) FileDataSource(net.sourceforge.pmd.util.datasource.FileDataSource) ResourceNotFoundException(org.codehaus.plexus.resource.loader.ResourceNotFoundException) File(java.io.File) MavenReportException(org.apache.maven.reporting.MavenReportException) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration)

Example 2 with DataSource

use of net.sourceforge.pmd.util.datasource.DataSource in project Gargoyle by callakrsos.

the class PMDGargoyleThreadProcessor method processFiles.

public void processFiles(RuleSetFactory ruleSetFactory, List<DataSource> files, RuleContext ctx, List<Renderer> renderers) {
    // single threaded execution
    RuleSets rs = createRuleSets(ruleSetFactory);
    SourceCodeProcessor processor = new SourceCodeProcessor(configuration);
    for (DataSource dataSource : files) {
        String niceFileName = filenameFrom(dataSource);
        Report report = PMD.setupReport(rs, ctx, niceFileName);
        // overtake the listener
        //bug fix 2016-10-05 by kyj. 결과가 중복되서 출력됨.
        //			report.addSynchronizedListeners(ctx.getReport().getSynchronizedListeners());
        //	        ctx.setReport(report);
        //	        ctx.setSourceCodeFilename(niceFileName);
        //			if (LOG.isLoggable(Level.FINE)) {
        //				LOG.fine("Processing " + ctx.getSourceCodeFilename());
        //			}
        rs.start(ctx);
        for (Renderer r : renderers) {
            r.startFileAnalysis(dataSource);
        }
        try {
            InputStream stream = new BufferedInputStream(dataSource.getInputStream());
            //				ctx.setLanguageVersion(null);
            processor.processSourceCode(stream, rs, ctx);
        } catch (PMDException pmde) {
            //				LOGGER.error(ValueUtil.toString(pmde));
            //				if (LOG.isLoggable(Level.FINE)) {
            //					LOG.log(Level.FINE, "Error while processing file: " + niceFileName, pmde.getCause());
            //				}
            report.addError(new Report.ProcessingError(pmde.getMessage(), niceFileName));
        } catch (IOException ioe) {
            //				LOGGER.error(ValueUtil.toString(ioe));
            // unexpected exception: log and stop executor service
            addError(report, "Unable to read source file", ioe, niceFileName);
        } catch (RuntimeException re) {
            //				LOGGER.error(ValueUtil.toString(re));
            // unexpected exception: log and stop executor service
            addError(report, "RuntimeException while processing file", re, niceFileName);
        } catch (Exception e) {
            LOGGER.error(ValueUtil.toString(e));
        }
        rs.end(ctx);
        super.renderReports(renderers, ctx.getReport());
    }
}
Also used : Report(net.sourceforge.pmd.Report) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) IOException(java.io.IOException) PMDException(net.sourceforge.pmd.PMDException) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) BufferedInputStream(java.io.BufferedInputStream) RuleSets(net.sourceforge.pmd.RuleSets) Renderer(net.sourceforge.pmd.renderers.Renderer) PMDException(net.sourceforge.pmd.PMDException)

Example 3 with DataSource

use of net.sourceforge.pmd.util.datasource.DataSource in project Gargoyle by callakrsos.

the class DoPMD method doPMD.

public int doPMD(GargoylePMDConfiguration configuration, List<ReportListener> listeners) {
    renerderWriter = RendererWriterFactory.get(WRITER_TYPE.StringWriter);
    // Load the RuleSets
    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration);
    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(configuration.getRuleSets(), ruleSetFactory);
    if (ruleSets == null) {
        return 0;
    }
    Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
    List<DataSource> files = getApplicableFiles(configuration, languages);
    long reportStart = System.nanoTime();
    try {
        //			Renderer renderer = RendererFactory.createRenderer(configuration.getReportFormat(), configuration.getReportProperties()); //configuration.createRenderer();//createDefaultRenderer();
        List<Renderer> renderers = new LinkedList<>();
        //configuration.createRenderer();
        Renderer renderer = new DatabaseXmlRenderer();
        renderer.setWriter(renerderWriter.getWriter());
        renderer.start();
        renderers.add(renderer);
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
        RuleContext ctx = new RuleContext();
        final AtomicInteger violations = new AtomicInteger(0);
        ctx.getReport().addListener(new ReportListener() {

            @Override
            public void ruleViolationAdded(RuleViolation ruleViolation) {
                violations.incrementAndGet();
            }

            @Override
            public void metricAdded(Metric metric) {
            }
        });
        if (listeners != null && !listeners.isEmpty()) {
            for (ReportListener l : listeners) ctx.getReport().addListener(l);
        }
        processFiles(configuration, ruleSetFactory, files, ctx, renderers);
        reportStart = System.nanoTime();
        //				renderer.renderFileReport();
        renderer.end();
        renderer.flush();
        return violations.get();
    } catch (Exception e) {
        LOGGER.error(ValueUtil.toString(e));
        return 0;
    } finally {
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
        try {
            close();
        } catch (IOException e) {
            LOGGER.error(ValueUtil.toString(e));
        }
    }
}
Also used : ReportListener(net.sourceforge.pmd.ReportListener) RuleContext(net.sourceforge.pmd.RuleContext) RuleViolation(net.sourceforge.pmd.RuleViolation) IOException(java.io.IOException) LinkedList(java.util.LinkedList) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) Language(net.sourceforge.pmd.lang.Language) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RuleSets(net.sourceforge.pmd.RuleSets) Renderer(net.sourceforge.pmd.renderers.Renderer) Metric(net.sourceforge.pmd.stat.Metric)

Example 4 with DataSource

use of net.sourceforge.pmd.util.datasource.DataSource in project Gargoyle by callakrsos.

the class DoPMD method internalGetApplicableFiles.

private List<DataSource> internalGetApplicableFiles(GargoylePMDConfiguration configuration, Set<Language> languages) {
    List<DataSource> files = new ArrayList<>();
    LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(languages);
    if (null != configuration.getInputPaths()) {
        files.addAll(FileUtil.collectFiles(configuration.getInputPaths(), fileSelector));
    }
    if (null != configuration.getSourceText()) {
        String filePaths = "SourceBase";
        if (null != configuration.getSourceFileName()) {
            filePaths = configuration.getSourceFileName();
        }
        filePaths = filePaths.replaceAll("\\r?\\n", ",");
        filePaths = filePaths.replaceAll(",+", ",");
        String sourceText = configuration.getSourceText();
        try {
            Reader reader = new StringReader(sourceText);
            files.addAll(Arrays.asList(new ReaderDataSource(reader, filePaths)));
        } catch (Exception e) {
            LOGGER.error(ValueUtil.toString(e));
        }
    }
    return files;
}
Also used : ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) ArrayList(java.util.ArrayList) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) LanguageFilenameFilter(net.sourceforge.pmd.lang.LanguageFilenameFilter) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource)

Aggregations

IOException (java.io.IOException)4 DataSource (net.sourceforge.pmd.util.datasource.DataSource)4 ArrayList (java.util.ArrayList)2 RuleSets (net.sourceforge.pmd.RuleSets)2 Renderer (net.sourceforge.pmd.renderers.Renderer)2 ReaderDataSource (net.sourceforge.pmd.util.datasource.ReaderDataSource)2 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 PrintStream (java.io.PrintStream)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 LinkedList (java.util.LinkedList)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 PMDConfiguration (net.sourceforge.pmd.PMDConfiguration)1 PMDException (net.sourceforge.pmd.PMDException)1 Report (net.sourceforge.pmd.Report)1 ReportListener (net.sourceforge.pmd.ReportListener)1 RuleContext (net.sourceforge.pmd.RuleContext)1