SonarQube 持续集成代码质量管理

 

目录

简介

集成

Sonar服务器

SonarQube汉化包

SonarQube 集成阿里P3c规范

应用

Sonar- Scanner手工执行分析

SonarLint  应用插件


简介

        SonarQube 是一个开源的代码分析平台,用来持续分析和评测代码的质量,支持检测 Java、JavaScript、C#、C、C++ 等二十几种编程语言。通过 SonarQube 可以检测出项目中潜在的Bug、漏洞、代码规范、重复代码、缺乏单元测试的代码等问题,并提供了 UI 界面进行查看和管理

  • SonarQube Server

SonarQube Server 会启动3个主要进程:

Web Server:UI 管理界面

Search Server:基于 Elasticsearch 的搜索服务

Compute Engine Server:计算引擎服务,进行代码分析并保存到SonarQube Database

  

  • SonarQube Database

存储 SonarQube 实例的配置信息,项目、视图等的快照信息

  

  • SonarQube Scanners

分析项目代码,可在构建/持续集成服务器上运行一个或多个

     

  • SonarQube Plugins 

          插件支持与管理

集成

搭建持续集成工具(如:Jenkins),

  • 工具中集成 SonarQube Scanners,根据持续集成工具设置的条件会自动触发拉取和 Build 代码,

    • SonarQube Server 对分析报告进行处理并保存到 SonarQube Database,同时可将分析报告发送给相关负责人进行 Review ,

    • 然后经过 SonarQube Scanners 分析并将分析报告发送到 SonarQube Server,

最终我们可以通过 UI 界面进行查看分析结果,开发人员对有问题的代码再次进行优化,如此循环。

Sonar服务器

Linux 下安装SonarQube (版本sonarqube7.6)_=PNZ=BeijingL的博客-CSDN博客公司的虚拟环境坏了,sonarqube需要重新安装。简单记录安装过程和遇到的问题。相关环境信息。https://blog.csdn.net/Beijing_L/article/details/130772649

SonarQube汉化包

访问官方插件库找到汉化链接: https://docs.sonarqube.org/display/PLUG/Plugin+Library

访问:GitHub - xuhuisheng/sonar-l10n-zh: Chinese Pack for SonarQube

将汉化包部署到   plugins 下   例如:D:\Soft\sonarqube-7.6\extensions\plugins\sonar-l10n-zh-plugin-1.26.jar

注意汉化包的兼容版本,

兼容列表如下:

SonarQube

8.0

8.1

8.2

8.3

8.4

8.5

sonar-l10n-zh

8.0

8.1

8.2

8.3

8.4

8.5

SonarQube

7.0

7.1

7.2

7.3

7.4

7.5

7.6

7.7

7.8

7.9

sonar-l10n-zh

1.20

1.21

1.22

1.23

1.24

1.25

1.26

1.27

1.28

1.29

SonarQube

6.0

6.1

6.2

6.3

6.4

6.5

6.6

6.7

sonar-l10n-zh

1.12

1.13

1.14

1.15

1.16

1.17

1.18

1.19

SonarQube

5.4

5.5

5.6

sonar-l10n-zh

1.9

1.10

1.11

SonarQube

4.0

4.1

sonar-l10n-zh

1.7

1.8

SonarQube

3.1

3.2

3.3

3.4

3.5

3.6

3.7

sonar-l10n-zh

SonarQube 集成阿里P3c规范

       随着我们鼓励重用和更好地理解彼此的程序,大量的Java编程团队对项目之间的代码质量提出了苛刻的要求。 过去我们已经看到许多编程问题。 例如,有缺陷的数据库表结构和索引设计可能会导致软件体系结构缺陷和性能风险。 另一个例子是难以维护的混乱代码结构。 此外,未经身份验证的易受攻击的代码容易受到黑客的攻击。 为了解决这类问题,我们在阿里巴巴为Java开发人员开发了本文档。alibaba p3c 地址: https://github.com/alibaba/p3c

       适当的规范和标准绝不是消灭代码内容的创造性、优雅性,而是限制过度个性化,以一种普遍认可的方式一起做事,降低故障率,提升协作效率。开发手册详细列举如何开发更加高效,更加容错,更加有协作性,力求知其然,更知其不然,结合正反例,提高代码质量

下载规则插件 sonar extensions/plugins,部署后重启SonarQube

设置SONAR

 设置P3C规则并激活

搜索P3C规则并批量修改激活

设置规则为默认规则

附录:

[p3c]'L' instead of 'l' should be used for long or Long variable.

Java异味

对于long或Long变量,应该使用“L”而不是“l”。

[p3c]A meaningful thread name is helpful to trace the error information,so assign a name when creating threads or thread pools.

Java异味

创建线程或线程池时请指定有意义的线程名称,方便出错时回溯

[p3c]Abstract class names must start with Abstract or Base.

Java异味

抽象类命名使用Abstract或Base开头

[p3c]Abstract methods (including methods in interface) should be commented by Javadoc.

Java异味

抽象方法和接口必须使用javadoc注释

[p3c]All enumeration type fields should be commented as Javadoc style.

Java异味

 

