Gradle Build Automation Handbook PDF
Gradle Build Automation Handbook PDF
ii
Contents
1.1
What is Gradle ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
1.3
Downloading Gradle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4
1.5
1.6
1.7
1.8
1.8.1
Default Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.8.2
Task Dependency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.8.3
Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1
2.2
What do we need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3
2.3.1
1.9
2.4
System Properties
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Project Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.4.1
2.4.2
2.4.3
2.4.4
2.5
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.6
iii
17
Gradle Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.1.2
Dependency Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.1.3
3.2
What do we need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3
Environment Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3.1
Gradles Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3.2
3.3.3
3.4
3.5
3.6
3.6.2
3.7
3.8
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.9
31
4.2
What do We Need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3
Environment Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.4
4.5
4.6
SourceSets Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.7
4.8
4.9
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
42
Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.2
What do We Need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.3
Environment Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
iv
5.4
5.5
5.6
Gradle Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.7
5.8
5.9
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
54
6.1
6.2
6.3
Environment Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.4
6.5
6.6
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.7
57
7.1
7.2
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
7.3
7.4
7.5
7.6
7.7
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
7.8
64
8.1
8.2
8.3
Environment Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
8.4
8.5
8.6
Running Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
8.7
8.8
Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
8.9
vi
Preface
Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces
a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven of declaring the project
configuration. Gradle uses a directed acyclic graph ("DAG") to determine the order in which tasks can be run.
Gradle was designed for multi-project builds which can grow to be quite large, and supports incremental builds by intelligently
determining which parts of the build tree are up-to-date, so that any task dependent upon those parts will not need to be reexecuted. The initial plugins are primarily focused around Java, Groovy and Scala development and deployment, but more
languages and project workflows are on the roadmap. (Source: https://en.wikipedia.org/wiki/Gradle)
In this ebook, we provide a compilation of Gradle examples that will help you kick-start your own projects. We cover a wide
range of topics, from installation and configuration, to how to use various plugins and how to integrate Gradle with 3rd party
tools. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time.
vii
1 / 70
Chapter 1
1.1
What is Gradle ?
Gradle is a build and automation tool, that can automate our building, testing, deploying tasks and many more. Gradle is the next
generation build system for Java technologies that includes some advantages from older tools like ant or maven. Lets have a
look:
Allows declarative and expressive domain-specific-language (DSL). This is a powerful concept because it allows us to write a
custom language that is more friendly than Java.
Is Groovy-based. This means that your configuration is made in Groovy statements instead of xml blocks, making it very easy
to define the tasks to be performed.
Supports legacy scripts in Ant or Maven, and has full support to Ivy repository infrastructure.
Its designed to take advantage of convention over configuration.
Works on non-java projects too.
Easily customizable and scalable.
1.2
Today, we work on large projects that need automated release process to mitigate risks and failures; a building system as Gradle,
permits you to structure a process from the compilation to the deployment in your application server. This approach has several
advantages, like spending time on more important tasks for our project (like modeling and coding features) and delegating
repetitive tasks to Gradle, or also the use of Groovy dynamic language scripts (DSL) instead of too long xml files.
If you want to do continuous delivery and make your release process automatic, Gradle is a nice tool to carry out these goals.
1.3
Downloading Gradle
At time of this tutorial, Gradle is in your 2.3 version. You can download from here.
We need a JDK 1.6 before installing Gradle, if you dont have, you can download from here.
2 / 70
So, unzip the file in any directory that you choose, in this example we set Gradle in C:/Desarrollo/Lib/gradle-2.3.
1.4
Then, we have to set enviroment variables to get a full access to Gradle, so create the GRADLE_HOME variable that point to
the earlier directory that you set.
Note: The screenshots shown here are taken from Windows 8. Your version of Windows may vary.
3 / 70
4 / 70
1.5
2.3.9
Apache Ant(TM) version 1.9.3 compiled on December 23 2013
1.7.0_67 (Oracle Corporation 24.65-b04)
Windows 8.1 6.3 amd64
The Gradles starting point is the build.gradle file. Any task or project starts with this script. With the default naming
convention, this file is called, but we can define any name to our build gradle scripts.
In the example, the first task of gradle is called helloWorld, with using Groovy language we call the Javas method System.
out.println with the Groovys shorter equivalent println to print a short message in console.
5 / 70
build.gradle
task helloWorld << {
println Welcome to JCG Gradle Tutorial
}
To execute the build script, go to the directory where you saved the file and execute the task, running this command:
gradle helloWorld, this will be the output.
E:\JavaCodeGeeks JCG\Gradle Tutorial>gradle helloWorld
:helloWorld
Welcome to JCG Gradle Tutorial
BUILD SUCCESSFUL
Total time: 1.838 secs
1.6
As any Java based tool, Gradle can set JVM Options to manage the memory space and another stuff. We can use the environment
variables GRADLE_OPTS or JAVA_OPTS, this configuration prevents an OutOfMemoryError setting stable values. For
example, we can set the maximum memory allocation pool adding the value -Xmx512m in the GRADLE_OPTS variable.
1.7
In Gradle we have 2 top concepts, that are Projects and Tasks. Any Gradle script is made up of one or more projects, and every
project is made up of one or more tasks.
A Gradle project is any goal what we want to do with Gradle, assemble a JAR, compile a Java project, run Unit tests, deploy
an application.
A Gradle task is the minimum unit of work, represents an atomic piece of work. The main goal is define some tasks to
accomplish a Project.
In our first basic task helloWorld we can see what happens:
When you execute the Gradle helloWorld, Gradle will lookup a task with that name in the default build script build.gradle. If
Gradle finds the task, it executes the code with the Groovy engine .
Every line of code (LOC) between the braces composes the task
The double << , is the shorthand to define a Gradle task, the longhand is thus:
task helloWorld {
doLast {
println Welcome to JCG Gradle Tutorial
}
}
Yes, the double << is the short form to define the doLast tasks block. We suggest you to use the shorthand way.
Gradle has basic commands that help us to write a more readable and clean code or scripts. Every command have to the shorthand
and longhand way to run them.
--help or -h : Prints out the helper messages.
--info or -i : Set the logger level to INFO, this level prints a high level of information.
6 / 70
--debug or -d : Set the Gradle logger level to DEBUG, this is useful for troubleshooting build problems.
--quiet or -q : Only shows the error messages.
tasks : Show all availables tasks in the current build script, also displayed the tasks defined by the plugin.
--gui : Launches the Gradle GUI.
1.8
7 / 70
In this post we have only worked with the most basic concept tasks, but can we do more than just print some text on the screen?
If we execute the command Gradle tasks, we get the following output:
E:\JavaCodeGeeks JCG\Gradle Tutorial>gradle tasks -q
****************************************
All tasks runnable from root project
****************************************
Build Setup tasks
************
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]
Help tasks
*******
components - Displays the components produced by root project Gradle Tutorial. [ incubating]
dependencies - Displays all dependencies declared in root project Gradle Tutorial.
dependencyInsight - Displays the insight into a specific dependency in root project Gradle Tutorial.
help - Displays a help message.
projects - Displays the sub-projects of root project Gradle Tutorial.
properties - Displays the properties of root project Gradle Tutorial.
tasks - Displays the tasks runnable from root project Gradle Tutorial.
Other tasks
*******helloWorld
To see all tasks and more detail, run gradle tasks --all
To see more detail about a task, run gradle help --task
Displays the list of tasks that we do, including default tasks and in other tasks that we define. So, Gradle is like an agent that
perform tasks to carry out the projects that we model.
1.8.1
Default Tasks
Another important concept is the Default Tasks, which are the tasks that run if no task name indicated. Modify the build.gradle
script like this:
defaultTasks beforHelloWorld
task helloWorld << {
println Welcome to JCG Gradle Tutorial
}
task beforHelloWorld << {
println Setting the previous configuration...
}
8 / 70
BUILD SUCCESSFUL
Total time: 2.685 secs
1.8.2
Task Dependency
The biggest basic concept that we cover in this tutorial is task dependency. What does that mean? Gradle adds prevalence on
execution of dependency-on task instead of the task that depends on it. Modify the build.gradle file as follows:
defaultTasks beforHelloWorld
task helloWorld << {
println Welcome to JCG Gradle Tutorial
}
task beforHelloWorld (dependsOn:helloWorld) << {
println Setting the previous configuration...
}
1.8.3
The last basic and useful tip about Gradle tasks, is the abbreviated calling.
In Gradle, if our tasks name is so long, we dont need to write the complete name to execute them, only specifying the initials in
a camelCase format can execute the tasks.
If we run gradle -q hW the output will be:
E:\JavaCodeGeeks JCG\Gradle Tutorial>gradle -q hW
Welcome to JCG Gradle Tutorial
Gradle using regular expressions matches the name of task (helloWorld) and execute it.
1.9
Conclusions
Gradle combining the capabilities of earlier build tools such as Ant and Maven allows you to create flexible and maintainable
scripts that are interoperable with Java-based technologies.
The most important concept are the tasks, they are the unit of work in Gradle.
With predefined tasks we dont need to make everything by hand.
Gradle is a user-friendly framework, which can be adopted very quickly compared to its predecessors.
1.10
Download
You can download the full source code of this example here: GradleHelloWorldTutorial
9 / 70
Chapter 2
2.1
As developers, we provide high-quality code that is scalable and easy to read; Gradles properties allow us to perform these tasks,
in addition to some cases optimize the compilation and execution of them.
2.2
What do we need?
As described in the previous example (Gradle Hello World Tutorial), we need Gradle fully functional. Please review the part of
the installation and then continue with this example.
2.3
In Gradle there are two types of properties, System properties and Project properties. The first of them, are
properties used to configure the JVM that supports the execution of the builds, and the second type are for parameterizing
variables in our projects, like names, paths, and other useful approaches.
2.3.1
System Properties
We can set these properties via environment variables, setting the GRADLE_OPTS or JAVA_OPTS values to manage, for example the Java home, Heap and PermGem Spaces, or Gradle daemon activation.
Then, go to the environment variables in windows users, and set the GRADLE_OPTS variable with the value -Dorg.gradle.
daemon=true.
10 / 70
11 / 70
12 / 70
2.4
2.4.1
13 / 70
Project Properties
Gradles Properties, hello!
Gradle offers a wide list of default properties for the current build, we can print all running this simple command in the console:
gradle properties. This is equivalent to the Properties in the Gradle "Hello World" Example.
E:\JavaCodeGeeks JCG\Gradle Properties Tutorial>gradle properties
:properties
****************************************
Root project
****************************************
allprojects: [root project Gradle Properties Tutorial]
ant: org.gradle.api.internal.project.DefaultAntBuilder@33666fbb
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@7e10
cc38
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorate
d@4065a018
asDynamicObject: org.gradle.api.internal.ExtensibleDynamicObject@7ff37476
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderS
cope@68a2866d
beforHelloWorld: task :beforHelloWorld
buildDir: E:\JavaCodeGeeks JCG\Gradle Properties Tutorial\build
buildFile: E:\JavaCodeGeeks JCG\Gradle Properties Tutorial\build.gradle
buildScriptSource: org.gradle.groovy.scripts.UriScriptSource@608a1b4e
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@65037d6
3
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope
@5ba0df26
components: []
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurati
onActionContainer@57628c1c
configurations: []
convention: org.gradle.api.internal.plugins.DefaultConvention@18740ad1
defaultTasks: [beforHelloWorld]
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependen
cyHandler_Decorated@3f5aa04b
depth: 0
description: null
ext: org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@2b90cc9
extensions: org.gradle.api.internal.plugins.DefaultConvention@18740ad1
fileOperations: org.gradle.api.internal.file.DefaultFileOperations@5a6bc081
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@3e3155a8
gradle: build Gradle Properties Tutorial
group:
helloWorld: task :helloWorld
inheritedScope: org.gradle.api.internal.ExtensibleDynamicObject$InheritedDynamic
Object@247eb222
logger: org.gradle.api.logging.Logging$LoggerImpl@767c9c02
logging: org.gradle.logging.internal.DefaultLoggingManager@6aed5294
modelRegistry: org.gradle.model.internal.registry.DefaultModelRegistry@49d7572c
module: org.gradle.api.internal.artifacts.ProjectBackedModule@556edb6b
name: Gradle Properties Tutorial
parent: null
parentIdentifier: null
path: :
pluginManager: org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@26
1bf0a0
plugins: [org.gradle.api.plugins.HelpTasksPlugin@751f265a]
processOperations: org.gradle.api.internal.file.DefaultFileOperations@5a6bc081
project: root project Gradle Properties Tutorial
projectDir: E:\JavaCodeGeeks JCG\Gradle Properties Tutorial
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@703
91e42
projectRegistry: org.gradle.api.internal.project.DefaultProjectRegistry@600e7a58
properties: {...}
repositories: []
resources: org.gradle.api.internal.resources.DefaultResourceHandler@3e4eede1
rootDir: E:\JavaCodeGeeks JCG\Gradle Properties Tutorial
rootProject: root project Gradle Properties Tutorial
scriptHandlerFactory: org.gradle.api.internal.initialization.DefaultScriptHandle
rFactory@6867946a
scriptPluginFactory: org.gradle.configuration.DefaultScriptPluginFactory@579ab80
1
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$
5@40f76015
services: ProjectScopeServices
standardOutputCapture: org.gradle.logging.internal.DefaultLoggingManager@6aed529
4
state: project state EXECUTED
status: release
subprojects: []
tasks: [task :beforHelloWorld, task :helloWorld, task :properties]
version: unspecified
BUILD SUCCESSFUL
Total time: 0.958 secs
These are a lot of properties, we only want to know how to read the default project properties.
2.4.2
If we want to add our custom properties, we have to define them in a build script with the ext{} block.
ext{
myFirstProperty = myCustomPropertyValue
}
task showPropertiesTask << {
println myFirstProperty
}
14 / 70
2.4.3
15 / 70
Instead of setting the properties in a build script (thats not a good practice, the best approach is a properties file), we can use the
-P command-line option to add any custom property.
Then, the build script has a task that prints the value of two properties.
task showPropertiesTask << {
println "Version: $version"
println "Custom property: $customProperty"
}
Running the script with this command gradle -Pversion=2.3.3 -PcustomProperty=myCustomValue showP
ropertiesTask, we get the following output.
E:\JavaCodeGeeks JCG\Gradle Properties Tutorial>gradle -Pversion=2.3.3 -PcustomProperty= myCustomValue showPropertiesTask
:showPropertiesTask
Version: 2.3.3
Custom property: myCustomValue
BUILD SUCCESSFUL
Total time: 2.67 secs
2.4.4
So, we look at the optimal way to set our project properties, through an external file. The file needs to be named gradle.
properties and it should be a plain text file with the name of the property and its value in the same line.
We now create a gradle.properties file in the same directory of our build.gradle file, with the following contents:
gradle.properties
version = 3.0
customProperty = This value is obtained from gradle.properties
We use our previous build script to show the properties, after running the gradle script we get the following output:
E:\JavaCodeGeeks JCG\Gradle Properties Tutorial>gradle showPropertiesTask
:showPropertiesTask
Version: 3.0
Custom property: This value is obtained from gradle.properties
BUILD SUCCESSFUL
Total time: 0.943 secs
A useful concept, is the main Gradle directory. If we put the gradle.properties there, these properties take precedence over those
that are in the project. In windows this directory is $USER_HOME/.gradle.
16 / 70
Then, we add another gradle.properties file in this directory and run the gradle build, we get the following output.
E:\JavaCodeGeeks JCG\Gradle Properties Tutorial>gradle showPropertiesTask
:showPropertiesTask
Version: 4.0
Custom property: This value is obtained from gradle.properties in user home
BUILD SUCCESSFUL
Total time: 1.45 secs
2.5
Key Points
2.6
Download
You can download the full source code of this example here: Gradle Configuration Properties Tutorial
17 / 70
Chapter 3
3.1
GWT is the Googles Toolkit to develop ajax applications using the Java language, these applications like Java EEs Applications
need a server, but, in this case, is a lightweight web server like Jetty to make them run. So, and why I need Gradle here? Gradle
facilitates and improves the build process with the automatization of the tasks and allowing the applications uncoupling of an
IDE, making your release cycle easier!
Before we start with this example, we will cover some essentials topics about Gradle.
3.1.1
Gradle Plugins
Gradle as a build tool offers a set of basic tasks to perform simple compilations, such as wars generation, copying files and
creating directories, but in more complex projects like GWT we need to add some plugins to execute advanced tasks. With
adding this line at the top of your gradle build script, you are able to use another task.
apply plugin:PLUGIN_NAME
For this example, we need to apply various plugins like war, java and eclipse plugins; with them we can execute this tasks:
compileJava: Compile Java Source files using javac.
classes: Assembles the production classes directory.
jar: Assembles the JAR file.
war: Generates a war file with all the compiled classes.
eclipse: Generates all Eclipse files.
3.1.2
Dependency Management
This is a Gradles critical feature with a main purpose, to centralize and automate management of libraries dependency, people
thinks that dependency management is only an automated fetching of dependencies from a remote source, but this feature wants
more like to includes automatically fetching dependencies, detecting transitive dependency conflicts, and so on. For this example,
we work declaring dependencies via DSL.
dependencies {
compile com.google.gwt:gwt-user:2.7.0
}
3.1.3
18 / 70
This is a key point from the Java Plugin, a source set is a collection of source files which are compiled together. But for this
example we need to know that for this Java Plugin, source sets has a default configuration to works:
Java source code directory: src/main/java
Production resources: src/main/resources
Test sources: src/test/java
Test resources: src/test/resources
3.2
What do we need?
3.3
3.3.1
Environment Configuration
Gradles Installation
Start, with downloading the Gradle 2.3 version and setting environment variables correctly thus:
19 / 70
3.3.2
In the Eclipse Marketplace just type: Eclipse Integration and install the plugin that matches with your Eclipse version (for this
example 4.4).
20 / 70
21 / 70
To install the GWT Plugin you have to go Help > Install New Software, then add this site https://dl.google.com/
eclipse/plugin/4.4
3.3.3
Finally, download GWT 2.7 distribution and unzip in some directory, then set as the default GWT SDK in Eclipse. Go to the
Menu, Window > Preferences > Google > Web Toolkit, so add your GWT specifying the unzip location
22 / 70
3.4
To start, we need to have already installed the GWT plugin in Eclipse. Then, using the Eclipse Wizard we will create a Google
Web Application Project
23 / 70
24 / 70
3.5
To continue, we have to create the main file, Gradle Build Script, so, make a new File called build.gradle in the root of the
project.
3.6
25 / 70
build.gradle
apply
apply
apply
apply
apply
plugin:
plugin:
plugin:
plugin:
plugin:
war
java
gwt
eclipse
jetty
26 / 70
3.6.1
The first step is apply the plugins and set GWT Project dependencies to provide all the necessary libs and tasks to make the Build
and Deployment.
apply plugin:war, basic plugin that adds assembling war tasks; it provides the main task War, that assembles the file
itself.
apply plugin:java, is the basis from other plugins and provides the capabilities to build and test the projects.
apply plugin:gwt, this plugin is provided by the declared dependency in line 19. This plugin facilitates the assembly
process of gwt-war, if we dont use them, we would have to do the process of making directories, copy files, compile java files,
etc.
apply plugin:eclipse, this plugin provides configuration tasks to the eclipse project, is useful if you want to do a
full synchronization between the Gradle generated files and the Eclipse Project.
apply plugin:jetty, with this plugin we can deploy the war directly with no need run configuration in Eclipse.
The BuildScript block, this concept is used to define the external dependencies that are available to the classloader during
the execution of Gradle build script. In the declaration of dependencies only be used the method classpath, and you cant use
the configurations compile , runtime, testCompile, etc. because this block is just to declare external libraries references
available to the classpath, if you need to provide any configuration like compile or runtime you need to do outside of
BuildScript block.
The repositories block (line 23), indicates where Gradle looks for any required dependency, in this case in the Maven
central repository. For this example get gwt libraries and automatically fetch gwt dependencies; while the script is executing
some lines like these appears in the console.
Download https://jcenter.bintray.com/de/richsource/gradle/plugins/gwt-gradle-plugin/0.6/gwt -gradle-plugin-0.6.pom
Download https://jcenter.bintray.com/de/richsource/gradle/plugins/gwt-gradle-plugin/0.6/gwt -gradle-plugin-0.6.jar
Download https://repo1.maven.org/maven2/com/google/gwt/gwt-codeserver/2.7.0/gwt-codeserver -2.7.0.pom
Download https://repo1.maven.org/maven2/com/google/gwt/gwt-codeserver/2.7.0/gwt-codeserver -2.7.0.jar
3.6.2
The Main goal of this post is to understand how to integrate Gradle with GWT, and in this part is the key.
In the line 27 set the incremental compilation of java files, why do use this? If your GWT project its so large, indicates to Gradle
exactly which input files were out of date compared to a previous execution and only compile those files, improving the compile
performance.
The GWT task defined in line 32, is the main method of the build script, in here we need to define the GWT version that are we using, for this example is 2.7.0 distribution. In line 35, we need to set the name of the GWT Module, how we find them? Its simple
27 / 70
are composed by the package + name of the module in the gwt.xml file, then is com.javacodegeeks.gradle.gwt.integration.build.
+ GradleGWTIntegrationExampleJCG , look the name in the line 8.
<?xml version="1.0" encoding="UTF-8"?>
<!-When updating your version of GWT, you should also update this DTD reference,
so that your app can take advantage of the latest GWT module capabilities.
-->
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.7.0//EN"
"https://gwtproject.org/doctype/2.7.0/gwt-module.dtd">
<module rename-to=gradlegwtintegrationexamplejcg>
<!-- Inherit the core Web Toolkit stuff.
-->
<inherits name=com.google.gwt.user.User/>
<!-- Inherit the default GWT style sheet. You can change
-->
<!-- the theme of your GWT application by uncommenting
-->
<!-- any one of the following lines.
-->
<inherits name=com.google.gwt.user.theme.clean.Clean/>
<!-- <inherits name=com.google.gwt.user.theme.standard.Standard/> -->
<!-- <inherits name=com.google.gwt.user.theme.chrome.Chrome/> -->
<!-- <inherits name=com.google.gwt.user.theme.dark.Dark/>
-->
<!-- Other module inherits
-->
-->
The SourceSets in line 37, are an important part, because here we define the custom directories where are the classes, but we
do this, Gradle look for classes in the default directory which is src/main/java.
The logLevel property set the error level to print on the console; minHeapSize and maxHeapSize set the space of Java
Heap, like an jvm args, would do.
The addGwtContainer sets if GWT_CONTAINER should be added to the eclipse classpath instead of using the Gradle
dependencies, making dependency with GPE (GWT Plugin Eclipse) if is set to true, for this we prefer to set false.
For last property httpPort in line 60, allows us to customize deployment port.
The jettyDraftWar tasks will be used if you want to run in a draft mode, with a no production quality version. This task is
a type of JettyRunWar, i.e. extending and inherits its properties.
3.7
Open a command shell on the root of the GWT Project, where is the Gradle build script.
28 / 70
29 / 70
3.8
Key Points
Tips
You have to distinguish the difference between buildScript block and repositories and dependencies blocks, these are configuration items, that we use to set the classpath external libraries, URL Repositories and set the dependencies with other
libraries.
The use of SourceSets to set the custom directory of Java sources. The default directory in where Gradle search sources is
src/main/java.
The dependency of Gradle-Gwt-Plugin developed by Steffen Schaeffer, that provides all GWT compilation Gradle tasks and
make so easier the Gradle GWT Integration.
If you want to make Eclipse Project and GPE compatible, you have to set addGwtContainer to true and update the classpath
settings in eclipse, its likely to get some errors in Eclipse GWT Project.
When we run the task compileGWT, the generated resources (cache, draftOut, extra, gen, out, work) are allocated in root_
project/build/gwt/ directory.
30 / 70
3.9
Download
You can download the full source code of this example here: Gradle GWT Integration Example
31 / 70
Chapter 4
4.1
4.1.1
A SourceSet is a collection of java source files and additional resource files that are compiled and assembled together to be
executed. The main idea of sourcesets is to group files with a common meaning for the project, with no need of separate them in
another project.
4.2
What do We Need?
4.3
Environment Configuration
Please set your Gradle environment variables and install the Gradle plugin on your IDE. To avoid to be boilerplate visit this
previous posts that show how to configure your Gradle Environment. Gradle Hello World Tutorial & Gradle GWT Integration
Example
4.4
32 / 70
33 / 70
4.5
34 / 70
testCompile sourceSets.api.output
testCompile sourceSets.impl.output
runtime configurations.apiRuntime
runtime configurations.implRuntime
}
sourceSets.all { set ->
def jarTask = task("${set.name}Jar", type: Jar) {
baseName = baseName + "-$set.name"
from set.output
}
artifacts {
archives jarTask
}
}
sourceSets {
api
impl
}
jar {
from sourceSets.api.output
from sourceSets.impl.output
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: uri("${buildDir}/repo"))
addFilter("main") { artifact, file -> artifact.name == project.name }
["api", "impl"].each { type ->
addFilter(type) { artifact, file -> artifact.name.endsWith("-$type") }
// We now have to map our configurations to the correct maven scope for
each pom
["compile", "runtime"].each { scope ->
configuration = configurations[type + scope.capitalize()]
["main", type].each { pomName ->
pom(pomName).scopeMappings.addMapping 1, configuration, scope
}
}
}
}
}
}
So, this script has a some tasks configurations, take a look to each:
First we apply java and maven plugins to use the tasks defined in them. See apply plugin reference.
The maven repository is referenced to download the libraries with which there are dependencies to compile and run. See
repositories and dependencies reference.
Then, dynamically its defined for each SourceSet a jar assembly task. In the 25 line, we define 2 tasks, called apiJar
and implJar that both are Jar type and what they do is to assemble the jar with the classes contained for the SourceSets.
In the line 35 we define the new SourceSets, api and impl, that are contained in the src folder, in next steps we see how to
set a custom location.
35 / 70
The Jar method in line 40 set the sources that are assembled in the Jar, in this case get all sources from api and impl SourceSets.
If we take a look at line 27, for apiJar and implJar tasks, those only has api sources or impl sources but no both, so if them have
dependency will occurs compilation or runtime errors using the Jar.
Last method uploadArchives will deploy this jar file to a remote Maven repository. For this example we can delete this.
4.6
SourceSets Properties
Foremost we will add a task to see all the properties of SourceSets, please add it to the end of the script.
task sourceSetProperties << {
sourceSets {
main {
println
println
println
println
println
println
println
println
println
}
}
}
"java.srcDirs = ${java.srcDirs}"
"resources.srcDirs = ${resources.srcDirs}"
"java.files = ${java.files.name}"
"allJava.files = ${allJava.files.name}"
"resources.files = ${resources.files.name}"
"allSource.files = ${allSource.files.name}"
"output.classesDir = ${output.classesDir}"
"output.resourcesDir = ${output.resourcesDir}"
"output.files = ${output.files}"
In this tasks we point to the main SourceSet thats set by default. So, then run the task with the command gradle sSP (brief
invocation) and will see this output:
C:\Users\Andres\workspaceLuna\GradleSourceSetProject>gradle sSP
:sourceSetProperties
java.srcDirs = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\src\main\ja
va]
resources.srcDirs = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\src\ma
in\resources]
java.files = []
allJava.files = []
resources.files = []
allSource.files = []
output.classesDir = C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\c
lasses\main
output.resourcesDir = C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build
\resources\main
output.files = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\class
es\main, C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\resources\ma
in]
BUILD SUCCESSFUL
Total time: 1.169 secs
The result is, all files properties are empty because the directories point to the default values src/main/java. So to make
this properties works we can set this task to impl or api SourceSets, or also we can set any as the main SourceSet. If we change
main for impl in 3rd line and run again the task we will see this output.
C:\Users\Andres\workspaceLuna\GradleSourceSetProject>gradle sSP
:sourceSetProperties
java.srcDirs = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\src\impl\ja
va]
resources.srcDirs = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\src\im
36 / 70
pl\resources]
java.files = [DoublerImpl.java]
allJava.files = [DoublerImpl.java]
resources.files = []
allSource.files = [DoublerImpl.java]
output.classesDir = C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\c
lasses\impl
output.resourcesDir = C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build
\resources\impl
output.files = [C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\class
es\impl, C:\Users\Andres\workspaceLuna\GradleSourceSetProject\build\resources\im
pl]
BUILD SUCCESSFUL
Total time: 1.265 secs
We have 3 directories for the main SourceSet, and both classes are contained.
4.7
So if we want to package the output classes in a new JAR file, its simple we must define a task of Jar type and set a key
sentence from sourceSet.output. In previous steps we already define them, look at 25 line or Jar configuration in line
40. So if we run the inital dinamic tasks gradle apiJar and gradle implJar, Gradle will generate a JAR with the output sources in
the directories defined for the task.
C:\Users\Andres\workspaceLuna\GradleSourceSetProject>gradle apiJar
:compileApiJava UP-TO-DATE
:processApiResources UP-TO-DATE
:apiClasses UP-TO-DATE
37 / 70
:apiJar UP-TO-DATE
BUILD SUCCESSFUL
Total time: 0.997 secs
Gradle automatically will create 3 new tasks based on any new SourceSet added to the project, apiClasses, compileApiJava, and
processApiResources for this case, but in other case change api for sourcesets name. These tasks have a dependency between
them, so what they do in 3 steps is to compile the java files, process resources and assemble the jar copying all the files to it,
keeping the project structure.
Then, we assemble the three possible Jar files, so:
gradle apiJar , only contains api output sources
gradle impJar, only contains api output sources.
gradle Jar, contains all output project sources.
So refresh the project and take a look in the build/libs directory.
38 / 70
4.8
39 / 70
So if we want to generate the Javadoc documentation, we must use the javadoc task. This tasks seeks by default the main
SourceSet, but with the property sourceSets.<sourceSet>.allJava we can add another custom SourceSet. Next, add
this task to the build script and we can run the command gradle javadoc; the generated documentation is allocated into build/
docs/javadoc.
javadoc {
// but the main sourceset contains both api & impl sourceset, javadoc will generate all documentation
source sourceSets.api.allJava
}
C:\Users\Andres\workspaceLuna\GradleSourceSetProject>gradle javadoc
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:javadoc UP-TO-DATE
BUILD SUCCESSFUL
Total time: 1.321 secs
4.9
Testing
So for run the Unit test classes contained in the test SourceSet, we need to add this configuration to the test Task to view the
result of execution.
test {
// Print in console the result of test
afterTest { test, result ->
println "Executing test ${test.name} [${test.className}] with result: ${ result.resultType}"
}
}
4.10
40 / 70
41 / 70
}
// Compile, Test and Run dependencies
dependencies {
apiCompile 'commons-codec:commons-codec:1.5'
implCompile sourceSets.api.output
implCompile 'commons-lang:commons-lang:2.6'
testCompile 'junit:junit:4.9'
testCompile sourceSets.api.output
testCompile sourceSets.impl.output
runtime configurations.apiRuntime
runtime configurations.implRuntime
}
// JAR Task Configuration, define output the directories that make up the file.
jar {
from sourceSets.api.output
from sourceSets.impl.output
}
javadoc {
// but the main sourceset contains both api & impl sourceset, javadoc will generate all documentation
source sourceSets.api.allJava
}
test {
// Print in console the result of test
afterTest { test, result ->
println "Executing test ${test.name} [${test.className}] with result:
${result.resultType}"
}
4.11
Key Points
Tips
The Gradle SourceSets Properties are made to access to the directories and files that make up the SourceSet.
Java plugin give us a lot of basic funcionalities to improves the development process.
Gradle have a lot of default values, you need to set the custom values that adjust to your project
Every task have so many properties, that can be useful to your needs but to mantain the article more readable we dont mention
it here
Gradle SourceSet concept, is an excellent tool to build a clean structure into your project and make softwares components,
atomic pieces that you can manage and assemble.
4.12
Download
You can download the full source code of this example here Gradle SourceSet Project
42 / 70
Chapter 5
5.1
Gradle is an automatic build tool of more use today, so its almost necessary to integrate the different types of projects with
Gradle, to automate the process of build and liberation. In this example we will see how using Gradle can compile, build, install
and run a bundle in an OSGi environment. The main goal is to understand Gradle integration with OSGi BND tools.
5.1.1
Basic Concepts
There are some basic concepts that we must check before starting the example.
Gradle: Our tool to build and automate the process.
OSGi: Its the framework to make Java Modular applications and the environment where to deploy.
BND Tools: Its a framework or library pack, that makes OSGi development process more friendly and give to us a lot of
capabilities to customize out OSGi bundles. OSGi and BND Tools are required each other.
Gradle-Osgi Plugin: Its a Gradle Plugin developed by Renato Athaydes to make the OSGi integration easier.
Apache Felix, Eclipse Equinox: Are the main OSGi implementations, are containers to deploy OSGi bundles. Think in OSGi
bundles like a war file and Apache Felix like Tomcat container.
I want to make this example so simple, so we start.
5.2
What do We Need?
5.3
43 / 70
Environment Configuration
To make simpler the example, we assume that you have already installed your Eclipse, JDK, Gradle and environment variables
for both tools (JAVA_HOME and GRADLE_HOME).
How to Install OSGi?
Its the most simple installation ever, you only need to download Eclipse! Eclipse is one the projects that use OSGi for your
development and release process, so OSGi, Equinox and Felix frameworks are already installed as Eclipses plugins.
Next Step, Install BND Tools Eclipse Plugin.
Please download and install from Eclipse Marketplace using the menu: Help > Eclipse Marketplace > type "bndtools".
5.4
Create a new OSGi bundle project using File > New > Other > Bndtools > Bndtools OSGi project
44 / 70
45 / 70
46 / 70
47 / 70
5.5
48 / 70
The last step before injects Gradle is to deploy the Bundle in an OSGi container, in this example we use Apache Felix. To make
possible this, we need to configure bnd.bnd file.
Define a version number, choose the Activator that we created before. In the Export Packages please choose the green plus sign,
and add the main package that contains the Activator.
49 / 70
5.6
|Level|Name
|
0|System Bundle (4.4.1)
|
1|GradleOSGiProjectIntegration (1.0.0.201507130549)
|
1|Apache Felix Gogo Command (0.14.0)
|
1|Apache Felix Gogo Runtime (0.12.1)
|
1|Apache Felix Gogo Shell (0.10.0)
Gradle Integration
To "Gradlify" the OSGi Project we need to create a Gradle Build script and configure it correctly. So, create a new File in root
project, New > File > type name "build.gradle".
This is the file, so well look in detail each instruction.
build.gradle
50 / 70
/*
* Author: Andres Cespedes
* Date: 01 July 2015
* Example: Gradle OSGi Integration Example
* Site: www.javacodegeeks.com
* */
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "com.athaydes.gradle.osgi:osgi-run-core:1.2"
}
}
// repositories to download external files, like apache felix
repositories {
jcenter()
mavenCentral()
}
// java version source compatibility
sourceCompatibility = 1.7
apply plugin: osgi-run
// osgi-run plugin task that add OSGi subprojects as a bundle files to deploy.
runOsgi {
bundles += subprojects
}
jar {
manifest { // Manifest.MF file customization
instruction Private-Package,com.javacodegeeks.gradle.osgi
instruction Bundle-Vendor, JavaCodeGeeks
instruction Bundle-Description, First OSGi Bundle Created By Gradle JCG Tutorial
instruction Bundle-Activator, com.javacodegeeks.gradle.osgi.HelloActivator
instruction Bundle-ManifestVersion, 2
instruction Bundle-Version, 1.0.0.${tstamp}
instruction Bundle-Name, GradleOSGiProjectIntegration
instruction Bundle-SymbolicName, GradleOSGiProjectIntegration
instruction Export-Package, com.javacodegeeks.gradle.osgi;version="1.0.0";uses :="org.osgi.framework"
}
}
The first part buildscript, define the repositories and dependencies to import Gradle Bnd OSGi Plugin. In line 18, we
set repositories to download and import external libraries to Gradle, this part its important as some think they just simply
repositories defined in the buildscript block, are necessary to get libraries like apache felix, these libraries are downloaded
to %USER_HOME%.gradlecachesmodules-2files-2.1 directory.
In line 20, apply the external OSGi plugin developed by Renato Athaydes, because Gradles official plugin doesnt add value at
all, dont adds tasks more than customize the Manifest.
Line 23 and 27 are the main part of the script, then we add the project to the bundles to deploy and then can configure OSGi
Manifest, each Manifest property is added as instruction, you can check OSGi documentation for available properties.
5.7
51 / 70
When apache felix gogo shell is active, type lb to see all available Bundles, if your bundle dont appears yet, so let install it,
how? Execute this simple command install file:../GradleOSGiProject.jar, obviously considering the name of
your jar; apache gogo shell will tell you the Bundle ID, in this case is 4.
5.8
Gradle already setup OSGi environment, so, executing apache gogo shell commands we can interact in Gradle thread with the
OSGi Bundle, updating Manifest or Activator itself.
52 / 70
5.9
Key Points
Tips
Gradle Official plugin is poor to support OSGi integration
Key point to Gradle-OSGi integration is to know how to install external bundles
53 / 70
Unofficial Gradle Run Osgi Bundle plugin facilitates the integration process, thanks to Renato Athaydes for his job.
Manage OSGi deployment through Gradle enhances the development process by automatization and isolation the execution
from Eclipse
5.10
54 / 70
Chapter 6
6.1
Gradle Wrapper is a type batch or shell script that downloads and automatically configures Gradle to execute tasks. Imagine
that you want to run a Gradle build, well you need to download and install Gradle in your computer, so this concept allows is to
distribute our project and build configurations with no need to have Gradle installed.
6.2
This is a simple example, really you only need Gradle to start and to create the base wrapper to distribute to all others, but to
make more readable will use Eclipse. So
As IDE: Eclipse Luna 4.4
Eclipse Gradle Plugin
Java JDK 1.7
Gradle 2.3 or higher
6.3
Environment Configuration
Please set your Gradle environment variables and install the Gradle plugin on your IDE. To avoid to be boilerplate visit this
previous posts that show how to configure your Gradle Environment. Gradle Hello World Tutorial
6.4
In Eclipse, Create a new Gradle Project and then edit gradle build script.
55 / 70
Then, we can execute this task to generate the wrapper files. Execute gradle createGradleWrapper or gradle cGW
in abbreviated form on Windows command shell. This is the output:
C:\Users\Andres\workspaceLuna\GradlWrapperExample>gradle cGW
:GradlWrapperExample:createGradleWrapper UP-TO-DATE
BUILD SUCCESSFUL
Total time: 1.044 secs
C:\Users\Andres\workspaceLuna\GradlWrapperExample>
6.5
56 / 70
Then, after the execution of the task, two files are generated: gradlej and gradlej.bat in the root of the project (so refresh
it to see them), that contain all the logic and configurations to run Gradle.
This new files are part of the project, so is a good practice add these files to the version control, to able team people that checkout
project and build the scripts with gradle and gradlew by default if you dont customize the name) instead of theirs Gradle version.
So, to test Gradle Wrapper we add this simple task and we run with gradlej instead of gradle command.
task helloWrapper << {
println Welcome to JCG Gradle Wrapper Tutorial
}
Execute this command gradlej helloWrapper or gradlej hW in abbreviated form on Windows command shell. This
is the output:
C:\Users\Andres\workspaceLuna\GradlWrapperExample>gradlej hW
:GradlWrapperExample:helloWrapper
Welcome to JCG Gradle Wrapper Tutorial
BUILD SUCCESSFUL
Total time: 1.445 secs
C:\Users\Andres\workspaceLuna\GradlWrapperExample>
This is how we can use Gradle wrapper to build projects even if other developers dont have Gradle installed.
6.6
Key Points
Tips
Gradle Wrapper is a good practice to standardize the builds
Is a good practice too, add Gradle Wrapper in a control version system to distribute to the team
distributionUrl property can used to reference a download URL in your company intranet or a custom fixed Gradle
version.
If you build via Gradle Wrapper, any Gradle version installed in the PC is ignored.
You will save time on installing and setting Gradle in every developers machine.
6.7
57 / 70
Chapter 7
7.1
Gradle is a powerful tool for building and automation. It has many advantages, enabling the development of build scripts that
are cross-platform and cross-IDE. You should have no problems migrating your Gradle-based applications to a different IDE or
Continuous Integration server.
7.2
Requirements
7.3
The tasks that we will perform in this post are simple. To install Gradle in NetBeans IDE, go to Tools > Plugins > Available
Plugins.
Then, type "Gradle" and choose "Gradle Support" plugin, of which the author is Attila Kelemen, and click Install.
58 / 70
7.4
We will assume that you have installed Gradle in your computer if you didnt have yet, take a look here.
In this step we have to set the default configuration for Gradles environment.
Then, go to Menu Tools > Options > Miscellaneous > Gradle.
Here we need to set 2 important and critical configurations in the Gradle Installation category.
59 / 70
7.5
In NetBeans IDE we need to set a Root Project to start working, so open new project wizard, and in Gradle category choose
Gradle Root Project and click next, give a projects name and Maven Group Id, then click Finish.
60 / 70
61 / 70
62 / 70
7.6
Then, we have to add a simple class that executes a print console, so create a package and class on Gradle subproject called
Greeting with only a main method.
Greeting.java
package com.javacodegeeks.gradle.netbeans;
/**
*
* @author Andres Cespedes
* @since 1.7
*/
public class Greeting {
public static void main(String[] args) {
System.out.println("Hello World JCG in Gradle NetBeans");
}
}
The last step is to set this class as Main Class, so in build.gradle script of subproject HelloProject type full name without
extension. The build.gradle script may looks like this:
// Note: "common.gradle" in the root project contains additional initialization
//
for this project. This initialization is applied in the "build.gradle"
//
of the root project.
//
//
//
//
//
//
//
if
63 / 70
NetBeans will automatically add "run" and "debug" tasks relying on the
"mainClass" property. You may however define the property prior executing
tasks by passing a "-PmainClass=" argument.
Note however, that you may define your own "run" and "debug" task if you
prefer. In this case NetBeans will not add these tasks but you may rely on
your own implementation.
(!hasProperty(mainClass)) {
ext.mainClass = com.javacodegeeks.gradle.netbeans.Greeting
}
dependencies {
// TODO: Add dependencies here
//
but note that JUnit should have already been added in parent.gradle.
//
By default, only the Maven Central Repository is specified in
//
parent.gradle.
//
// You can read more about how to add dependency here:
//
https://www.gradle.org/docs/current/userguide/dependency_management.html#sec: how_to_declare_your_dependencies
}
So, make right click on subproject HelloProject then Run, the output will be this: .NetBeans Gradle Output NetBeans Gradle
Output
7.7
Key Points
Tips
Gradle NetBeans Plugin is unofficial yet, but Kelemen has done a great job.
In NetBeans Gradle needs a multiproject structure, is mandatory a root project to work.
All Gradle configuration needs to be done right in both places to ensure correctly operation, gradle build scripts and project
properties.
7.8
64 / 70
Chapter 8
8.1
This is a basic Gradle plugin that allows packaging web applications in WAR files. This plugin adds a war task for us that we
can invoke instead of creating a war task ourselves. Basically, its a copy file task, that maintains the projects structure on WAR
file, but it follows some configurations.
src/main/java default directory where java source files are. We can customize this with sourcesets.
src/main/webapp default web sources directory for the content of the WAR file. We can change the value with the
webAppDirName property.
Adds 2 dependency configurations, providedCompile and providedRuntime, any dependencies added to these configurations
are not packaged in WAR file, so are not copied to the WEB-INF/lib directory. Tipically libraries declared in these dependecy
configurations reside on the container.
8.2
8.3
Environment Configuration
Please set your Gradle environment variables and install the Gradle plugin on your IDE. To avoid to be repetitive, visit this
previous posts that show how to configure your Gradle Environment. Gradle Hello World Tutorial
8.4
65 / 70
On eclipse create a new Dynamic Web Project, go to File > New > Dynamic Web Project, choose your tomcat container and
servlet version (in this example is servlet 3.0).
66 / 70
</html>
The last step is to test the dynamic web application running on Tomcat server, so make right click to the project and Run As "Run
On Server" to check the application is on a valid state, hereafter we will use Gradle to do all tasks.
8.5
67 / 70
}
// dependencies to run on tomcat, are mandatory for tomcat plugin
dependencies {
def tomcatVersion = 7.0.57
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
exclude group: org.eclipse.jdt.core.compiler, module: ecj
}
}
// context where tomcat is deployed, by defautl localhost:8080/
tomcatRun.contextPath = /
tomcatRunWar.contextPath = /
Look at the previous file line by line, in the first part we define the repositories to download all libraries and dependencies. Then
we must apply plugins to perform all necessary tasks, java plugin is to compile and copy java files, war plugin is to package all
files and resources into WAR file and tomcat Benjamin Muschko plugin is to deploy the generated war on Tomcat server.
In line 22, we customize the webapp directory value that by default point to webapp folder. Repositories task is to define where
its all dependencies and libraries will be downloaded.
The last 2 parts are, sourcesets to set the custom directory of which classes are provided, by default is src/main/java. And
for last, dependencies is to define the tomcat dependencies that are needed by the tomcat plugin.
8.6
Running Example
68 / 70
8.7
The last task is to deploy the WAR file on tomcat server so with all previous job only we need to execute this Gradle command,
gradle tomcatRun or gradle tR as abbreviated form on command shell. This will be the output:
C:\Users\Andres\workspaceLuna\GradleWarPlugin>gradle tomcatRun
:GradleWarPlugin:compileJava UP-TO-DATE
:GradleWarPlugin:processResources UP-TO-DATE
:GradleWarPlugin:classes UP-TO-DATE
:GradleWarPlugin:tomcatRun
Started Tomcat Server
The Server is running at https://localhost:8080
> Building 75% > :GradleWarPlugin:tomcatRun
69 / 70
70 / 70
8.8
Key Points
Tips
Gradle WAR plugin provides a clean tool to package web applications, that isnt IDE dependent.
Its necessary to set our custom webapp diretory and sourceset values to ensure that WAR packaging works.
Tomcat Plugin has an embedded Tomcat server that allows to test WAR files. If you want to deploy WAR on remote or external
server you need to use another plugin. See cargo plugin.
With both plugins WAR and Tomcat, the deployment process it becomes a one-button production mode process.
8.9
This was an example of Gradle WAR Plugin and how to deploy it using Gradle Tomcat Plugin.
Download
You can download the full source code of this example here: Gradle WAR and Tomcat Plugin Project