Search in sources :

Example 26 with RuleContext

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

the class AnalyzerTest method analyze.

/**
 * Prepares the arguments, calls {@link Analyzer#analyze(IFile, RuleSets, ViolationProcessor), and verifies that it
 * invokes {@link ViolationProcessor#annotate(IFile, Iterable) with the correct rule violations and that it invokes
 * {@link RuleSets#start(RuleContext)} as well as {@link RuleSets#end(RuleContext)} if the file is valid.
 */
public void analyze(final IFile file, final String ruleSetRefId, final String... violatedRules) {
    try {
        final ViolationProcessor violationProcessor = mock(ViolationProcessor.class);
        final RuleSets ruleSets = spy(RulesetsFactoryUtils.defaultFactory().createRuleSets(ruleSetRefId));
        new Analyzer().analyze(file, ruleSets, violationProcessor);
        verify(violationProcessor).annotate(same(file), violations(violatedRules));
        final boolean isValidFile = violatedRules.length > 0;
        if (isValidFile) {
            verify(ruleSets).start(any(RuleContext.class));
            verify(ruleSets).end(any(RuleContext.class));
        }
    } catch (final RuleSetNotFoundException e) {
        throw new AssertionError("Failed to create rule sets", e);
    } catch (CoreException | IOException e) {
        throw new AssertionError("Failed to annotate file", e);
    }
}
Also used : RuleContext(net.sourceforge.pmd.RuleContext) CoreException(org.eclipse.core.runtime.CoreException) RuleSets(net.sourceforge.pmd.RuleSets) RuleSetNotFoundException(net.sourceforge.pmd.RuleSetNotFoundException) IOException(java.io.IOException)

Example 27 with RuleContext

use of net.sourceforge.pmd.RuleContext in project maven-plugins by apache.

the class PmdReport method processFilesWithPMD.

private void processFilesWithPMD(PMDConfiguration pmdConfiguration, List<DataSource> dataSources) throws MavenReportException {
    RuleSetFactory ruleSetFactory = new RuleSetFactory(RuleSetFactory.class.getClassLoader(), RulePriority.valueOf(this.minimumPriority), false, true);
    RuleContext ruleContext = new RuleContext();
    try {
        getLog().debug("Executing PMD...");
        PMD.processFiles(pmdConfiguration, ruleSetFactory, dataSources, ruleContext, Arrays.<Renderer>asList(renderer));
        if (getLog().isDebugEnabled()) {
            getLog().debug("PMD finished. Found " + renderer.getViolations().size() + " violations.");
        }
    } catch (Exception e) {
        String message = "Failure executing PMD: " + e.getLocalizedMessage();
        if (!skipPmdError) {
            throw new MavenReportException(message, e);
        }
        getLog().warn(message, e);
    }
}
Also used : RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleContext(net.sourceforge.pmd.RuleContext) ResourceNotFoundException(org.codehaus.plexus.resource.loader.ResourceNotFoundException) MavenReportException(org.apache.maven.reporting.MavenReportException) IOException(java.io.IOException) FileResourceCreationException(org.codehaus.plexus.resource.loader.FileResourceCreationException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileNotFoundException(java.io.FileNotFoundException) MavenReportException(org.apache.maven.reporting.MavenReportException)

Example 28 with RuleContext

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

the class Analyzer method runPMD.

private Iterable<RuleViolation> runPMD(final IFile file, final RuleSets ruleSets) {
    try {
        if (isValidFile(file, ruleSets)) {
            final Language language = LANGUAGES.get(file.getFileExtension().toLowerCase(Locale.ROOT));
            if (isValidLanguage(language)) {
                final PMDConfiguration configuration = new PMDConfiguration();
                try (InputStreamReader reader = new InputStreamReader(file.getContents(), file.getCharset())) {
                    final RuleContext context = PMD.newRuleContext(file.getName(), file.getRawLocation().toFile());
                    context.setLanguageVersion(language.getDefaultVersion());
                    context.setIgnoreExceptions(false);
                    new SourceCodeProcessor(configuration).processSourceCode(reader, ruleSets, context);
                    return ImmutableList.copyOf(context.getReport().iterator());
                }
            }
        }
    } catch (CoreException | IOException e) {
        PMDPlugin.getDefault().error("Could not run PMD on file " + file.getRawLocation(), e);
    } catch (final PMDException e) {
        if (isIncorrectSyntaxCause(e)) {
            PMDPlugin.getDefault().info("Could not run PMD because of incorrect syntax of file " + file.getRawLocation(), e);
        } else {
            PMDPlugin.getDefault().warn("Could not run PMD on file " + file.getRawLocation(), e);
        }
    }
    return ImmutableList.<RuleViolation>of();
}
Also used : Language(net.sourceforge.pmd.lang.Language) InputStreamReader(java.io.InputStreamReader) RuleContext(net.sourceforge.pmd.RuleContext) CoreException(org.eclipse.core.runtime.CoreException) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) PMDException(net.sourceforge.pmd.PMDException) IOException(java.io.IOException) RuleViolation(net.sourceforge.pmd.RuleViolation) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration)

