net.sourceforge.pmd.RuleSetFactory Java Examples

The following examples show how to use net.sourceforge.pmd.RuleSetFactory. 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 5 votes vote down vote up
private RuleSets createRulesets(String repositoryKey) {
  String rulesXml = pmdProfileExporter.exportProfile(repositoryKey, rulesProfile);
  File ruleSetFile = pmdConfiguration.dumpXmlRuleSet(repositoryKey, rulesXml);
  String ruleSetFilePath = ruleSetFile.getAbsolutePath();
  RuleSetFactory ruleSetFactory = new RuleSetFactory();
  try {
    RuleSet ruleSet = ruleSetFactory.createRuleSet(ruleSetFilePath);
    return new RuleSets(ruleSet);
  } catch (RuleSetNotFoundException e) {
    throw new IllegalStateException(e);
  }
}
 
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 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 #5
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 #6
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
}