Tuesday, 3 June 2014

How to add JasperReports library to Gradle project

Usually adding new dependency is enough to add new library to Gradle project.

Unfortunately this is not that case.

To properly add JasperReports library we have to deal with compiling reports (new ant task) and adding new repositories.

New repositories


Standard repositories section look like this:

1
2
3
4
repositories {
 mavenLocal()
 mavenCentral()
}

JasperReports needs two additional repositories. It is because guys who develop this library often publish fixes to third-party libraries.
Our repositories section should look like this:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
repositories {
 mavenLocal()
 mavenCentral()
 maven {
  url "http://jasperreports.sourceforge.net/maven2"
 }
 maven {
  url "http://jaspersoft.artifactoryonline.com/jaspersoft/third-party-ce-artifacts/"
 }
}

Creating new configuration


Before we write ant task to compile reports we have to create configuration.

1
2
3
4
configurations.create('jasperreports')
configurations.jasperreports {
 transitive = true
}

Adding dependency


Nothing new here. Just add new dependency to your project dependencies section.

1
2
3
dependencies {
 jasperreports 'net.sf.jasperreports:jasperreports:5.5.2'
}

Creating sourceSet


In new sourceSet we will be holding variables for ant task.

1
2
3
4
5
6
sourceSets {
 jasper {
  srcDir = file(relativePath('src/main/resources/reports'))
  classesDir = srcDir
 }
}

Ant task


We have to create ant task to compile *.jrxml files.

1
2
3
4
5
6
7
8
9
task compileJasperJava(overwrite: true) << {
 ant {
  taskdef(name: 'jrc', classname: 'net.sf.jasperreports.ant.JRAntCompileTask', classpath: configurations.jasperreports.asPath)
  sourceSets.jasper.classesDir.mkdirs()
  jrc(srcdir: sourceSets.jasper.srcDir, destdir: sourceSets.jasper.classesDir) {
   include(name:'**/*.jrxml')
  }
 }
}

Adding our task to compilation cycle


Just add following line to your build.gradle file:

1
classes.dependsOn compileJasperJava

Source


Gradle forum