Skip to end of metadata
Go to start of metadata


about this cookbook

This page will contain short information on "how to do X, Y and Z using Gradle". It is not a Gradle tutorial, nor is it a comprehensive source of knowledge. The aim of this cookbook is to give you fast answers to your urgent needs.
intelli


It differs both from the the userguide (which contains so much information that it is sometimes hard to find interesting bits) and from the FAQ (which says what can be done with Gradle, but does not explain how to do it).

How can you help ?

  • Add new information here (for example if you find an interesting topic on the mailing lists).
  • Make sure that the existing information are still valid (maybe the latests version of Gradle makes things easier ?).
  • Correct mistakes, errors and typos.

general issues

Please consult the archives of mailing lists - plenty of great stuff there. (smile) But be careful - some posts might be outdated as Gradle is evolving really fast. There is an IRC channel on irc.codehaus.org #gradle

problems after upgrade to newer version of Gradle

If something doesn't work after you upgraded Gradle, please have a look at "breaking changes" sites:


plugins

Information on plugins has been moved to Plugins page.


web development

Small but useful hints on web development.

creation of exploded war

To create an exploded war simply add this snippet to build.gradle (Gradle 0.9+)

build.gradle

Alternatively, you can get the war task to build both the war and the exploded war:

build.gradle

running selenium tests

See this thread for some hints http://gradle.1045684.n5.nabble.com/working-example-of-gradle-running-selenium-tests-tp4549630p4549630.html


creating new project (structure, directories)

creating source and resource directories

You've just created a new Java project but you're too lazy to create the source and resource directory layout. This code does that for you:

build.gradle

Starting from Gradle 0.9 preview 1 this becomes:

build.gradle

The same for Gradle 1.0:

build.gradle

create project, archetypes etc

See https://github.com/townsfolk/gradle-templates plugin. Also read comments on this JIRA issue http://jira.codehaus.org/browse/GRADLE-1289 and vote if you think it is needed.


reports

maven-like site

Try https://github.com/breskeby/GradleSite plugin.


missing features

This section gathers description of how to achieve things that users of other build tools might expect to be available "out of the box".

Hopefully this is the only section of this cookbook that will shrink over time till it vanishes completely...

  • advanced ssh support (including tunnelling and ssh options)
  • Gradle metaprogramming

running things from Gradle

If you need functionality a'la exec-maven-plugin:

build.gradle

creating GroovyEclipse project files

For use with http://groovy.codehaus.org/Eclipse+Plugin

Gradle 0.9 does this automatically when you apply the Groovy and Eclipse plugins.

For Gradle 0.8:

build.gradle

applying plugins via init script

In some scenarios it maybe helpful to apply a plugin not directly in a build script but in a init script. In gradle 0.9 you can do that in the following way:

init.gradle

Dependencies

Everything you wanted to know about the dependencies ...but were afraid to read the whole userguide. (wink)

Specifying version of dependencies

Gradle uses the same version syntax as Apache Ivy. Please consult: http://ant.apache.org/ivy/history/latest-milestone/ivyfile/dependency.html#revision

Creating a fat jar

For Gradle 0.9 you can use the following code to modify the jar task to create a fat jar containing all class files from libs in your compile dependencies:

If you are working with one of the language plugins, for example you use "apply plugin: 'groovy'" in your build.gradle file, pay attention to the project layout. For a fat jar from Groovy see http://www.gradle.org/groovy_plugin.html#groovylayout and for Java see the corresponding section of: http://www.gradle.org/java_plugin.html . If you don't follow this layout, your fat jar will be much thinner than expected (your project class files will be missing from the jar).

For Gradle 0.8:

Include all runtime dependencies

The above snippet will only include the compile dependencies for that project, not any transitive runtime dependencies. If you also want to merge those, replace configurations.compile with configurations.runtime.

Fetching from protected repository

This is currently not a core functionality of gradle, we therefore have to rely on ivy. If you want to retrieve your dependencies from a password (http basic) protected repository, add the following line to your buildscript:

The realm name is displayed in any browser's password popup but may be also retrieved from the web servers configuration. Be aware that you should not provide the protocol prefix to the hostname (e.g. use google.com instead of http://google.com).

Gathering all dependencies libraries JARs in one folder

For gradle 0.8+

Include project artifacts

The above snippet will only include the dependencies of the project. It does not include the jar produced by the project itself. To include those:
For gradle 0.8+

Graphviz dependency report

tbd.

