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);
}
}
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);
}
}
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();
}
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();
}
}
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);
}
Aggregations