CheckStyle(Java代码审计工具)

2012年7月微软MVP申请开始啦!           CSDN十大风云博客专栏评选结果公布!            CSDN博客皮肤评选活动火爆开启!

CheckStyle(Java代码审计工具)

分类: Java工具类 76人阅读 评论(0) 收藏 举报
 

假设Checkstyle位于全局的classpath中,可以使用如下的taskdef定义:

<taskdef resource="checkstyletask.properties"/>

checkstyle任务的参数:

file:需要检查的文件。

config:指定配置文件。

configURL:指定配置文件的URL。

(config和configURL中必须指定一个)

properties:指定包含扩展属性值的属性文件。

packageNamesFile:指定一个包含配置的package名的文件。

failOnViolation:如果检查出错误时,是否停止。默认为true。

failureProperty:如果发生错误时,需要设置的属性的名称。

maxErrors:允许发生错误ude最大数。默认为0。

maxWarnings:允许发生的警告的最大数。默认值为整型的最大值。

classpath:查询类时使用的类路径。默认为当前classpath。

classpathref:类路径的引用。

嵌套元素:checkstyle任务支持以下的嵌套元素:<fileset>、<classpath>、<formatter>和<property>。其中<formatter>元素的参数如下:

type:生成的输出内容的类型,合法的值包括plain和xml。默认的值为plain。

toFile:将输出写入的文件。默认为标准输出。

useFile:是否将输出写入到文件,默认为true。

<property>元素指定提供扩展属性的值的属性文件。该元素的参数如下:

key:属性的键值。

value:字符串格式的属性的值。

file:文件格式的属性的值。

(value和file参数必须设置一个)

下面是一些例子:

<checkstyle config="docs/sun_checks.xml" file="Check.java"/>

 

<checkstyle config="/path/to/site/sun_checks.xml">

  <fileset dir="src/checkstyle" includes="**/*.java"/>

  <!-- Location of cache-file. Something that is project specific -->

  <property key="checkstyle.cache.file" file="target/cachefile"/>

</checkstyle>

 

<checkstyle config="docs/sun_checks.xml">

  <fileset dir="src/checkstyle" includes="**/*.java"/>

  <formatter type="plain"/>

  <formatter type="xml" toFile="build/checkstyle_errors.xml"/>

</checkstyle>

 

<checkstyle config="docs/sun_checks.xml"

            packageNamesFile="myPackageNames.xml"

            file="Check.java"/>

 

<target name="checkstyle"

        description="Generates a report of code convention violations.">

  <checkstyle config="docs/sun_checks.xml"

              failureProperty="checkstyle.failure"

              failOnViolation="false">

    <formatter type="xml" tofile="checkstyle_report.xml"/>

    <fileset dir="src" includes="**/*.java"/>

  </checkstyle>

  <style in="checkstyle_report.xml" out="checkstyle_report.html" style="checkstyle.xsl"/>

</target>

<!-- run this target as part of automated build -->

<target name="checkstyle-nightly"

        depends="checkstyle"

        if="checkstyle.failure"

        description="Sends email if checkstyle detected code conventions violations.">

  <!-- use your own server and email addresses below. See Ant documentation for details -->

  <mail from="[email protected]"

        tolist="[email protected],[email protected]"

        mailhost="mailbox.some.domain"

        subject="Checkstyle violation(s) in project ${ant.project.name}"

        files="checkstyle_report.html"/>

</target>

 

Checkstyle的命令行使用方式:

java -D<property>=<value>  \

     com.puppycrawl.tools.checkstyle.Main \

     -c <configurationFile> [-n <packageNameFile>] \

     [-f <format>] [-p <propertiesFile>] [-o <file>] \

     [-r <dir>] file...

    *   -n packageNamesFile - 指定使用的package name文件。

    * -f format - 指定输出的格式。

    * -p propertiesFile - 指定使用的属性文件。

    * -o file - 指定输出文件。

    * -r dir - 指定需要遍历java文件的目录。