[p3c]All names should not start or end with an underline or a dollar sign.

Java异味

代码中的命名均不能以下划线或美元符号开始

[p3c]All Service and DAO classes must be interface based on SOA principle. Implementation class names.

Java异味

对于Service和DAO类,基于SOA的理念,暴露出来的服务一定是接口,内部的实现类用Impl的后缀与接口区别

[p3c]Attribute rollbackFor of annotation Transactional must be set.

Java异味

 

[p3c]Avoid using *Apache Beanutils* to copy attributes.

Java异味

避免使用*Apache Beanutils* 拷贝对象

[p3c]Avoid using [Math.random()] by multiple threads.

Java异味

避免Random实例被多线程使用,虽然共享该实例是线程安全的,但会因竞争同一seed 导致的性能下降。

[p3c]Avoid using the negation operator '!'.

Java异味

避免使用否定运算符“!”

[p3c]Braces are used with if, else, for, do and while statements, even if the body contains only a single statement.

Java异味

在if/else/for/while/do语句中必须使用大括号。即使只有一行代码

[p3c]Brackets are a part of an Array type. The definition could be: String[] args

Java异味

中括号是数组类型的一部分,数组定义如下:String[] args;

[p3c]Class names should be nouns in UpperCamelCase except domain models: DO, BO, DTO, VO, etc.

Java异味

类名使用UpperCamelCase风格,必须遵从驼峰形式,但以下情形例外:DO / BO / DTO / VO / AO

[p3c]Codes or configuration that is noticed to be obsoleted should be resolutely removed from projects.

Java异味

及时清理不再使用的代码段或配置信息

[p3c]Constant variable names should be written in upper characters separated by underscores.

Java异味

对于Service和DAO类,基于SOA的理念,暴露出来的服务一定是接口,内部的实现类用Impl的后缀与接口区别

[p3c]Constant variable names should be written in upper characters separated by underscores.

Java异味

常量命名全部大写,单词间用下划线隔开,力求语义表达完整清楚,不要嫌名字长

[p3c]Date format string is error,When doing date formatting, 'y' should be written in lowercase for 'year'..

Java异味

时间格式化的时, 字符年应该使用小写y

[p3c]Do not add 'is' as prefix while defining Boolean variable.

Java异味

POJO类中布尔类型的变量,都不要加is,否则部分框架解析会引起序列化错误

[p3c]Do not cast subList in class ArrayList, otherwise ClassCastException will be thrown.

Java异味

ArrayList的subList结果不可强转成ArrayList,否则会抛出ClassCastException异常

[p3c]Do not remove or add elements to a collection in a foreach loop.

Java异味

不要在foreach循环里进行元素的remove/add操作。remove元素请使用Iterator方式,如果并发操作,需要对Iterator对象加锁

[p3c]Do not use complicated statements in conditional statements.

Java异味

不要在条件语句中使用复杂语句

[p3c]Do not use methods which will modify the list after using Arrays.asList to convert array to list.

Java异味

使用工具类Arrays.asList()把数组转换成集合时,不能使用其修改集合相关的方法,它的add/remove/clear方法会抛出UnsupportedOperationException异常

[p3c]Do not use toArray method without arguments.

Java异味

使用toArray带参方法

[p3c]Equals should be invoked by a constant or an object that is definitely not null.

Java异味

Object的equals方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals

[p3c]Every class should include information of author(s) and date.

Java异味

每一个类都必须有作者和时间注释

[p3c]HashMap should set a size when initializing.

Java异味

