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.reporting.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 Map<String, String> additionalInfo = errorDetail.getAdditionalInfo();
88          final String className = extractClassName(
89                  additionalInfo.get(RuleViolation.PACKAGE_NAME),
90                  additionalInfo.get(RuleViolation.CLASS_NAME),
91                  errorDetail.getFileId().getAbsolutePath());
92          return isExcludedFromFailure(className, errorDetail.getRule().getName());
93      }
94  
95      @Override
96      public int countExclusions() {
97          int result = 0;
98          for (Set<String> rules : excludeFromFailureClasses.values()) {
99              result += rules.size();
100         }
101         return result;
102     }
103 
104     private boolean isExcludedFromFailure(String className, String ruleName) {
105         final Set<String> excludedRuleSet = excludeFromFailureClasses.get(className);
106         return excludedRuleSet != null && excludedRuleSet.contains(ruleName);
107     }
108 
109     private String extractClassName(String packageName, String className, String fullPath) {
110         // for some reason, some violations don't contain the package name, so we have to guess the full class name
111         // this looks like a bug in PMD - at least for UnusedImport rule.
112         if (packageName != null && !packageName.isEmpty() && className != null && !className.isEmpty()) {
113             return packageName + "." + className;
114         } else if (packageName != null && !packageName.isEmpty()) {
115             String fileName = fullPath;
116             fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
117             fileName = fileName.substring(0, fileName.length() - 5);
118             return packageName + "." + fileName;
119         } else {
120             final String fileName = fullPath;
121             final int javaIdx = fileName.indexOf(File.separator + "java" + File.separator);
122             return fileName.substring(javaIdx >= 0 ? javaIdx + 6 : 0, fileName.length() - 5)
123                     .replace(File.separatorChar, '.');
124         }
125     }
126 }