jenkins+maven配置findbugs+checkstyle+pmd

一、findbugs+checkstyle+pmd介绍

工具

目的

检查项

FindBugs

检查.class

基于Bug Patterns概念,查找javabytecode(.class文件)中的潜在bug

主要检查bytecode中的bug patterns,如NullPoint空指针检查、没有合理关闭资源、字符串相同判断错(==,而不是equals)等

PMD

检查源文件

检查Java源文件中的潜在问题

主要包括:

空try/catch/finally/switch语句块

未使用的局部变量、参数和private方法

空if/while语句

过于复杂的表达式,如不必要的if语句等

复杂类

CheckStyle

检查源文件

主要关注格式

检查Java源文件是否与代码规范相符

主要包括:

Javadoc注释

命名规范

多余没用的Imports

Size度量,如过长的方法

缺少必要的空格Whitespace

重复代码

 

二、jenkins配置

1.下载对应插件FindBugs、PMD、CheckStyle

 

 2.在maven中设置插件(pom.xml)

 1 <project ...>
 2     <properties>
 3         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 4         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 5     </properties>
 6 
 7     <!-- ...... -->
 8 
 9     <reporting>
10         <plugins>
11             <plugin>
12                 <groupId>org.codehaus.mojo</groupId>
13                 <artifactId>findbugs-maven-plugin</artifactId>
14                 <version>3.0.4</version>
15                 <configuration>
16                     <xmlOutput>true</xmlOutput>
17                     <findbugsXmlOutput>true</findbugsXmlOutput>
18                     <findbugsXmlWithMessages>true</findbugsXmlWithMessages>
19                 </configuration>
20             </plugin>
21             <plugin>
22                 <groupId>org.apache.maven.plugins</groupId>
23                 <artifactId>maven-checkstyle-plugin</artifactId>
24                 <version>2.17</version>
25                 <configuration>
26                     <linkXRef>false</linkXRef>
27                     <failsOnError>true</failsOnError>
28                     <consoleOutput>true</consoleOutput>
29                     <configLocation>checkstyle.xml</configLocation>
30                 </configuration>
31             </plugin>
32             <plugin>
33                 <groupId>org.apache.maven.plugins</groupId>
34                 <artifactId>maven-pmd-plugin</artifactId>
35                 <version>3.7</version>
36                 <configuration>
37                     <linkXref>false</linkXref>
38                 </configuration>
39             </plugin>
40         </plugins>
41     </reporting>
42 </project>

3.在pom.xml同目录下新增checkstyle.xml文件(可以放置其他目录,修改pom文件中此行:<configLocation>checkstyle.xml</configLocation>)

