Search in sources :

Example 6 with SourceCodeProcessor

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

the class XPathRuleTest method getReportForTestString.

private static Report getReportForTestString(Rule r, String test) throws PMDException {
    RuleContext ctx = new RuleContext();
    Report report = new Report();
    ctx.setReport(report);
    ctx.setSourceCodeFile(new File("n/a"));
    RuleSet rules = RuleSet.forSingleRule(r);
    SourceCodeProcessor sourceCodeProcessor = new SourceCodeProcessor(new PMDConfiguration());
    sourceCodeProcessor.processSourceCode(new StringReader(test), new RuleSets(rules), ctx);
    return report;
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) RuleContext(net.sourceforge.pmd.RuleContext) Report(net.sourceforge.pmd.Report) RuleSets(net.sourceforge.pmd.RuleSets) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) StringReader(java.io.StringReader) File(java.io.File) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration)

Example 7 with SourceCodeProcessor

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

the class ReviewResourceForRuleCommand method execute.

@Override
public void execute() {
    // IProject project = resource.getProject();
    IFile file = (IFile) resource.getAdapter(IFile.class);
    beginTask("PMD checking for rule: " + rule.getName(), 1);
    if (file != null) {
        RuleSet ruleSet = RuleSetUtil.newSingle(rule);
        // final PMDEngine pmdEngine = getPmdEngineForProject(project);
        File sourceCodeFile = file.getFullPath().toFile();
        if (ruleSet.applies(sourceCodeFile)) {
            try {
                context = PMD.newRuleContext(file.getName(), sourceCodeFile);
                // Reader input = new InputStreamReader(file.getContents(),
                // file.getCharset());
                new SourceCodeProcessor(new PMDConfiguration()).processSourceCode(file.getContents(), InternalRuleSetUtil.toRuleSets(Collections.singletonList(ruleSet)), context);
            // input.close();
            // } catch (CoreException e) {
            // throw new CommandException(e);
            } catch (PMDException | CoreException e) {
                throw new RuntimeException(e);
            }
            // trigger event propertyChanged for all listeners
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    for (IPropertyListener listener : listenerList) {
                        listener.propertyChanged(context.getReport().getViolations().iterator(), PMDRuntimeConstants.PROPERTY_REVIEW);
                    }
                }
            });
        }
    }
}
Also used : RuleSet(net.sourceforge.pmd.RuleSet) IFile(org.eclipse.core.resources.IFile) CoreException(org.eclipse.core.runtime.CoreException) SourceCodeProcessor(net.sourceforge.pmd.SourceCodeProcessor) PMDException(net.sourceforge.pmd.PMDException) File(java.io.File) IFile(org.eclipse.core.resources.IFile) IPropertyListener(org.eclipse.ui.IPropertyListener) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration)

Example 8 with SourceCodeProcessor

use of net.sourceforge.pmd.SourceCodeProcessor 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 9 with SourceCodeProcessor

use of net.sourceforge.pmd.SourceCodeProcessor 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 10 with SourceCodeProcessor

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

Aggregations

SourceCodeProcessor (net.sourceforge.pmd.SourceCodeProcessor)13 PMDConfiguration (net.sourceforge.pmd.PMDConfiguration)11 RuleContext (net.sourceforge.pmd.RuleContext)10 RuleSet (net.sourceforge.pmd.RuleSet)9 RuleSets (net.sourceforge.pmd.RuleSets)9 PMDException (net.sourceforge.pmd.PMDException)8 File (java.io.File)7 Report (net.sourceforge.pmd.Report)6 RuleViolation (net.sourceforge.pmd.RuleViolation)5 StringReader (java.io.StringReader)4 RuleSetNotFoundException (net.sourceforge.pmd.RuleSetNotFoundException)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 RuleSetFactory (net.sourceforge.pmd.RuleSetFactory)3 DataSource (net.sourceforge.pmd.util.datasource.DataSource)3 BufferedInputStream (java.io.BufferedInputStream)2 Language (net.sourceforge.pmd.lang.Language)2 CoreException (org.eclipse.core.runtime.CoreException)2 Range (ch.acanda.eclipse.pmd.marker.MarkerUtil.Range)1