Using gradle itself as an embedded repository

Gradle contains a growing number of useful libraries as part of the distribution, and at present, there is no built-in way to compile code against these included jars. The short code snippet below provides the desired functionality.

embeddedRepo.gradle

Use is as simple as:

build.gradle

This can be extremely handy for smaller, self-contained projects that really only need access to JUnit or TestNG when trying to compile their unit tests. It has more general use as well, as slf4j-api and several commons libraries are included.

build.gradle

Please keep an eye on JIRA GRADLE-1395 to see when/if it becomes a native feature (and vote for it, if it is something you would like to see included).

This was partially driven as a work around for JIRA GRADLE-1394.

Custom repository structure and its access patterns

Sample repository structure:

Reference to the repository:

build.gradle

This is technically using module artifact and revision (although gradle really wants to utilize organisation, module and revision).
The IVY tags within parens are optional (meaning they only get filled in if they are provided by default).

Usage is then:

build.gradle

One needs to specify the explicit type for an artifact (and artifacts are mostly hidden within gradle and there aren't many good examples of using them). There is no "short-form" specification that utilizes artifact names. (Notice that organization isn't being filled in, since the ':' comes first.)

Using the 3 patterns above this would look in:

One can utilize the recommended pattern, but that means "groovy" is the organization, and "groovy-all" the module. Gradle contains all the resolving power (and more) of IVY, but it tries hard to constrain its use to Maven resolving patterns.

How to refer to multiple artifacts within the same module

Sample repository structure:

When artifacts's naming do not follow a regular pattern, here is a solution:

build.gradle

Gradle does not keep it's mapping based upon artifacts but rather at the module level, so the code below will not work, only the first one is resolved, further ones are ignored:

build.gradle

Building a project with Java / Groovy inter-dependencies

If a project has both Java and Groovy plugins enabled and has dependencies between Java and Groovy classes, the entire project (java and groovy source) can be built as a Groovy project (if there is only a one-way dependency of Groovy on Java, this is not necessary. If the dependency is the other way around, use the commented code below.)


Ant integration

Some tips&tricks on Ant integration not covered by the userguide.

tbd.


Maven2 integration

Some tips&tricks on Maven2 integration not covered by the userguide.

use local Maven2 cache repository

Since 0.9.1 to use artifacts from local Maven2 cache repository do the following:

build.gradle

This will read Maven settings.xml file, if present, to locate the cache.

With earlier versions (0.9 and before) this snippet should work (provided that you keep local repo in default $HOME/.m2/repository):

build.gradle

translate Maven2 dependencies to Gradle dependencies

There is no such functionality (yet). Please take a look at this JIRA link to learn what is the status of this issue. You should also check this blog post by Baruch Sadogursky.


3rd party tools

This section explains how to use various tools (like Cobertura, PMD, Findbugs) from Gradle.

In general, if the tool you intend to use has Ant task, than go for it !

Please notice, that there are some efforts to make 3rd party tools easier accessible from Gradle, so check out this JIRA issue to make sure that no better solution exists.

using Cobertura

There is a plugin available that works out-of-the-box: please see the Plugins page.

For Gradle 0.8 you can follow this example:

build.gradle

As you can see Cobertura Ant Task is used.

Don't forget to tell JUnit/TestNG where the cobertura.ser file is !

TestNG example for Gradle 0.9:

build.gradle

JUnit example:

build.gradle

TestNG example for Gradle 0.8:

build.gradle

using Emma

Please see Plugins page.

using Findbugs

The script below uses Findbugs Ant task. One thing is worth noticing. Because class is a reserved word in Groovy it must be surrounded by quotes: "class".

Of course you need to change values of home and location attributes.

build.gradle

Alternative Findbugs using subproject injection

Thanks to the initial Findbugs cookbook pattern, I was able to generate a more complex version that creates a single ant taskdef that is then utilized by all subprojects (a version that selectively injects this task if and only if there is a jar task for the subproject would be more robust).

Aside from having to put findbugs in a flat-file repository some place there are no values that need to be adjusted. I was toying with adding explicit dependencies upon the missing jars (annotations.jar, asm-3.1.jar, asm-analysis-3.1.jar, asm-commons-3.1.jar, asm-tree-3.1.jar, asm-util-3.1.jar, asm-xml-3.1.jar, bcel.jar, commons-lang-2.4.jar, dom4j-1.6.1.jar, jFormatString.jar, jaxen-1.1.1.jar, jsr305.jar), but haven't done so yet.