此处提供一个checksyle.xml文件模板,可根据具体所需进行配置

  1 <?xml version="1.0" encoding="UTF-8"?>  
  2 <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">  
  3   
  4 <!-- Generated by RHY @will_awoke -->  
  5   
  6 <module name="Checker">     
  7       
  8     <property name="charset" value="UTF-8"/>     
  9     <property name="severity" value="warning"/>  
 10       
 11     <!-- Checks for Size Violations.  -->   
 12     <!-- 检查文件的长度(行) default max=2000 -->   
 13     <module name="FileLength">           
 14      <property name="max" value="2500"/>          
 15   </module>    
 16     
 17   <!-- Checks that property files contain the same keys. -->   
 18   <!-- 检查**.properties配置文件 是否有相同的key  
 19   <module name="Translation">           
 20   </module>     
 21   -->   
 22       
 23   <module name="TreeWalker">  
 24       
 25     <!-- Checks for imports    -->                 
 26     <!-- 必须导入类的完整路径,即不能使用*导入所需的类 -->    
 27     <!--<module name="AvoidStarImport"/>  -->      
 28       
 29     <!-- 检查是否从非法的包中导入了类 illegalPkgs: 定义非法的包名称-->    
 30     <module name="IllegalImport"/> <!-- defaults to sun.* packages -->    
 31       
 32     <!-- 检查是否导入了不必显示导入的类-->    
 33     <module name="RedundantImport"/>    
 34       
 35     <!-- 检查是否导入的包没有使用-->    
 36     <module name="UnusedImports"/>  
 37       
 38     <!-- Checks for whitespace             
 39     <module name="EmptyForIteratorPad"/>  
 40     <module name="MethodParamPad"/>  
 41     <module name="NoWhitespaceAfter"/>  
 42     <module name="NoWhitespaceBefore"/>  
 43     <module name="OperatorWrap"/>  
 44     <module name="ParenPad"/>  
 45     <module name="TypecastParenPad"/>  
 46     <module name="WhitespaceAfter"/>  
 47     <module name="WhitespaceAround"/>  
 48     -->  
 49       
 50     <!-- 检查类和接口的javadoc 默认不检查author 和version tags         
 51       authorFormat: 检查author标签的格式  
 52             versionFormat: 检查version标签的格式  
 53             scope: 可以检查的类的范围,例如:public只能检查public修饰的类,private可以检查所有的类  
 54             excludeScope: 不能检查的类的范围,例如:public,public的类将不被检查,但访问权限小于public的类仍然会检查,其他的权限以此类推  
 55             tokens: 该属性适用的类型,例如:CLASS_DEF,INTERFACE_DEF -->  
 56     <module name="JavadocType">    
 57         <property name="authorFormat" value="\S"/>    
 58       <property name="scope" value="protected"/>          
 59       <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>    
 60     </module>  
 61       
 62     <!-- 检查方法的javadoc的注释  
 63             scope: 可以检查的方法的范围,例如:public只能检查public修饰的方法,private可以检查所有的方法  
 64             allowMissingParamTags: 是否忽略对参数注释的检查  
 65             allowMissingThrowsTags: 是否忽略对throws注释的检查  
 66             allowMissingReturnTag: 是否忽略对return注释的检查 -->  
 67     <module name="JavadocMethod">    
 68         <property name="scope" value="private"/>    
 69       <property name="allowMissingParamTags" value="false"/>    
 70       <property name="allowMissingThrowsTags" value="false"/>    
 71       <property name="allowMissingReturnTag" value="false"/>    
 72       <property name="tokens" value="METHOD_DEF"/>    
 73       <property name="allowUndeclaredRTE" value="true"/>    
 74       <property name="allowThrowsTagsForSubclasses" value="true"/>    
 75       <!--允许get set 方法没有注释-->  
 76         <property name="allowMissingPropertyJavadoc" value="true"/>  
 77     </module>    
 78           
 79     <!-- 检查类变量的注释  
 80             scope: 检查变量的范围,例如:public只能检查public修饰的变量,private可以检查所有的变量 -->      
 81     <module name="JavadocVariable">    
 82       <property name="scope" value="private"/>    
 83     </module>    
 84           
 85     <!--option: 定义左大括号'{'显示位置,eol在同一行显示,nl在下一行显示    
 86       maxLineLength: 大括号'{'所在行行最多容纳的字符数    
 87       tokens: 该属性适用的类型,例:CLASS_DEF,INTERFACE_DEF,METHOD_DEF,CTOR_DEF -->    
 88     <!--<module name="LeftCurly">   
 89         <property name="option" value="nl"/>  
 90     </module>  -->   
 91        
 92     <!-- NeedBraces 检查是否应该使用括号的地方没有加括号    
 93       tokens: 定义检查的类型 -->    
 94     <module name="NeedBraces"/>    
 95       
 96     <!-- Checks the placement of right curly braces ('}') for  else, try, and catch tokens. The policy to verify is specified using property  option.     
 97       option: 右大括号是否单独一行显示    
 98       tokens: 定义检查的类型  -->    
 99     <module name="RightCurly">      
