net.sourceforge.pmd.RuleContext Java Examples

The following examples show how to use net.sourceforge.pmd.RuleContext. 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: Main.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Run PMD on a list of files using multiple threads - if more than one is
 * available
 *
 * @param configuration
 *            Configuration
 * @param ruleSetFactory
 *            RuleSetFactory
 * @param files
 *            List<DataSource>
 * @param ctx
 *            RuleContext
 * @param renderers
 *            List<Renderer>
 */
public static void processFiles(final PMDConfiguration configuration, final RuleSetFactory ruleSetFactory,
        final List<DataSource> files, final RuleContext ctx, final List<Renderer> renderers) {

    sortFiles(configuration, files);

    /*
     * Check if multithreaded support is available. ExecutorService can also
     * be disabled if threadCount is not positive, e.g. using the
     * "-threads 0" command line option.
     */
    if (configuration.getThreads() > 0) {
        new MultiThreadProcessor(configuration).processFiles(ruleSetFactory, files, ctx, renderers);
    } else {
        new MonoThreadProcessor(configuration).processFiles(ruleSetFactory, files, ctx, renderers);
    }

    if (configuration.getClassLoader() instanceof ClasspathClassLoader) {
        IOUtil.tryCloseClassLoader(configuration.getClassLoader());
    }
}
 
Example #2
Source File: PmdExecutor.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
public void executeRules(PmdTemplate pmdFactory, RuleContext ruleContext, Iterable<File> files, String repositoryKey) {
  if (Iterables.isEmpty(files)) {
    // Nothing to analyze
    return;
  }

  RuleSets rulesets = createRulesets(repositoryKey);
  if (rulesets.getAllRules().isEmpty()) {
    // No rule
    return;
  }

  rulesets.start(ruleContext);

  for (File file : files) {
    pmdFactory.process(file, rulesets, ruleContext);
  }

  rulesets.end(ruleContext);
}
 
Example #3
Source File: PmdProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
/**
 * PMD has terrible design of process configuration. You must use report file with it. I paste this method here and
 * improve it.
 *
 * @throws IllegalArgumentException
 *             if the configuration is not correct
 */
private void doPMD(@NotNull PMDConfiguration configuration) throws IllegalArgumentException {
    // Load the RuleSets
    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration, new ResourceLoader());

    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSets(configuration.getRuleSets(), ruleSetFactory);
    // this is just double check - we don't get null here
    // instead IllegalArgumentException/RuntimeException is thrown if configuration is wrong
    if (ruleSets == null) {
        return;
    }

    Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
    // this throws RuntimeException when modified file does not exist in workspace
    List<DataSource> files = PMD.getApplicableFiles(configuration, languages);

    long reportStart = System.nanoTime();
    try {
        renderer = configuration.createRenderer();
        List<Renderer> renderers = new LinkedList<>();
        renderers.add(renderer);
        renderer.start();

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

        RuleContext ctx = new RuleContext();

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

        reportStart = System.nanoTime();
        renderer.end();
    } catch (IOException e) {
        log.error("PMD analysis error", e);
    } finally {
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
    }
}
 
Example #4
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new rule context, initialized with a new, empty report.
 *
 * @param sourceCodeFilename the source code filename
 * @param sourceCodeFile the source code file
 * @return the rule context
 */
public static RuleContext newRuleContext(String sourceCodeFilename, File sourceCodeFile) {

    RuleContext context = new RuleContext();
    context.setSourceCodeFile(sourceCodeFile);
    context.setSourceCodeFilename(sourceCodeFilename);
    context.setReport(new Report());
    return context;
}
 
Example #5
Source File: PmdExecutorTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_ignore_empty_test_dir() throws Exception {
  InputFile srcFile = file("src/Class.java", Type.MAIN);
  doReturn(pmdTemplate).when(pmdExecutor).createPmdTemplate(any(URLClassLoader.class));
  setupPmdRuleSet(PmdConstants.REPOSITORY_KEY, "simple.xml");
  fileSystem.add(srcFile);

  pmdExecutor.execute();

  verify(pmdTemplate).process(eq(srcFile.file()), any(RuleSets.class), any(RuleContext.class));
  verifyNoMoreInteractions(pmdTemplate);
}
 
