一、sonar環境搭建 1、安裝JDK-1.5以上版本。 2、安裝mysql-5.x以上版本。 3、mysql新建數據庫並增加權限
CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
GRANT all ON sonar.* TO sonar@localhost IDENTIFIED BY 'sonar';
FLUSH PRIVILEGES
4、在sonar官網www.sonarsouce.org上下載並解壓sonar-2.8.zip,不要放在中文目錄下。
5、配置sonar-2.8\conf\sonar.properties文件。 1)配置啓動的http端口
sonar.web.host: localhost
sonar.web.port: 9000
sonar.web.context: /
三句前本來被註釋,取消註釋 2)取消mysql連接的註釋 #----- MySQL 5.x/6.x
# Comment the embedded database and uncomment the following properties to use MySQL. The validation query is optional.
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
sonar.jdbc.driverClassName=com.mysql.jdbc.Driver
sonar.jdbc.validationQuery=SELECT1
運行sonar-2.8\bin\windows-x86-32\StartSonar.bat,打開相應的網頁:
http://localhost:9000測試是否配置成功,這裏的頁面鏈接跟前頭的http配置有關
二、配置sonar-runner
1、下載並解壓sonar-runner.zip 官網下載網址:
http://repository.codehaus.org/org/codehaus/sonar-plugins/sonar-runner/1.0/sonar-runner-2.0.zip
2、環境變量,設置SONAR_RUNNER_HOME,在Path下添${SONAR_RUNNER_HOME}/bin (Unix) or %SONAR_RUNNER_HOME%/bin。
3、修改${SONAR_RUNNER_HOME}/conf/sonar-runner.properties文件,打開database connection, server URL的註釋
命令行中輸入sonar-runner –h查看是否配置成功
三、測試文件的配置
1、在每個項目的項目源文件目錄下新建一個文件名爲sonar-project.properties的文件,在文件中輸入以下內容:
# required metadata
# My project------修改成你的項目名稱
sonar.projectKey=my:project
sonar.projectName=My project
sonar.projectVersion=1.0
# path to source directories (required)
# srcDir1,srcDir2---------修改成你的源文件夾路徑
sources=srcDir1,srcDir2
# path to test source directories (optional) # testDir1,testDir2--------修改成你的測試文件夾路徑
tests=testDir1,testDir2
# path to project binaries (optional), for example directory of Java #bytecode
# binDir--------修改成你的二進制文件夾路徑
binaries=binDir
# path to project libraries (optional)
libraries=junit.jar
# advanced parameters
my.property=value
四、應用sonar監測代碼質量
以上配置完成之後,就可以應用sonar來監測代碼質量了。
1、先啓動sonar用sonar-2.8\bin\windows-x86-32\ StartSonar.bat文件,這時可以查看sonar-2.8\logs\ sonar.log文件,看是否已經啓動sonar
2、啓動好sonar之後,接着在命令行中切換到項目文件的目錄下,然後輸入sonar-runner,等到運行結束後,進入到http://localhost:9000頁面,查看代碼的質量統計結果。
五、錯誤:java.lang.OutOfMemoryError處理方法:
在sonar-runner-1.0\bin\sonar-runner.bat文件中修改內存容量:
Set JAVA_OPTS=-Xms128m –Xmx512m %JAVA_OPTS%
maven下配置sonar
Edit the settings.xmlfile, located in$MAVEN_HOME/conf or ~/.m2, to set the database parameters to be used as well asthe SonarQube server URL.
Example:
<settings>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Example for MySQL-->
<sonar.jdbc.url>
jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
</sonar.jdbc.url>
<sonar.jdbc.username>sonar</sonar.jdbc.username>
<sonar.jdbc.password>sonar</sonar.jdbc.password>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
</sonar.host.url>
</properties>
</profile>
</profiles>
</settings>
在maven中只要使用mvnsonar:sonar這樣的命令就可以對當前工程進行分析了