net.sourceforge.pmd.RuleViolation Java Examples

The following examples show how to use net.sourceforge.pmd.RuleViolation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffTextRenderer.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException {
    DiffLineFilter filter = new DiffLineFilter(Main.DIFF_ENTRY_LIST);
    Writer writer = getWriter();
    StringBuilder buf = new StringBuilder();

    while (violations.hasNext()) {
        buf.setLength(0);
        RuleViolation rv = violations.next();
        if (!filter.accept(rv)) {
            continue;
        }
        buf.append(rv.getFilename());
        buf.append(':').append(Integer.toString(rv.getBeginLine()));
        buf.append(":\t").append(rv.getDescription()).append(PMD.EOL);
        writer.write(buf.toString());
    }
}
 
Example #2
Source File: PmdViolationRecorder.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
public void saveViolation(RuleViolation pmdViolation) {
  InputFile inputFile = findResourceFor(pmdViolation);
  if (inputFile == null) {
    // Save violations only for existing resources
    return;
  }

  Issuable issuable = perspectives.as(Issuable.class, inputFile);

  Rule rule = findRuleFor(pmdViolation);
  if (issuable == null || rule == null) {
    // Save violations only for enabled rules
    return;
  }

  IssueBuilder issueBuilder = issuable.newIssueBuilder()
    .ruleKey(rule.ruleKey())
    .message(pmdViolation.getDescription())
    .line(pmdViolation.getBeginLine());
  issuable.addIssue(issueBuilder.build());
}
 
Example #3
Source File: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
@Test
public void should_convert_pmd_violation_to_sonar_violation() {
  org.sonar.api.rules.Rule sonarRule = createRuleInRuleFinder("RULE");
  File file1 = new File("src/source.java");
  DefaultInputFile inputFile1 = addToFileSystem(file1);
  Issuable issuable = createIssuable(inputFile1);
  RuleViolation pmdViolation = createPmdViolation(file1, 42, "Description", "RULE");

  Issue issue = mock(Issue.class);
  IssueBuilder issueBuilder = mock(IssueBuilder.class);
  when(issuable.newIssueBuilder()).thenReturn(issueBuilder);
  when(issueBuilder.ruleKey(sonarRule.ruleKey())).thenReturn(issueBuilder);
  when(issueBuilder.message("Description")).thenReturn(issueBuilder);
  when(issueBuilder.line(42)).thenReturn(issueBuilder);
  when(issueBuilder.build()).thenReturn(issue);

  pmdViolationRecorder.saveViolation(pmdViolation);
  verify(issuable).addIssue(issue);
  verify(issueBuilder).ruleKey(sonarRule.ruleKey());
  verify(issueBuilder).message("Description");
  verify(issueBuilder).line(42);
  verify(sonarRule, atLeastOnce()).ruleKey();
}
 
Example #4
Source File: CollectorRendererTest.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@NotNull
private Report createReportWithVolation(@NotNull RuleViolation violation, @NotNull Configuration config) {
    renderer = new CollectorRenderer(config);
    Report report = mock(Report.class);
    List<RuleViolation> list = new ArrayList<RuleViolation>();
    list.add(violation);
    when(report.iterator()).thenReturn(list.iterator());

    return report;
}
 
Example #5
Source File: CollectorRendererTest.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@NotNull
private RuleViolation createRuleViolation(@NotNull Rule rule, String violationDescription, @NotNull Configuration config) {
    renderer = new CollectorRenderer(config);
    RuleViolation violation = mock(RuleViolation.class);
    when(violation.getRule()).thenReturn(rule);
    when(violation.getDescription()).thenReturn(violationDescription);

    return violation;
}
 
Example #6
Source File: CollectorRenderer.java    From sputnik with Apache License 2.0 5 votes vote down vote up
private String renderViolationDetails(RuleViolation ruleViolation) {
    StringBuilder fullDescription = new StringBuilder(ruleViolation.getDescription());

    String reason = ruleViolation.getRule().getDescription();
    if (StringUtils.isNotEmpty(reason)) {
        fullDescription.append(LINE_SEPARATOR).append(reason);
    }
    String url = ruleViolation.getRule().getExternalInfoUrl();
    if (StringUtils.isNotEmpty(url)) {
        fullDescription.append(LINE_SEPARATOR).append(url);
    }

    return fullDescription.toString();
}
 
Example #7
Source File: CollectorRenderer.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@Override
public void renderFileReport(Report report) throws IOException {
    boolean showDetails = Boolean.valueOf(configuration.getProperty(GeneralOption.PMD_SHOW_VIOLATION_DETAILS));

    for (RuleViolation ruleViolation : report) {
        String violationDescription = showDetails ? renderViolationDetails(ruleViolation) :ruleViolation.getDescription();
        reviewResult.add(new Violation(ruleViolation.getFilename(), ruleViolation.getBeginLine(), violationDescription, convert(ruleViolation.getRule().getPriority())));
    }
}
 
Example #8
Source File: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
private RuleViolation createPmdViolation(File file, int line, String description, String ruleName) {
  Rule rule = mock(Rule.class);
  when(rule.getName()).thenReturn(ruleName);
  RuleViolation pmdViolation = mock(RuleViolation.class);
  when(pmdViolation.getFilename()).thenReturn(file.getAbsolutePath());
  when(pmdViolation.getBeginLine()).thenReturn(line);
  when(pmdViolation.getDescription()).thenReturn(description);
  when(pmdViolation.getRule()).thenReturn(rule);
  return pmdViolation;
}
 