Example #6
Source File: PmdTemplateTest.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
@Test
public void should_ignore_PMD_error() throws PMDException, FileNotFoundException {
  doThrow(new PMDException("BUG"))
    .when(processor).processSourceCode(any(InputStream.class), any(RuleSets.class), any(RuleContext.class));

  new PmdTemplate(configuration, processor).process(inputFile, rulesets, ruleContext);
}
 
Example #7
Source File: PmdExecutor.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
private Report executePmd(URLClassLoader classLoader) {
  Report report = new Report();

  RuleContext context = new RuleContext();
  context.setReport(report);

  PmdTemplate pmdFactory = createPmdTemplate(classLoader);
  executeRules(pmdFactory, context, javaFiles(Type.MAIN), PmdConstants.REPOSITORY_KEY);
  executeRules(pmdFactory, context, javaFiles(Type.TEST), PmdConstants.TEST_REPOSITORY_KEY);

  pmdConfiguration.dumpXmlReport(report);

  return report;
}
 
Example #8
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a report, filter out any defective rules, and keep a record of
 * them.
 *
 * @param rs the rules
 * @param ctx the rule context
 * @param fileName the filename of the source file, which should appear in the report
 * @return the Report
 */
public static Report setupReport(RuleSets rs, RuleContext ctx, String fileName) {

    Set<Rule> brokenRules = removeBrokenRules(rs);
    Report report = Report.createReport(ctx, fileName);

    for (Rule rule : brokenRules) {
        report.addConfigError(new Report.RuleConfigurationError(rule, rule.dysfunctionReason()));
    }

    return report;
}
 
Example #9
Source File: PlainTextLanguage.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected void visit(Rule rule, Node node, RuleContext ctx) {
    rule.apply(Collections.singletonList(node), ctx);
}
 
Example #10
Source File: MaximumMethodsCountCheck.java    From sonar-p3c-pmd with MIT License 4 votes vote down vote up
@Override
public void end(RuleContext ctx) {
  LOG.info("End " + getName());
}
 
Example #11
Source File: MaximumMethodsCountCheck.java    From sonar-p3c-pmd with MIT License 4 votes vote down vote up
@Override
public void start(RuleContext ctx) {
  LOG.info("Start " + getName());
}
 
Example #12
Source File: PlainTextLanguage.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected void indexNodes(List<Node> nodes, RuleContext ctx) {
    // there's a single node...
}
 
Example #13
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 #14
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 #15
Source File: XPathEvaluator.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Evaluates an XPath query on the compilation unit. Performs
 * no side effects.
 *
 * @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 static List<Node> evaluateQuery(Node compilationUnit,
                                       LanguageVersion languageVersion,
                                       String xpathVersion,
                                       String xpathQuery,
                                       Map<String, String> propertyValues,
                                       List<PropertyDescriptorSpec> properties) throws XPathEvaluationException {

    if (StringUtils.isBlank(xpathQuery)) {
        return 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);

        propertyValues.forEach((k, v) -> {
            PropertyDescriptor<?> d = xpathRule.getPropertyDescriptor(k);
            if (d != null) {
                setRulePropertyCapture(xpathRule, d, v);
            } else {
                throw new RuntimeException("Property '" + k + "' is not defined, available properties: "
                                               + properties.stream().map(PropertyDescriptorSpec::getName).collect(Collectors.toList()));
            }
        });

        final RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(xpathRule);

        RuleSets ruleSets = new RuleSets(ruleSet);

        RuleContext ruleContext = new RuleContext();
        ruleContext.setLanguageVersion(languageVersion);
        ruleContext.setIgnoreExceptions(false);

        ruleSets.apply(singletonList(compilationUnit), ruleContext, xpathRule.getLanguage());

        return results;

    } catch (RuntimeException e) {
        throw new XPathEvaluationException(e);
    }
}
 
Example #16
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);
    }
}
 
Example #17
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * An entry point that would typically be used by IDEs intent on providing
 * ongoing feedback and the ability to terminate it at will.
 *
 * @param configuration the PMD configuration to use
 * @param ruleSetFactory ruleset factory
 * @param files the files to analyze
 * @param ctx the rule context to use for the execution
 * @param monitor PMD informs about the progress through this progress monitor. It provides also
 * the ability to terminate/cancel the execution.
 */
public static void processFiles(PMDConfiguration configuration, RuleSetFactory ruleSetFactory,
        Collection<File> files, RuleContext ctx, ProgressMonitor monitor) {

    // TODO
    // call the main processFiles with just the new monitor and a single
    // logRenderer
}