CheckStyle一般配置:(正常情况下,该规则已足够)

  1. <?xml version="1.0" encoding="GB2312"?>  
  2. <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">  
  3.   
  4. <module name="Checker">  
  5.     <!-- 重复代码的检查,超过8行就认为重复,UTF-8格式   
  6.         本检查一定要放在"TreeWalker"节点前,否则在   
  7.         Checkclipse中会无法使用。(在ant下可以)   
  8.     -->  
  9.     <!-- <module name="StrictDuplicateCode">  
  10.         <property name="min" value="8" />  
  11.         <property name="charset" value="UTF-8" />  
  12.     </module>-->  
  13.     <!-- 文件长度不超过1500行 -->  
  14.         <module name="FileLength">  
  15.             <property name="max" value="1500" />  
  16.         </module>  
  17.   
  18.     <module name="TreeWalker">  
  19.   
  20.         <!-- javadoc的检查 -->  
  21.         <!-- 检查所有的interface和class -->  
  22.         <module name="JavadocType" />  
  23.   
  24.         <!-- 检查所有方法的javadoc,可以不声明RuntimeException -->  
  25.         <module name="JavadocMethod">  
  26.             <property name="allowUndeclaredRTE" value="true" />  
  27.         </module>  
  28.         <!-- 检查某个变量的javadoc -->  
  29.         <module name="JavadocVariable" />  
  30.   
  31.         <!-- 命名方面的检查,它们都使用了Sun官方定的规则。 -->  
  32.         <module name="TypeName" /><!-- 类名 (class 或interface) 的检查 -->  
  33.         <module name="MemberName" /><!-- 变量的检查 -->  
  34.         <module name="MethodName" /><!-- 方法名的检查 -->  
  35.         <module name="ParameterName " /><!-- 方法的参数名 -->  
  36.         <module name="ConstantName" /><!-- 常量名的检查 -->  
  37.   
  38.         <!-- 长度方面的检查 -->  
  39.           
  40.         <!-- 每行不超过120个字-->  
  41.         <module name="LineLength">  
  42.             <property name="max" value="120" />  
  43.         </module>  
  44.         <!-- 方法不超过30行 -->  
  45.         <module name="MethodLength">  
  46.             <property name="tokens" value="METHOD_DEF" />  
  47.             <property name="max" value="30" />  
  48.         </module>  
  49.         <!-- 方法的参数个数不超过3个。 -->  
  50.         <module name="ParameterNumber">  
  51.             <property name="max" value="3" />  
  52.         </module>  
  53.   
  54.         <!-- 多余的关键字 -->  
  55.         <module name="RedundantModifier" />  
  56.         <!-- 对区域的检查 -->  
  57.         <!-- 不能出现空白区域 -->  
  58.         <module name="EmptyBlock" />  
  59.         <!-- 所有区域都要使用大括号。 -->  
  60.         <module name="NeedBraces" />  
  61.         <!-- 多余的括号 -->  
  62.         <module name="AvoidNestedBlocks">  
  63.             <property name="allowInSwitchCase" value="true" />  
  64.         </module>  
  65.         <!-- 编码方面的检查 -->  
  66.   
  67.         <!-- 不许出现空语句 -->  
  68.         <module name="EmptyStatement" />  
  69.         <!-- 每个类都实现了equals()和hashCode() -->  
  70.         <module name="EqualsHashCode" />  
  71.         <!-- 不许使用switch -->  
  72.         <module name="IllegalToken">  
  73.             <property name="tokens" value="LITERAL_SWITCH" />  
  74.         </module>  
  75.         <!-- 不许内部赋值 -->  
  76.         <module name="InnerAssignment" />  
  77.         <!-- 绝对不能容忍魔法数 -->  
  78.         <module name="MagicNumber" />  
  79.         <!-- 循环控制变量不能被修改 -->  
  80.         <module name="ModifiedControlVariable" />  
  81.         <!-- 多余的throw -->  
  82.         <module name="RedundantThrows" />  
  83.         <!-- 不许使用未被简化的条件表达式 -->  
  84.         <module name="SimplifyBooleanExpression" />  
  85.         <!-- 不许使用未被简化的布尔返回值 -->  
  86.         <module name="SimplifyBooleanReturn" />  
  87.         <!-- String的比较不能用!= 和 == -->  
  88.         <module name="StringLiteralEquality" />  
  89.         <!-- if最多嵌套3层 -->  
  90.         <module name="NestedIfDepth">  
  91.             <property name="max" value="3" />  
  92.         </module>  
  93.         <!-- try最多被嵌套1层 -->  
  94.         <module name="NestedTryDepth" />  
  95.         <!-- clone方法必须调用了super.clone() -->  
  96.         <module name="SuperClone" />  
  97.         <!-- finalize 必须调用了super.finalize() -->  
  98.         <module name="SuperFinalize" />  
  99.         <!-- 不能catch java.lang.Exception -->  
  100.         <module name="IllegalCatch">  
  101.             <property name="illegalClassNames"  
  102.                 value="java.lang.Exception" />  
  103.         </module>  
  104.         <!-- JUnitTestCase 的核心方法存在。 -->  
  105.         <module name="JUnitTestCase" />  
  106.         <!-- 一个方法中最多有3个return -->  
  107.         <module name="ReturnCount">  
  108.             <property name="max" value="3" />  
  109.         </module>  
  110.         <!-- 不许对方法的参数赋值 -->  
  111.         <module name="ParameterAssignment" />  
  112.         <!-- 不许有同样内容的String -->  
  113.         <module name="MultipleStringLiterals" />  
  114.         <!-- 同一行不能有多个声明 -->  
  115.         <module name="MultipleVariableDeclarations" />  
  116.   
  117.         <!-- 各种量度 -->  
  118.         <!-- 布尔表达式的复杂度,不超过3 -->  
  119.         <module name="BooleanExpressionComplexity" />  
  120.         <!-- 类数据的抽象耦合,不超过7 -->  
  121.         <module name="ClassDataAbstractionCoupling" />  
  122.         <!-- 类的分散复杂度,不超过20 -->  
  123.         <module name="ClassFanOutComplexity" />  
  124.         <!-- 函数的分支复杂度,不超过10 -->  
  125.         <module name="CyclomaticComplexity" />  
  126.         <!-- NPath复杂度,不超过200 -->  
  127.         <module name="NPathComplexity" />  
  128.   
  129.         <!-- 杂项 -->  
  130.         <!-- 禁止使用System.out.println -->  
  131.         <!-- <module name="GenericIllegalRegexp">  
  132.   
  133.             <property name="format" value="System\.out\.println" />  
  134.             <property name="ignoreComments" value="true" />  
  135.         </module>-->  
  136.   
  137.         <!-- 不许使用与代码同行的注释 -->  
  138.         <module name="TrailingComment" />  
  139.   
  140.     </module>  
  141.   
  142.     <!-- 检查翻译文件       -->  
  143.     <module name="Translation" />  
  144.   
  145. </module>  

CheckStyle与Ant整合

  1. <?xml version="1.0" encoding="GB2312"?>  
  2.   
  3. <project name="CSA_WEB" default="my_check" basedir=".">   
  4.   <taskdef resource="checkstyletask.properties" classpath=".//WebRoot/WEB-INF/lib/checkstyle-5.3-all.jar"/>    
  5.   <target name="my_check">   
  6.     <checkstyle config="ant_audit_rule/my_checks.xml">   
  7.       <fileset dir="E:/MyEclipse6.6/workspace/CSA_WEB/WebRoot/ant_audit/ant_audit_code/297e2ae4313bdc5f01313bddc15e0001" includes="**/*.java"/>    
  8.       <formatter type="plain" toFile="ant_audit_log/checkstyle_errors.txt"/>    
  9.       <formatter type="xml" toFile="ant_audit_log/checkstyle_errors.xml"/>   
  10.     </checkstyle>   
  11.   </target>   
  12. </project>  

猜你喜欢

转载自h405589168.iteye.com/blog/1484503