Straight from the Heart

How to integrate Sonar with Gradle

Posted on: March 27, 2012


Recently, I have got a fruitful chance to work on an integration task of a multi module Gradle project with Sonar. This was the first time; I worked on Gradle and find it really cool with multi project build support, powerful dependency management system, and already enriched domain model. Before this, I generally worked on ant, maven build systems but I have find gradle a bit easy as you can easily build logic inside the Gradle task by doing simple coding- yes you read it right; no godzilla sized xmls, shell scripts….just groovy code that runs on JVM.

But again, the efficacy of Gradle compare to other available build tool options is not our intent to discuss here.

So let’s see in few simple steps-how to integrate Sonar with gradle based projects.

Before start, we need to confirm if the current gradle version (and related sonar plugin) installed in our system supports multi project build and project setting configuration, if not, it’s time to migrate to the latest version.

Now go to your parent build.gradle file and put below lines, the second line will apply the Sonar plugin and include all related tasks into your build system.

Third line is here to apply cobertura.gradle file, to generate code coverage. remember the parent build.gradle and cobertua.gradle should be placed at the same level.

allprojects {    
apply plugin: 'sonar'
apply from: "$rootDir/cobertura.gradle"
--
--
}

Now let’s define the sonar specific configuration for each sub-project, add sonar URL and project related configuration detail under “project” as shown below. Unless Sonar is run locally and with default settings, it is also necessary to configure connection settings for the Sonar server and database.

subprojects {
sonar {

serverUrl = http://localhost:9000/

database {
url= ”jdbc:mysql://my.server.com/sonar”
driverClassName=”com.mysql.jdbc.driver”
username=”sonar”
password=”sonar”
}
project {
sourceEncoding = "UTF-8"
coberturaReportPath = file("build/ reports/coverage.xml")
}
}

We can see here- under project element, we are declaring cobertura report path in xml format, and this will be utilise by sonar to show code coverage.

So now we are pretty much done with the sonar integration with our multi project build system; but hey we have not created the code coverage files yet, just given the coverage file path. Here comes the choices, you can use some available open source plug-ins for coverage report generation or you can do generate with your own code as we are going to do in next few lines.

The groovy code(cobertura.gradle) given below is to instrument classes and create coverage reports. Reports in html and xml will be created at “build/reports”.

Available plug-ins for code coverage report generation are-

https://github.com/valkolovos/gradle_cobertura/wiki

https://github.com/bmuschko/gradle-clover-plugin

cobertura.gradle

logger.info "Configuring Cobertura Plugin"

configurations{
coberturaRuntime
} 
dependencies {

testRuntime(
[group: 'org.apache.ant', name: 'ant', version: '1.8.0'],
[group: 'net.sourceforge.cobertura', name: 'cobertura', version: '1.9.4.1']
)
coberturaRuntime group: 'net.sourceforge.cobertura', name: 'cobertura', version: '1.9.4.1'
} 

def serFile=new File(project.projectDir, 'build/cobertura/cobertura.ser')
def classes=new File(project.projectDir, 'build/classes')
def classesCopy="${classes}-copy"

task cobertura(type: Test){
useTestNG()
systemProperties["net.sourceforge.cobertura.datafile"] = serFile
} 

cobertura.doFirst {
logger.quiet "Instrumenting classes for Cobertura"
ant {
logger.quiet "Delete data file for cobertura, otherwise coverage would be added"
delete(file:serFile, failonerror:false)
logger.quiet "Delete copy of original classes"
delete(dir: classesCopy, failonerror:false)
logger.quiet "Create copy (backup) of original class files"
copy(todir: classesCopy) { fileset(dir: classes) }
taskdef(resource:'tasks.properties', classpath: configurations.coberturaRuntime.asPath)
'cobertura-instrument'(datafile: serFile) {
fileset(dir: classes,
includes:"**/*.class",
excludes:"**/*Test.class")
}
}
}

cobertura.doLast{
if (new File(classesCopy).exists()) {
logger.quiet "Create cobertura reports"
ant.'cobertura-report'(destdir:"build/reports",
format:'html', srcdir:"src/main/java", datafile: serFile)
ant.'cobertura-report'(destdir:"build/reports",
format:'xml', srcdir:"src/main/java", datafile: serFile)
logger.quiet "Replace instrumented classes with backup copy again"
ant.delete(file: classes)
ant.move(file: classesCopy, tofile: classes)
}
}

So finally we are done with the set-up, just run cobertura and sonar task defined in the files, once the coverage reports and sonar tasks are done, launch the URL given above and you are ready to analyse your project statistics🙂.

Feedback and Suggestions are welcome and please contact me if you have any difficulties or leave a comment below to help out other users.

Manu

1 Response to "How to integrate Sonar with Gradle"

Nice post.Useful information.Thanks for that.
I have a problem with integration of gradle with normal project.
I am using STS for my development.I have created a normal project and added build.gradle to that.I am not able to run it.STS is not identifying it as Gradel file.Can you please help me with this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Translator

a

The Calendar..तारीख

March 2012
M T W T F S S
« Jun   Jul »
 1234
567891011
12131415161718
19202122232425
262728293031  

गुफ्तुगू ….

Sindhu on How to integrate Sonar with…
Naga Anji on EMMA: a free Java code coverag…
Manu on Hiring
jarvarm on Hiring
Manu on Hiring

पन्ना

हिसाब-किताब

  • 37,617 hits

Tashveerein.......तसवीरें

Ceannabeinne

Cuckoo, Cuckoo

All the Small Mistakes

The Old Teahouse in Pengzhen Town, Chengdu

Kestrel      (Falco tinnunculus)

American Crow

Sony A7 MII + Zeiss Sonnar 50/1.5 ZM

Einsam

sparkles

Tunnel View Sunset

More Photos

Thanks for the Visit…आने का शुक्रिया

website statistics

Rumbling of Mind

  • Sushil Kumar has won his second Olympic medal, become the first Indian to win two individual Olympic medals for India. Respect. 4 years ago
  • Satyamev Jayate-A great initiative by Aamir Khan & company....must watch on star plus/DD National every Sunday 11:00 AM 4 years ago
  • @sujeetkant number is changed..sent on your linkedin.. 4 years ago
  • @sujeetkant dude I m fine..howz life at you end ..long time 4 years ago
  • In real bad mood.. :( Banged my car today.. 4 years ago

Aaate-Jaate..आते-जाते

Top Clicks..पसंदीदा

  • None

The Selected One’s..चुनिन्दा

U come from..

%d bloggers like this: