持续集成工具Sonar的使用(二)[ant+sonar]

来源:互联网 发布:搞笑网络短剧前十名 编辑:程序博客网 时间:2024/05/17 04:06

 

上一篇我们讲述了Sonar和Maven的结合来达到代码质量审查的效果,但是由于maven的学习成本高,并不是任何项目都适合,因此本篇我们讲述一下如何通过Sonar和ant的结合来进行代码质量审查。
 
目前来说,Sonar和Ant的集成没有做到Sonar和Maven的集成这么好,因此在使用过程中需要多写一些脚本。我们下面来介绍一下使用步骤吧:
  1、下载Sonar并解压到任何目录,注意目录中不允许有中文;
  2、点击bin\windows-x86-32\StartSonar.bat启动Sonar;
  3、下载一个ant插件:sonar-ant-task-1.1.jar,并存放到某个路径,ant脚本需要访问这个文件。
  4、编写一个ant脚本,如下:

<?xml version="1.0" encoding="UTF-8" ?>

<project name="framework-client" default="sonar" basedir=".">
  
 <property name="project.name" value="framework-client"/>
 <property name="src.dir" value="${basedir}/src/main/java" />
 <property name="lib.dir" value="${basedir}/lib"/>
 
   <!-- Out-of-the-box those parameters are optional -->
   <!-- EXAMPLE FOR MYSQL    
   <property name="sonar.jdbc.url"
        value="jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8" />
   <property name="sonar.jdbc.driverClassName" value="com.mysql.jdbc.Driver" />
   <property name="sonar.jdbc.username" value="sonar" />
   <property name="sonar.jdbc.password" value="sonar" />
   -->

   <!-- SERVER ON A REMOTE HOST -->
   <!--
   <property key="sonar.host.url" value="http://myserver:1234" />
   -->
 
   <!-- Define the Sonar task if this hasn't been done in a common script -->
   <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml">
     <classpath>
       <pathelement location="${lib.dir}/sonar-ant-task-1.1.jar"/>
     </classpath>
   </taskdef>
  
   <!-- Add the target -->
   <target name="sonar">
     <!-- list of mandatories Sonar properties -->
     <property name="sonar.sources" value="${src.dir}" />
    <property name="sonar.projectKey" value="org.example:${project.name}" />

     <!-- list of optional Sonar properties -->
    <!--
     <property key="sonar.projectName" value="this value overrides the name defined in Ant root node" />
     <property key="sonar.binaries" value="list of directories which contain for example the Java bytecode" />
     <property key="sonar.tests" value="list of test source directories separated by a comma" />
     <property key="sonar.libraries" value="list of paths to libraries separated by a comma (These libraries are for example used by the Sonar Findbugs plugin)" />
    -->
    
     <sonar:sonar key="${sonar.projectKey}" version="0.9" xmlns:sonar="antlib:org.sonar.ant"/>

    </target>
</project>

  5、运行ant脚本,看到build successfully的提示后,就可以访问:http://localhost:9000/来查看代码质量审查结果了。

上述是使用Sonar和ant最简单的步骤,用了Sonar自带的嵌入式数据库Derby,以及standalone的应用服务器,当然也支持使用其它数据库,比如:mysql,只要修改一下sonar.properties的配置文件,以及在ant脚本中配置一下连接数据库的方式。另外也可以使用tomcat、jboss等应用服务器来发布Sonar应用,只要运行一下Sonar自带的一个脚本:build-war.bat就可以了,这里不再详述。