集合初始化时,指定集合初始值大小。即:HashMap使用HashMap(int initialCapacity) 初始化,initialCapacity (需要存储的元素个数 / 负载因子) + 1。 注意 负载因子(即loader factor 默认为 0.75,如果 暂时无法 确定 初始值大小,请设置为 16(即默认值

[p3c]Magic values, except for predefined, are forbidden in coding.

Java异味

不允许任何魔法值(即未经定义的常量)直接出现在代码中

[p3c]Manually create thread pool is better.

Java异味

.....

[p3c]Method names, parameter names, member variable names, and local variable names should be written in lowerCamelCase.

Java异味

方法名、参数名、成员变量、局部变量都统一使用lowerCamelCase风格,必须遵从驼峰形式。

[p3c]Must be ended with Exception.

Java异味

异常类命名使用Exception结尾

[p3c]Never use return within a finally block.

Java异味

不能在finally块中使用return,finally块中的return返回后方法结束执行,不会再执行try块中的return语句

[p3c]Rules for using primitive data types and wrapper classes.

Java异味

 

[p3c]should be called in finally block.

Java异味

finally块必须对资源对象、流对象进行关闭,有异常也要做try-catch

[p3c]SimpleDataFormat is unsafe, do not define it as a static variable. If have to, lock or DateUtils class must be used.

Java异味

SimpleDateFormat 是线程不安全的类,一般不要定义为static变量,如果定义为static,必须加锁,或者使用DateUtils工具类

[p3c]Single line comments in a method should be put above the code to be commented, by using // and multiple lines by using /* */.

Java异味

方法内部单行注释,在被注释语句上方另起一行,使用//注释。方法内部多行注释使用/* */注释,注意与代码对齐

不能使用行尾注释

[p3c]Test cases should be ended with Test.

Java异味

 

[p3c]The return type of Math.random() is double, value range is 0<=x<1 (0 is possible).

Java异味

注意 Math.random() 这个方法返回是double类型,注意取值的范围 0≤x<1(能够取到零值,注意除零异常)

[p3c]The total number of lines for a method should not be more than 80.

Java异味

一个方法最多不能超过80行

[p3c]The wrapper classes should be compared by equals method rather than by symbol of '==' directly.

Java异味

所有的相同类型的包装类对象之间值的比较,全部使用equals方法比较,比使用==比较更好

[p3c]type 'ThreadLocal' must call remove() method at least one times.

Java异味

 

[p3c]Use ScheduledExecutorService instead.

Java异味

多线程并行处理定时任务时,Timer运行多个TimeTask时,只要其中之一没有捕获抛出的异常,其它任务便会自动终止运行,使用ScheduledExecutorService则没有这个问题,同场景建议使用ScheduledExecutorService 替换

[p3c]Use System.currentTimeMillis() to get the current millisecond. Do not use new Date().getTime().

Java异味

获取当前毫秒数System.currentTimeMillis(); 而不是new Date().getTime();

[p3c]Use the append method in StringBuilder inside a loop body when concatenating multiple strings.

Java异味

循环体内,字符串的连接方式,使用StringBuilder的append方法进行扩展

[p3c]We can call the toString method in a POJO directly to print property values.

Java异味

POJO类必须写toString方法。使用IDE的中工具:source> generate toString时,如果继承了另一个POJO类,注意在前面加一下super.toString。

[p3c]When using regex, precompile needs to be done in order to increase the matching performance.

Java异味

 

[p3c]When using subList, be careful to modify the size of original list.

Java异味

在subList场景中,高度注意对原集合元素个数的修改,会导致子列表的遍历、增加、删除均会产生ConcurrentModificationException 异常

[p3c]While defining POJO classes like DO, DTO, VO, etc., do not assign any default values to the members.

Java异味

定义POJO类时,不能定义成员变量有默认属性

应用

Sonar- Scanner手工执行分析

build.gradle

buildscript {
 
    repositories {
   
        maven {
            url "https://plugins.gradle.org/m2/"
        }
  
    }
 
    dependencies {
        .....
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6"
    }
}
 
apply plugin: "org.sonarqube"

gradle.properties


# gradle.properties
systemProp.sonar.host.url=http://192.168.10.29:9000
systemProp.sonar.login=admin
systemProp.sonar.password=admin
systemProp.sonar.projectKey=star2c-boss
systemProp.sonar.projectName=star2c-boss
systemProp.sonar.projectVersion=10.0.0
#----- Token generated from an account with 'publish analysis' permission

参数说明:

数项

说明

sonar.projectKey

项目Key,需要唯一,建议使用GroupId+ArtifactId

sonar.projectName

项目名称,跟ArtifactId保持一致即可

sonar.projectVersion

项目版本,跟pom.xml保持一致即可

sonar.sources

源码目录,Java项目默认就是src,如果项目有多个module,那就需要配置为{moduleDirectory}/src

sonar.java.binaries

编译产出的classes目录,如果项目有多个module,那就需要配置为{moduleDirectory}/target/classes

可以通过命令行gradlew sonarqube 命令分析代码,并将分析结果上传至服务器

Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
G:\GITLIB\demo>gradlew sonarqube
Starting a Gradle Daemon (subsequent builds will be faster)
[buildinfo] Not using buildInfo properties file for this build.
> Task :business:wechat-service:compileJava UP-TO-DATE
 .....
> Task :management:management-service:compileJava UP-TO-DATE
 .....
> Task :system:system-service:compileJava UP-TO-DATE
 .....
> Task :sonarqube
Invalid character encountered in file G:/GITLIB/star2c-boss/system/system-api/src/main/java/com/star/boss/product/enums/OpenDeviceType.java at line 129 for encoding UTF-8. Please fix file content or configure the encoding to be used using property 'sonar.sourceEnco
ding'.
 .....
BUILD SUCCESSFUL in 2m 27s
27 actionable tasks: 2 executed, 25 up-to-date

SonarLint  应用插件

      File–>Settings–>Plugins—>Browse Respositories ,搜索sonar,在搜索列表中选择SonarLint进行安装,根据提示重启idea即可

添加Sonarqube Server 
  依次点击File–>Settings–>Other Settings–>SonarLint General Settings,并进行如下操作

点击加号配置Service Detail  服务器信息

http://192.168.10.29:9000  管理员用户密码 admin/admin

设置登录信息 admin/admin

添加Sonarqube product 
  依次点击File–>Settings–>Other Settings–>SonarLint Project Settings,并进行如下操作

   类上右键 SonarLint - > Analyze with SonarLint,  分析后可以从开发环境中选中类就可以从下方看到分析结果

当然也可以从Sonar服务器上查看

上一篇:Oracle SQLTUNE性能分析

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

=PNZ=BeijingL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值