CheckStyle(Java代码审计工具)

 

假设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="qa@some.domain"

        tolist="someone@some.domain,someoneelse@some.domain"

        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一般配置:(正常情况下,该规则已足够)

<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">

<module name="Checker">
	<!-- 重复代码的检查,超过8行就认为重复,UTF-8格式 
		本检查一定要放在"TreeWalker"节点前,否则在 
		Checkclipse中会无法使用。(在ant下可以) 
	-->
	<!-- <module name="StrictDuplicateCode">
		<property name="min" value="8" />
		<property name="charset" value="UTF-8" />
	</module>-->
	<!-- 文件长度不超过1500行 -->
		<module name="FileLength">
			<property name="max" value="1500" />
		</module>

	<module name="TreeWalker">

		<!-- javadoc的检查 -->
		<!-- 检查所有的interface和class -->
		<module name="JavadocType" />

		<!-- 检查所有方法的javadoc,可以不声明RuntimeException -->
		<module name="JavadocMethod">
			<property name="allowUndeclaredRTE" value="true" />
		</module>
		<!-- 检查某个变量的javadoc -->
		<module name="JavadocVariable" />

		<!-- 命名方面的检查,它们都使用了Sun官方定的规则。 -->
		<module name="TypeName" /><!-- 类名 (class 或interface) 的检查 -->
		<module name="MemberName" /><!-- 变量的检查 -->
		<module name="MethodName" /><!-- 方法名的检查 -->
		<module name="ParameterName " /><!-- 方法的参数名 -->
		<module name="ConstantName" /><!-- 常量名的检查 -->

		<!-- 长度方面的检查 -->
		
		<!-- 每行不超过120个字-->
		<module name="LineLength">
			<property name="max" value="120" />
		</module>
		<!-- 方法不超过30行 -->
		<module name="MethodLength">
			<property name="tokens" value="METHOD_DEF" />
			<property name="max" value="30" />
		</module>
		<!-- 方法的参数个数不超过3个。 -->
		<module name="ParameterNumber">
			<property name="max" value="3" />
		</module>

		<!-- 多余的关键字 -->
		<module name="RedundantModifier" />
		<!-- 对区域的检查 -->
		<!-- 不能出现空白区域 -->
		<module name="EmptyBlock" />
		<!-- 所有区域都要使用大括号。 -->
		<module name="NeedBraces" />
		<!-- 多余的括号 -->
		<module name="AvoidNestedBlocks">
			<property name="allowInSwitchCase" value="true" />
		</module>
		<!-- 编码方面的检查 -->

		<!-- 不许出现空语句 -->
		<module name="EmptyStatement" />
		<!-- 每个类都实现了equals()和hashCode() -->
		<module name="EqualsHashCode" />
		<!-- 不许使用switch -->
		<module name="IllegalToken">
			<property name="tokens" value="LITERAL_SWITCH" />
		</module>
		<!-- 不许内部赋值 -->
		<module name="InnerAssignment" />
		<!-- 绝对不能容忍魔法数 -->
		<module name="MagicNumber" />
		<!-- 循环控制变量不能被修改 -->
		<module name="ModifiedControlVariable" />
		<!-- 多余的throw -->
		<module name="RedundantThrows" />
		<!-- 不许使用未被简化的条件表达式 -->
		<module name="SimplifyBooleanExpression" />
		<!-- 不许使用未被简化的布尔返回值 -->
		<module name="SimplifyBooleanReturn" />
		<!-- String的比较不能用!= 和 == -->
		<module name="StringLiteralEquality" />
		<!-- if最多嵌套3层 -->
		<module name="NestedIfDepth">
			<property name="max" value="3" />
		</module>
		<!-- try最多被嵌套1层 -->
		<module name="NestedTryDepth" />
		<!-- clone方法必须调用了super.clone() -->
		<module name="SuperClone" />
		<!-- finalize 必须调用了super.finalize() -->
		<module name="SuperFinalize" />
		<!-- 不能catch java.lang.Exception -->
		<module name="IllegalCatch">
			<property name="illegalClassNames"
				value="java.lang.Exception" />
		</module>
		<!-- JUnitTestCase 的核心方法存在。 -->
		<module name="JUnitTestCase" />
		<!-- 一个方法中最多有3个return -->
		<module name="ReturnCount">
			<property name="max" value="3" />
		</module>
		<!-- 不许对方法的参数赋值 -->
		<module name="ParameterAssignment" />
		<!-- 不许有同样内容的String -->
		<module name="MultipleStringLiterals" />
		<!-- 同一行不能有多个声明 -->
		<module name="MultipleVariableDeclarations" />

		<!-- 各种量度 -->
		<!-- 布尔表达式的复杂度,不超过3 -->
		<module name="BooleanExpressionComplexity" />
		<!-- 类数据的抽象耦合,不超过7 -->
		<module name="ClassDataAbstractionCoupling" />
		<!-- 类的分散复杂度,不超过20 -->
		<module name="ClassFanOutComplexity" />
		<!-- 函数的分支复杂度,不超过10 -->
		<module name="CyclomaticComplexity" />
		<!-- NPath复杂度,不超过200 -->
		<module name="NPathComplexity" />

		<!-- 杂项 -->
		<!-- 禁止使用System.out.println -->
		<!-- <module name="GenericIllegalRegexp">

			<property name="format" value="System\.out\.println" />
			<property name="ignoreComments" value="true" />
		</module>-->

		<!-- 不许使用与代码同行的注释 -->
		<module name="TrailingComment" />

	</module>

	<!-- 检查翻译文件       -->
	<module name="Translation" />

</module>

CheckStyle与Ant整合

<?xml version="1.0" encoding="GB2312"?>

<project name="CSA_WEB" default="my_check" basedir="."> 
  <taskdef resource="checkstyletask.properties" classpath=".//WebRoot/WEB-INF/lib/checkstyle-5.3-all.jar"/>  
  <target name="my_check"> 
    <checkstyle config="ant_audit_rule/my_checks.xml"> 
      <fileset dir="E:/MyEclipse6.6/workspace/CSA_WEB/WebRoot/ant_audit/ant_audit_code/297e2ae4313bdc5f01313bddc15e0001" includes="**/*.java"/>  
      <formatter type="plain" toFile="ant_audit_log/checkstyle_errors.txt"/>  
      <formatter type="xml" toFile="ant_audit_log/checkstyle_errors.xml"/> 
    </checkstyle> 
  </target> 
</project>



 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值