Example 29 with RuleContext

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

the class PMDIntegrationTest method violationRangeAndRuleId.

@Test
public void violationRangeAndRuleId() throws IOException, RuleSetNotFoundException, PMDException {
    checkState(params.language.isPresent(), "%s: language is missing", testDataXml);
    checkState(params.pmdReferenceId.isPresent(), "%s: pmdReferenceId is missing", testDataXml);
    final Matcher languageMatcher = Pattern.compile("(.*)\\s+(\\d+[\\.\\d]+)").matcher(params.language.get());
    checkState(languageMatcher.matches(), "%s: language must be formated '<terse-name> <version>'", testDataXml);
    final Language language = LanguageRegistry.findLanguageByTerseName(languageMatcher.group(1));
    if (language == null) {
        failDueToInvalidTerseName(languageMatcher.group(1));
    }
    final LanguageVersion languageVersion = language.getVersion(languageMatcher.group(2));
    final String fileExtension = "." + languageVersion.getLanguage().getExtensions().get(0);
    final File sourceFile = File.createTempFile(getFilePrefix(params), fileExtension);
    try {
        final PMDConfiguration configuration = new PMDConfiguration();
        final Reader reader = new StringReader(params.source);
        final RuleContext context = PMD.newRuleContext(sourceFile.getName(), sourceFile);
        context.setLanguageVersion(languageVersion);
        final RuleSets ruleSets = RulesetsFactoryUtils.defaultFactory().createRuleSets(params.pmdReferenceId.get());
        new SourceCodeProcessor(configuration).processSourceCode(reader, ruleSets, context);
        // handle violations that PMD does not (yet) find.
        if (!context.getReport().isEmpty()) {
            // PMD might find more than one violation. If there is one with a matching range then the test passes.
            final Optional<RuleViolation> violation = Iterators.tryFind(context.getReport().iterator(), new Predicate<RuleViolation>() {

                @Override
                public boolean apply(final RuleViolation violation) {
                    final Range range = MarkerUtil.getAbsoluteRange(params.source, violation);
                    return params.offset == range.getStart() && params.length == range.getEnd() - range.getStart();
                }
            });
            assertTrue(testDataXml + " > " + params.name + ": couldn't find violation with expected range (offset = " + params.offset + ", length = " + params.length + ")", violation.isPresent());
            final JavaQuickFixGenerator generator = new JavaQuickFixGenerator();
            final PMDMarker marker = mock(PMDMarker.class);
            final String ruleId = MarkerUtil.createRuleId(violation.get().getRule());
            when(marker.getRuleId()).thenReturn(ruleId);
            when(marker.getMarkerText()).thenReturn("");
            final JavaQuickFixContext quickFixContext = new JavaQuickFixContext(new Version(languageVersion.getVersion()));
            assertTrue("The Java quick fix generator should have quick fixes for " + ruleId, generator.hasQuickFixes(marker, quickFixContext));
            assertTrue("The Java quick fix generator should have at least one quick fix besides the SuppressWarningsQuickFix for " + ruleId, generator.getQuickFixes(marker, quickFixContext).size() > 1);
        }
    } finally {
        sourceFile.delete();
    }
}
Also used : RuleContext(net.sourceforge.pmd.RuleContext) Matcher(java.util.regex.Matcher) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) Reader(java.io.Reader) StringReader(java.io.StringReader) RuleViolation(net.sourceforge.pmd.RuleViolation) Range(ch.acanda.eclipse.pmd.marker.MarkerUtil.Range) Language(net.sourceforge.pmd.lang.Language) Version(org.osgi.framework.Version) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) RuleSets(net.sourceforge.pmd.RuleSets) PMDMarker(ch.acanda.eclipse.pmd.marker.PMDMarker) StringReader(java.io.StringReader) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) File(java.io.File) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration) Test(org.junit.Test)

Example 30 with RuleContext

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

the class AbstractRule method addViolationWithMessage.

/**
 * @see RuleViolationFactory#addViolation(RuleContext, Rule, Node, String,
 * Object[])
 */
public void addViolationWithMessage(Object data, Node node, String message, Object[] args) {
    RuleContext ruleContext = (RuleContext) data;
    ruleContext.getLanguageVersion().getLanguageVersionHandler().getRuleViolationFactory().addViolation(ruleContext, this, node, message, args);
}
Also used : RuleContext(net.sourceforge.pmd.RuleContext)

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