At some point I'd like to turn this into a real plugin, but haven't done so yet, and would be glad for someone to clean up and/or simplify this solution.

build.gradle

using PMD

This recipe is based on Mockito build script.

The script below does nothing special - inside "pmd" task it defines new Ant task 'pmd' and then configures it (see
PMD Ant task for explanation). It assumes, that rules are stored in conf/pmd-rules.xml file.

build.gradle

Important You'll encounter problems if you try to use rulesets from the PMD jar (e.g. rulesetfiles:'rulesets/basic.xml'). Please take a look at this JIRA link to learn what is the status of this issue.
Basically you can avoid it, by copying the rulesets you use to some other location, e.g. conf directory of your project. Other, but untested workaround, is presented in this mailing post.
As of 0.9-rc-1 this issue is closed.

using JDepend

The script below uses JDepend Ant task.

build.gradle

using JavaNCSS

The script below uses JavaNCSS Ant task.

build.gradle

using Checkstyle

Gradle has Checkstyle support built in, using the Code Quality Plugin. By default, the checkstyle tasks will look for a Checkstyle configuration file at $projectDir/config/checkstyle/checkstyle.xml. You can change the location as follows:

build.gradle

In order to create an HTML report of the checkstyle report, use an Ant xslt task:

build.gradle

using AspectJ

For Gradle 0.9
Please see Plugins page.

using Clover

To use this plugin, cut and paste this code into a file named "clover.gradle". In your build.gradle, put:

Use the -PwithClover command line parameter to enable code coverage (e.g. "gradle -PwithClover")

using Eclipse JDT Core Batch Compiler (ECJ)

Because the Ant javac property compilerClasspath is not accessible directly in the CompileJava class, the ECJ compiler needs to be injected directly into the Ant classloader.

For Gradle 0.9-rc-1 you can follow this example:

build.gradle

Make sure to put the ecj.jar in a repository defined in a repository{} block.

 

For 1.0-milestone-8a and later, try gradle-ecj plugin. (`CompileOptions.compiler` has been deprecated in Gradle-milestone-8a and will be removed in the future)

 


CI servers

"Can I use Gradle with my continuous integration server ?" Oh yes, you can ! See below. (smile)

Please see this discussion: http://gradle.1045684.n5.nabble.com/Current-state-of-Gradle-amp-lt-insert-CI-server-here-gt-td3301572.html

Hudson / Jenkins

There is a plugin for Hudson created by Gregory Boissinot. For details see http://wiki.hudson-ci.org/display/HUDSON/Gradle+Plugin

Rene Groeschke has "added some pages about gradle integration on hudson to the OpenSource HudsonCI Book free available at" http://www.wakaleo.com/download-ci-with-hudson

Team City

Full-fledged Gradle support.

Bamboo

tbd.


IDEs

Here you will find information on running Gradle build scripts with your favourite IDE, getting syntax highlighting etc.

Eclipse

Please see http://docs.codehaus.org/display/GRADLE/Running+Gradle+from+Eclipse

Excluding dependencies from Eclipse Projects

Please see IntelliJ IDEA solution

Intellij IDEA

Refer to the Gradle User Giude Chapter 37. The IDEA Plugin
and also http://kensipe.blogspot.com/2009/12/intellij-9-and-gradle.html, http://old.nabble.com/Gradle-from-IntelliJ-td28019991.html#a28019991 and search the user mailing list

If you want deeper integration - dependencies graphs, auto-completion, syntax checks, intentions, etc. please vote on the corresponding YouTrack issue

Excluding dependencies from IDEA modules

Gradle uses different dependencies model for IDEA modules, so excluding dependencies from regular Gradle scopes won't exclude them from IDEA modules. So, until JIRA issue is fixed, that's the way to exclude dependencies from IDEA modules:

Same is true for Eclipse .classpath

Netbeans

tbd.
From mailing list it seems as if Netbeans support is postponed until many people request it.

Vim syntax highlighting

Edit file ~/.vim/filetype.vim (it might not even exist)
add line
au BufNewFile,BufRead *.gradle setf groovy
now Groovy syntax highlighting will be used for all *.gradle files.


command line

Not happy with the default command line features of Gradle ? You will find some more hints here.

bash completion

