View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.pmd;
20  
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.IOException;
24  import java.util.HashMap;
25  import java.util.HashSet;
26  import java.util.Map;
27  import java.util.Map.Entry;
28  import java.util.Properties;
29  import java.util.Set;
30  
31  import net.sourceforge.pmd.RuleViolation;
32  import org.apache.maven.plugin.MojoExecutionException;
33  import org.apache.maven.plugins.pmd.model.Violation;
34  
35  /**
36   * This class contains utility for loading property files, which define which PMD violations
37   * from which classes should be ignored and not cause a failure.
38   * See property <code>pmd.excludeFromFailureFile</code>.
39   *
40   * @author Andreas Dangel
41   */
42  public class ExcludeViolationsFromFile implements ExcludeFromFile<Violation> {
43      private Map<String, Set<String>> excludeFromFailureClasses = new HashMap<>();
44  
45      @Override
46      public void loadExcludeFromFailuresData(final String excludeFromFailureFile) throws MojoExecutionException {
47          if (excludeFromFailureFile == null || excludeFromFailureFile.isEmpty()) {
48              return;
49          }
50  
51          File file = new File(excludeFromFailureFile);
52          if (!file.exists()) {
53              return;
54          }
55          final Properties props = new Properties();
56          try (FileInputStream fileInputStream = new FileInputStream(new File(excludeFromFailureFile))) {
57              props.load(fileInputStream);
58          } catch (final IOException e) {
59              throw new MojoExecutionException("Cannot load properties file " + excludeFromFailureFile, e);
60          }
61          for (final Entry<Object, Object> propEntry : props.entrySet()) {
62              final Set<String> excludedRuleSet = new HashSet<>();
63              final String className = propEntry.getKey().toString();
64              final String[] excludedRules = propEntry.getValue().toString().split(",");
65              for (final String excludedRule : excludedRules) {
66                  excludedRuleSet.add(excludedRule.trim());
67              }
68              excludeFromFailureClasses.put(className, excludedRuleSet);
69          }
70      }
71  
72      @Override
73      public boolean isExcludedFromFailure(final Violation errorDetail) {
74          final String className = extractClassName(
75                  errorDetail.getViolationPackage(), errorDetail.getViolationClass(), errorDetail.getFileName());
76          return isExcludedFromFailure(className, errorDetail.getRule());
77      }
78  
79      /**
80       * Checks whether the given {@link RuleViolation} is excluded. Note: the exclusions must have been
81       * loaded before via {@link #loadExcludeFromFailuresData(String)}.
82       *
83       * @param errorDetail the violation to check
84       * @return <code>true</code> if the violation should be excluded, <code>false</code> otherwise.
85       */
86      public boolean isExcludedFromFailure(final RuleViolation errorDetail) {
87          final String className =
88                  extractClassName(errorDetail.getPackageName(), errorDetail.getClassName(), errorDetail.getFilename());
89          return isExcludedFromFailure(className, errorDetail.getRule().getName());
90      }
91  
92      @Override
93      public int countExclusions() {
94          int result = 0;
95          for (Set<String> rules : excludeFromFailureClasses.values()) {
96              result += rules.size();
97          }
98          return result;
99      }
100 
101     private boolean isExcludedFromFailure(String className, String ruleName) {
102         final Set<String> excludedRuleSet = excludeFromFailureClasses.get(className);
103         return excludedRuleSet != null && excludedRuleSet.contains(ruleName);
104     }
105 
106     private String extractClassName(String packageName, String className, String fullPath) {
107         // for some reason, some violations don't contain the package name, so we have to guess the full class name
108         // this looks like a bug in PMD - at least for UnusedImport rule.
109         if (packageName != null && !packageName.isEmpty() && className != null && !className.isEmpty()) {
110             return packageName + "." + className;
111         } else if (packageName != null && !packageName.isEmpty()) {
112             String fileName = fullPath;
113             fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
114             fileName = fileName.substring(0, fileName.length() - 5);
115             return packageName + "." + fileName;
116         } else {
117             final String fileName = fullPath;
118             final int javaIdx = fileName.indexOf(File.separator + "java" + File.separator);
119             return fileName.substring(javaIdx >= 0 ? javaIdx + 6 : 0, fileName.length() - 5)
120                     .replace(File.separatorChar, '.');
121         }
122     }
123 }