Example #9
Source File: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_ignore_violation_on_unknown_rule() {
  File file1 = new File("test/source.java");
  DefaultInputFile inputFile1 = addToFileSystem(file1);
  Issuable issuable = createIssuable(inputFile1);
  RuleViolation pmdViolation = createPmdViolation(file1, 42, "Description", "UNKNOWN");

  pmdViolationRecorder.saveViolation(pmdViolation);
  verifyZeroInteractions(issuable);
}
 
Example #10
Source File: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_ignore_violation_on_non_issuable_resource() {
  org.sonar.api.rules.Rule sonarRule = createRuleInRuleFinder("RULE");
  File file1 = new File("test/source.java");
  addToFileSystem(file1);
  RuleViolation pmdViolation = createPmdViolation(file1, 42, "Description", "RULE");

  pmdViolationRecorder.saveViolation(pmdViolation);
  verifyZeroInteractions(sonarRule);
}
 
Example #11
Source File: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_ignore_violation_on_unknown_resource() {
  org.sonar.api.rules.Rule sonarRule = createRuleInRuleFinder("RULE");
  File unknownFile = new File("src/UNKNOWN.java");
  RuleViolation pmdViolation = createPmdViolation(unknownFile, 42, "Description", "RULE");

  pmdViolationRecorder.saveViolation(pmdViolation);
  verifyZeroInteractions(sonarRule);
}
 
Example #12
Source File: PmdSensorTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void shouldnt_report_invalid_violation() {
  RuleViolation pmdViolation = violation();
  Report report = report(pmdViolation);
  when(executor.execute()).thenReturn(report);
  when(report.iterator()).thenReturn(Iterators.forArray(pmdViolation));

  pmdSensor.analyse(project, sensorContext);

  verifyZeroInteractions(sensorContext);
}
 
Example #13
Source File: PmdSensorTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_report_violations() {
  RuleViolation pmdViolation = violation();
  Report report = report(pmdViolation);
  when(executor.execute()).thenReturn(report);

  pmdSensor.analyse(project, sensorContext);

  verify(pmdViolationRecorder).saveViolation(pmdViolation);
}
 
Example #14
Source File: PmdSensor.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Override
public void analyse(Project project, SensorContext context) {
  try {
    Report report = executor.execute();
    for (RuleViolation violation : report) {
      pmdViolationRecorder.saveViolation(violation);
    }
  } catch (Exception e) {
    throw new XmlParserException(e);
  }
}
 
Example #15
Source File: PmdViolationRecorder.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
private Rule findRuleFor(RuleViolation violation) {
  String ruleKey = violation.getRule().getName();
  Rule rule = ruleFinder.findByKey(PmdConstants.REPOSITORY_KEY, ruleKey);
  if (rule != null) {
    return rule;
  }
  return ruleFinder.findByKey(PmdConstants.TEST_REPOSITORY_KEY, ruleKey);
}
 
Example #16
Source File: DiffLineFilter.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean accept(RuleViolation violation) {
    List<Edit> editList = fileEditMap.get(violation.getFilename());
    if (editList == null || editList.isEmpty()) {
        return false;
    }
    for (Edit edit : editList) {
        if (edit.getBeginB() <= violation.getBeginLine() && edit.getEndB() >= violation.getEndLine()) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: PmdSensorTest.java    From sonar-p3c-pmd with MIT License 4 votes vote down vote up
static RuleViolation violation() {
  return mock(RuleViolation.class);
}
 
Example #18
Source File: PmdViolationRecorder.java    From sonar-p3c-pmd with MIT License 4 votes vote down vote up
private InputFile findResourceFor(RuleViolation violation) {
  return fs.inputFile(fs.predicates().hasAbsolutePath(violation.getFilename()));
}
 
Example #19
Source File: PlainTextLanguage.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected RuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String s, int i, int i1) {
    return new ParametricRuleViolation<>(rule, ruleContext, node, s);
}
 
Example #20
Source File: PlainTextLanguage.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected RuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String s) {
    return new ParametricRuleViolation<>(rule, ruleContext, node, s);
}
 
Example #21
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * This method is the main entry point for command line usage.
 *
 * @param configuration the configure to use
 * @return number of violations found.
 */
public static int doPMD(PMDConfiguration configuration) {

    // 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 = Collections.emptyList();
    if (StringUtils.isNotBlank(configuration.getGitDir())) {
        files = getApplicableGitDiffFiles(configuration, languages);
    } else {
        files = getApplicableFiles(configuration, languages);
    }

    long reportStart = System.nanoTime();
    try {
        Renderer renderer = configuration.createRenderer();
        List<Renderer> renderers = Collections.singletonList(renderer);

        renderer.setWriter(IOUtil.createWriter(configuration.getReportFile()));
        renderer.start();

        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);

        RuleContext ctx = new RuleContext();
        final AtomicInteger violations = new AtomicInteger(0);
        DiffLineFilter filter = new DiffLineFilter(Main.DIFF_ENTRY_LIST);
        ctx.getReport().addListener(new ReportListener() {
            @Override
            public void ruleViolationAdded(RuleViolation ruleViolation) {
                if (!filter.accept(ruleViolation)) {
                    return;
                }
                violations.incrementAndGet();
            }
            @Override
            public void metricAdded(Metric metric) {
            }
        });

        processFiles(configuration, ruleSetFactory, files, ctx, renderers);

        reportStart = System.nanoTime();
        renderer.end();
        renderer.flush();
        return violations.get();
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            LOG.severe(message);
        } else {
            LOG.log(Level.SEVERE, "Exception during processing", e);
        }
        LOG.log(Level.FINE, "Exception during processing", e);
        LOG.info(PMDCommandLineInterface.buildUsageText());
        return 0;
    } finally {
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
    }
}