Search in sources :

Example 46 with RuleContext

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

the class Benchmarker method stress.

/**
 * @param languageVersion
 *            LanguageVersion
 * @param ruleSet
 *            RuleSet
 * @param dataSources
 *            List<DataSource>
 * @param results
 *            Set<RuleDuration>
 * @param debug
 *            boolean
 * @throws PMDException
 * @throws IOException
 */
private static void stress(LanguageVersion languageVersion, RuleSet ruleSet, List<DataSource> dataSources, Set<RuleDuration> results, boolean debug) throws PMDException, IOException {
    final RuleSetFactory factory = new RuleSetFactory();
    for (Rule rule : ruleSet.getRules()) {
        if (debug) {
            System.out.println("Starting " + rule.getName());
        }
        final RuleSet working = factory.createSingleRuleRuleSet(rule);
        RuleSets ruleSets = new RuleSets(working);
        PMDConfiguration config = new PMDConfiguration();
        config.setDefaultLanguageVersion(languageVersion);
        RuleContext ctx = new RuleContext();
        long start = System.currentTimeMillis();
        for (DataSource dataSource : dataSources) {
            try (InputStream stream = new BufferedInputStream(dataSource.getInputStream())) {
                ctx.setSourceCodeFilename(dataSource.getNiceFileName(false, null));
                new SourceCodeProcessor(config).processSourceCode(stream, ruleSets, ctx);
            }
        }
        long end = System.currentTimeMillis();
        long elapsed = end - start;
        results.add(new RuleDuration(elapsed, rule));
        if (debug) {
            System.out.println("Done timing " + rule.getName() + "; elapsed time was " + elapsed);
        }
    }
}
Also used : RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) BufferedInputStream(java.io.BufferedInputStream) RuleSets(net.sourceforge.pmd.RuleSets) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) Rule(net.sourceforge.pmd.Rule) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration) DataSource(net.sourceforge.pmd.util.datasource.DataSource)

Example 47 with RuleContext

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

the class XPathEvaluator method evaluateQuery.

/**
 * Evaluates an XPath query on the compilation unit.
 *
 * @param compilationUnit AST root
 * @param languageVersion language version
 * @param xpathVersion    XPath version
 * @param xpathQuery      XPath query
 * @param properties      Properties of the rule
 *
 * @throws XPathEvaluationException if there was an error during the evaluation. The cause is preserved
 */
public List<Node> evaluateQuery(Node compilationUnit, LanguageVersion languageVersion, String xpathVersion, String xpathQuery, List<PropertyDescriptorSpec> properties) throws XPathEvaluationException {
    if (StringUtils.isBlank(xpathQuery)) {
        return Collections.emptyList();
    }
    try {
        List<Node> results = new ArrayList<>();
        XPathRule xpathRule = new XPathRule() {

            @Override
            public void addViolation(Object data, Node node, String arg) {
                results.add(node);
            }
        };
        xpathRule.setMessage("");
        xpathRule.setLanguage(languageVersion.getLanguage());
        xpathRule.setXPath(xpathQuery);
        xpathRule.setVersion(xpathVersion);
        properties.stream().map(PropertyDescriptorSpec::build).forEach(xpathRule::definePropertyDescriptor);
        final RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(xpathRule);
        RuleSets ruleSets = new RuleSets(ruleSet);
        RuleContext ruleContext = new RuleContext();
        ruleContext.setLanguageVersion(languageVersion);
        List<Node> nodes = new ArrayList<>();
        nodes.add(compilationUnit);
        ruleSets.apply(nodes, ruleContext, xpathRule.getLanguage());
        return results;
    } catch (RuntimeException e) {
        throw new XPathEvaluationException(e);
    }
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) Node(net.sourceforge.pmd.lang.ast.Node) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSets(net.sourceforge.pmd.RuleSets)

Example 48 with RuleContext

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

the class PmdRunnable method call.

@Override
public Report call() {
    ThreadContext tc = LOCAL_THREAD_CONTEXT.get();
    if (tc == null) {
        tc = new ThreadContext(new RuleSets(ruleSets), new RuleContext(ruleContext));
        LOCAL_THREAD_CONTEXT.set(tc);
    }
    Report report = Report.createReport(tc.ruleContext, fileName);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Processing " + tc.ruleContext.getSourceCodeFilename());
    }
    for (Renderer r : renderers) {
        r.startFileAnalysis(dataSource);
    }
    try (InputStream stream = new BufferedInputStream(dataSource.getInputStream())) {
        tc.ruleContext.setLanguageVersion(null);
        sourceCodeProcessor.processSourceCode(stream, tc.ruleSets, tc.ruleContext);
    } catch (PMDException pmde) {
        addError(report, pmde, "Error while processing file: " + fileName);
    } catch (IOException ioe) {
        addError(report, ioe, "IOException during processing of " + fileName);
    } catch (RuntimeException re) {
        addError(report, re, "RuntimeException during processing of " + fileName);
    }
    return report;
}
Also used : RuleContext(net.sourceforge.pmd.RuleContext) Report(net.sourceforge.pmd.Report) BufferedInputStream(java.io.BufferedInputStream) RuleSets(net.sourceforge.pmd.RuleSets) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Renderer(net.sourceforge.pmd.renderers.Renderer) PMDException(net.sourceforge.pmd.PMDException) IOException(java.io.IOException)

Example 49 with RuleContext

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

the class BasicPMDTest method testRunPmdJdk14.

/**
 * Let see with Java 1.4
 */
@Test
public void testRunPmdJdk14() {
    try {
        PMDConfiguration configuration = new PMDConfiguration();
        configuration.setDefaultLanguageVersion(LanguageRegistry.findLanguageVersionByTerseName("java 1.4"));
        final String sourceCode = "public class Foo {\n public void foo() {\nreturn;\n}}";
        final RuleContext context = new RuleContext();
        context.setSourceCodeFilename("foo.java");
        context.setReport(new Report());
        final RuleSet codeStyleRuleSet = new RuleSetFactory().createRuleSet("category/java/codestyle.xml/UnnecessaryReturn");
        RuleSets rSets = new RuleSets(codeStyleRuleSet);
        new SourceCodeProcessor(configuration).processSourceCode(new StringDataSource(sourceCode).getInputStream(), rSets, context);
        final Iterator<RuleViolation> iter = context.getReport().iterator();
        Assert.assertTrue("There should be at least one violation", iter.hasNext());
        final RuleViolation violation = iter.next();
        Assert.assertEquals(violation.getRule().getName(), "UnnecessaryReturn");
        Assert.assertEquals(3, violation.getBeginLine());
    } catch (final RuleSetNotFoundException e) {
        e.printStackTrace();
        Assert.fail();
    } catch (final PMDException e) {
        e.printStackTrace();
        Assert.fail();
    }
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) Report(net.sourceforge.pmd.Report) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) RuleViolation(net.sourceforge.pmd.RuleViolation) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSets(net.sourceforge.pmd.RuleSets) RuleSetNotFoundException(net.sourceforge.pmd.RuleSetNotFoundException) PMDException(net.sourceforge.pmd.PMDException) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration) Test(org.junit.Test)

Example 50 with RuleContext

use of net.sourceforge.pmd.RuleContext 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

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