View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.pmd;
6   
7   import com.qulice.spi.Environment;
8   import com.qulice.spi.ResourceValidator;
9   import com.qulice.spi.Violation;
10  import java.io.File;
11  import java.util.Collection;
12  import java.util.LinkedList;
13  
14  /**
15   * Validates source code with PMD.
16   *
17   * @since 0.3
18   */
19  public final class PmdValidator implements ResourceValidator {
20  
21      /**
22       * Environment to use.
23       */
24      private final transient Environment env;
25  
26      /**
27       * Constructor.
28       * @param env Environment to use.
29       */
30      public PmdValidator(final Environment env) {
31          this.env = env;
32      }
33  
34      @Override
35      @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
36      public Collection<Violation> validate(final Collection<File> files) {
37          final SourceValidator validator = new SourceValidator(this.env);
38          final Collection<File> sources = this.getNonExcludedFiles(files);
39          final Collection<PmdError> errors = validator.validate(
40              sources, this.env.basedir().getPath()
41          );
42          final Collection<Violation> violations = new LinkedList<>();
43          for (final PmdError error : errors) {
44              violations.add(
45                  new Violation.Default(
46                      this.name(),
47                      error.name(),
48                      error.fileName(),
49                      error.lines(),
50                      error.description()
51                  )
52              );
53          }
54          return violations;
55      }
56  
57      @Override
58      public String name() {
59          return "PMD";
60      }
61  
62      /**
63       * Filters out excluded files from further validation.
64       * @param files Files to validate
65       * @return Relevant source files
66       */
67      public Collection<File> getNonExcludedFiles(final Collection<File> files) {
68          final Collection<File> sources = new LinkedList<>();
69          for (final File file : files) {
70              final String name = file.getPath().substring(
71                  this.env.basedir().toString().length()
72              );
73              if (this.env.exclude("pmd", name)) {
74                  continue;
75              }
76              if (!name.matches("^.*\\.java$")) {
77                  continue;
78              }
79              sources.add(file);
80          }
81          return sources;
82      }
83  }