100         <property name="option" value="alone"/>     
101     </module>  
102           
103     <!-- 检查在重写了equals方法后是否重写了hashCode方法 -->   
104     <module name="EqualsHashCode"/>  
105           
106     <!--  Checks for illegal instantiations where a factory method is preferred.    
107       Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.    
108       A simple example is the java.lang.Boolean class. In order to save memory and CPU cycles, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().    
109       Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools. -->    
110     <!--<module name="IllegalInstantiation">    
111         <property name="classes" value="java.lang.Boolean"/>    
112     </module>  -->   
113       
114     <!-- Checks for Naming Conventions.   命名规范   -->  
115     <!-- 局部的final变量,包括catch中的参数的检查 -->
116     <module name="LocalFinalVariableName"/>  
117       
118     <!-- 局部的非final型的变量,包括catch中的参数的检查 -->  
119     <module name="LocalVariableName"/>  
120       
121     <!-- 仅仅是static型的变量(不包括static final型)的检查 -->
122     <module name="StaticVariableName">  
123         <property name="format" value="(^[A-Z0-9_]{0,19}$)"/>      
124     </module>    
125       
126     <!-- 包名的检查(只允许小写字母) -->
127     <module name="PackageName">
128     <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
129     <message key="name.invalidPattern" value="Package name ''{0}'' must match pattern ''{1}''."/>
130     </module> 
131        
132     <!-- 类型(Class或Interface)名的检查 --> 
133     <module name="TypeName">    
134         <property name="format" value="(^[A-Z][a-zA-Z0-9]{0,19}$)"/>    
135     </module>  
136       
137     <!-- methods -->    
138     <module name="MethodName">            
139       <property name="format" value="(^[a-z][a-zA-Z0-9]{0,19}$)"/>           
140     </module>   
141       
142     <!-- non-static fields -->  
143     <module name="MemberName">    
144         <property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,19}$)"/>           
145     </module>  
146       
147     <!-- parameters -->  
148     <module name="ParameterName">  
149         <property name="format" value="(^[a-z][a-zA-Z0-9_]{0,19}$)"/>           
150     </module>  
151       
152     <!-- 常量名的检查,忽略log -->
153     <module name="ConstantName">   
154         <property name="format" value="^logger$|^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>     
155     </module>  
156       
157     <!-- 检查java代码的缩进 默认配置:基本缩进 4个空格,新行的大括号:0。新行的case 4个空格 -->
158     <module name="Indentation">
159     <property name="basicOffset" value="4"/>
160     <property name="braceAdjustment" value="0"/>
161     <property name="caseIndent" value="2"/>
162     <property name="throwsIndent" value="4"/>
163     <property name="lineWrappingIndentation" value="4"/>
164     <property name="arrayInitIndent" value="2"/>
165     </module>
166       
167     <!-- Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.   
168       检查是否抛出了多余的异常    
169     <module name="RedundantThrows">  
170         <property name="logLoadErrors" value="true"/>  
171         <property name="suppressLoadErrors" value="true"/>   
172     </module>  
173     -->   
174       
175      <!--  Checks for overly complicated boolean expressions. Currently finds code like  if (b == true), b || true, !false, etc.     
176        检查boolean值是否冗余的地方    
177        Rationale: Complex boolean logic makes code hard to understand and maintain. -->    
178     <module name="SimplifyBooleanExpression"/>  
179       
180     <!--  Checks for overly complicated boolean return statements. For example the following code    
181        检查是否存在过度复杂的boolean返回值    
182        if (valid())    
183           return false;    
184        else    
185           return true;    
186        could be written as    
187           return !valid();    
188        The Idea for this Check has been shamelessly stolen from the equivalent PMD rule. -->    
189     <module name="SimplifyBooleanReturn"/>    
190       
191     <!-- Checks that a class which has only private constructors is declared as final.只有私有构造器的类必须声明为final-->    
192     <module name="FinalClass"/>  
193       
194      <!--  Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.    
195        确保Utils类(只提供static方法和属性的类)没有public构造器。    
196        Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.    
197        If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:    
198        public class StringUtils // not final to allow subclassing    
199        {    
200            protected StringUtils() {    
201                throw new UnsupportedOperationException(); // prevents calls from subclass    
202            }    
203            public static int count(char c, String s) {    
204                // ...    
205            }    
206        }   
207     <module name="HideUtilityClassConstructor"/>   
208     -->   
209       
210     <!--  Checks visibility of class members. Only static final members may be public; other class members must be private unless property protectedAllowed or packageAllowed is set.    
211       检查class成员属性可见性。只有static final 修饰的成员是可以public的。其他的成员属性必需是private的,除非属性protectedAllowed或者packageAllowed设置了true.    
212        Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default). Note: Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow CMP for EJB 1.1 with the default settings. With EJB 2.0 it is not longer necessary to have public access for persistent fields, hence the default has been changed.    
213        Rationale: Enforce encapsulation. 强制封装 -->    
214     <module name="VisibilityModifier"/>   
215       
216     <!-- 每一行只能定义一个变量 -->  
217     <module name="MultipleVariableDeclarations">         
218     </module>  
219       
220      <!-- Checks the style of array type definitions. Some like Java-style: public static void main(String[] args) and some like C-style: public static void main(String args[])     
221        检查再定义数组时,采用java风格还是c风格,例如:int[] num是java风格,int num[]是c风格。默认是java风格-->    
222     <module name="ArrayTypeStyle">   
223     </module>  
224       
225     <!-- Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.   
226     <module name="MagicNumber">     
227     </module>  
228     -->    
229       
230     <!-- A check for TODO: comments. Actually it is a generic regular expression matcher on Java comments. To check for other patterns in Java comments, set property format.     
231        检查是否存在TODO(待处理) TODO是javaIDE自动生成的。一般代码写完后要去掉。    
232      -->    
233     <module name="TodoComment"/>    
234       
235     <!--  Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification,  Section 3.10.1.    
236       检查是否在long类型是否定义了大写的L.字母小写l和数字1(一)很相似。    
237       looks a lot like 1. -->    
238     <module name="UpperEll"/>  
239       
240     <!--  Checks that switch statement has "default" clause. 检查switch语句是否有‘default’从句    
241        Rationale: It's usually a good idea to introduce a default case in every switch statement.   
242        Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch,  
243         e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type. -->   
244     <module name="MissingSwitchDefault"/>   
245       
246     <!--检查switch中case后是否加入了跳出语句,例如:return、break、throw、continue -->  
247     <module name="FallThrough"/>    
248       
249     <!-- 方法的参数个数不超过6个。只所有有这么多参数,是因为Swing里面有可能就有这么长-->    
250     <module name="ParameterNumber">        
251       <property name="max" value="5"/>                
252     </module>  
253       
254     <!-- 每行字符数 -->      
255     <module name="LineLength">    
256       <property name="max" value="1000"/>         
257     </module>    
258       
259     <!-- Checks for long methods and constructors. max default 150行. max=300 设置长度300 -->   
260     <module name="MethodLength">    
261       <property name="max" value="300"/>                   
262     </module>          
263       
264     <!-- ModifierOrder 检查修饰符的顺序,默认是 public,protected,private,abstract,static,final,transient,volatile,synchronized,native -->    
265     <module name="ModifierOrder">            
266     </module>        
267       
268     <!-- 检查是否有多余的修饰符,例如:接口中的方法不必使用public、abstract修饰  -->  
269     <module name="RedundantModifier">         
270     </module>  
271       
272     <!--- 字符串比较必须使用 equals() -->     
273     <module name="StringLiteralEquality">            
274     </module>   
275       
276     <!-- if-else嵌套语句个数 最多4层 -->  
277     <module name="NestedIfDepth">          
278       <property name="max" value="3"/>           
279     </module>    
280       
281     <!-- try-catch 嵌套语句个数 最多2层 -->  
282     <module name="NestedTryDepth">    
283       <property name="max" value="2"/>           
284     </module>    
285           
286     <!-- 返回个数 -->     
287     <!--<module name="ReturnCount">          
288       <property name="max" value="5"/>    
289       <property name="format" value="^$"/>            
290     </module>-->                      
291     
292   </module>  
293     
294 </module> 

4.将pom.xml及checkstyle.xml文件上传的svn上,因为jenkins是通过svn地址去拿的代码

5.修改jenkins构建配置

“Build”标签页,Goals and options 设置为: 
package -Dmaven.test.skip=true findbugs:findbugs checkstyle:checkstyle pmd:pmd

“构建设置”标签页,打开以下三个选项: 
- Publish FindBugs analysis results 
- Publish Checkstyle analysis results 
- Publish PMD analysis results

6.构建完成,查看报告

 

posted @ 2018-06-11 16:58  子渝渝渝  阅读(659)  评论(0编辑  收藏  举报