This recipe was tested on Kubuntu Linux 9.04 but should work for other *nix-es as well (check bash completion documentation for you beloved distro if it doesn't).

Under *nix operating systems you can have bash autocompletion for Gradle. Of course, it will work only for the predefined tasks - bash knows nothing about the tasks you create in your build scripts.

The idea is to put the file presented below to the /etc/bash_completion.d directory (you'll need sudo to do that). Put the tasks that you use most often (or all the tasks you can think of - it is up to you) in the tasks='x y z' line and voila ! Now type
gradle clTAB tTAB
and it will be autocompleted to
gradle clean test.
Sweet, isn't it ?

P.S. don't forget to execute source /etc/bash_completion.d/gradle after you make changes to this file.

P.S. this trick is somehow obsolete because Gradle has a powerful feature of recognizing tags by abbreviations (see userguide), but some old-schools like myself may find it useful

/etc/bash_completion.d/gradle

aliases

It is rather obvious, but maybe you forgot, that your lovely *nix allows you to create aliases, which allows you to easily execute commands with minimal amount of typing. Works best for often used commands, of course. So, update your .bash_aliases file (check your distro documentation) with any gradle specific staff, like this (below some examples, but probably not very interesting, I was in hurry writing them, you know):

.bash_aliases

testing

Are you test-infected ?

running single tests

As of 0.9, here's the simplest example:

Many more options are available, including pattern matching, subproject includes, and integration test separation. The documentation hasn't been updated as of this writing, but see the JIRA issue comments for full details in the meantime.

See also this blog post: http://www.practicalgradle.org/blog/2011/01/convenient-test-execution-with-camel-case-support/

TestNG

add listeners

build.gradle

If you want to disable the default listeners add this to options:

add reporters

Based on ReportNG (https://reportng.dev.java.net/) example. Please notice that there was a problem with previous versions of ReportNG (see this JIRA issue).

build.gradle

TestNG and JUnit together

To run tests used in TestNG and JUnit you need to add the second test task. Than you can for example add it to check task and use by running gradle check.

build.gradle

easyb

Since Gradle can make use of Ant tasks relatively easily, using easyb in a Gradle build is straightforward. First, add a dependency on easyb to the build, then use the easyb Ant task. The example below adds easyb testing to the Java "check" task, but it would be easy to create a separate Gradle task as well:

build.gradle

For more details, see Running easyb stories in a Gradle build at the Agile ICE blog.

running various types of tests separately

If you want to execute few kinds of tests separately (e.g. unit tests and integration tests) you can do the following:

build.gradle

how to run tests from a JAR library

If you have a library (JAR file) with tests that you would like to run, you need to unzip the JAR into a temporary directory and then point the test task at the temporary directory.

Please watch this JIRA issue

using Checkstyle

Gradle 0.8 has Checkstyle support built in. By default, the checkstyle tasks will look for a Checkstyle configuration file at $projectDir/config/checkstyle/checkstyle.xml. You can change the location as follows:

build.gradleusePlugin 'code-quality'

checkstyleConfigFileName = 'conf/sun_checks.xml'


multi-project builds

Please make sure that you read the user guide section on multi-project builds. Also studying of some real life examples (build.gradle of Hibernate or Gradle itself) can help you to learn a lot about multi-project builds.

I have many subprojects and would like to do something with a subset of them

A bunch of typical problems here, like: "I want to apply Java plugin only to those subprojects that do have some code".

This features is described in "Filtering by name" subsection of user guide, but was asked few times on mailing list, so I put it here.

The solution is to define a subset of subprojects and configure this subset, e.g.

build.gradle

how to aggregate javadocs

(solution copied from Adam Murdoch's email: http://gradle.1045684.n5.nabble.com/aggregating-javadocs-td1433469.html#a1433469)

build.gradle

source sets

Source sets are a powerful concept. Alas, they are somewhat intimidating when you meet them for the first time. (wink)

how to exclude some files from source set

(based on this post: http://gradle.1045684.n5.nabble.com/Exclude-some-java-classes-packages-from-compilation-sourceSets-td3277622.html)

build.gradle

The trick is to realize that source sets are FileTrees (see section on File Trees in userguide and take a look at javadocs of FileTree, ConfigurableFileTree and PatternFilterable interfaces) so you can do pretty much everything with them.

Chapter 37. The IDEA Plugin

Labels
  • None
  1. Jun 09, 2010

    I propose not to hold back until you earn big sum of money to buy different goods! You should just get the home loans or just financial loan and feel yourself fine

  2. Apr 14, 2011

    There is an example of a groovy clover plugin available - https://github.com/grails/inconsequential/blob/master/clover.gradle