Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Gradle Effective Implementations Guide
Gradle Effective Implementations Guide

Gradle Effective Implementations Guide: This comprehensive guide will get you up and running with build automation using Gradle. , Second Edition

Arrow left icon
Profile Icon Hubert Klein Ikkink
Arrow right icon
₱1399.99 ₱2000.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook May 2016 368 pages 2nd Edition
eBook
₱1399.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial
Arrow left icon
Profile Icon Hubert Klein Ikkink
Arrow right icon
₱1399.99 ₱2000.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook May 2016 368 pages 2nd Edition
eBook
₱1399.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial
eBook
₱1399.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Gradle Effective Implementations Guide

Chapter 1. Starting with Gradle

When we develop a software, we write, compile, test, package, and finally, distribute the code. We can automate these steps by using a build system. The big advantage is that we have a repeatable sequence of steps. The build system will always follow the steps that we have defined, so we can concentrate on writing the actual code and don't have to worry about the other steps.

Gradle is one such build system.

In this chapter, we will cover the following topics:

  • Getting started with Gradle
  • Writing our first build script
  • Looking at default tasks
  • Learning about command-line options
  • Discussing the Gradle graphical user interface

Gradle is a tool for build automation. With Gradle, we can automate compiling, testing, packaging, and deployment of our software or any other types of projects. Gradle is flexible, but has sensible defaults for most projects. This means that we can rely on the defaults if we don't want something special, but we can still can use the flexibility to adapt a build to certain custom needs.

Gradle is already used by large open source projects such as Spring, Hibernate, and Grails. Enterprise companies such as LinkedIn and Netflix also use Gradle.

In this chapter, we will explain what Gradle is and how to use it in our development projects.

Let's take a look at some of Gradle's features.

Declarative builds and convention over configuration

Gradle uses a Domain Specific Language (DSL) based on Groovy to declare builds. The DSL provides a flexible language that can be extended by us. As the DSL is based on Groovy, we can write Groovy code to describe a build and use the power and expressiveness of the Groovy language. Groovy is a language for the Java Virtual Machine (JVM), such as Java and Scala. Groovy makes it easy to work with collections, has closures, and a lot of useful features. The syntax is closely related to the Java syntax. In fact, we could write a Groovy class file with Java syntax and it will compile. However, using the Groovy syntax makes it easier to express the code intent and we need less boilerplate code than with Java. To get the most out of Gradle, it is best to also learn the basics of the Groovy language, but it is not necessary to start writing Gradle scripts.

Gradle is designed to be a build language and not a rigid framework. The Gradle core itself is written in Java and Groovy. To extend Gradle, we can use Java and Groovy to write our custom code. We can even write our custom code in Scala if we want to.

Gradle provides support for Java, Groovy, Scala, web, and OSGi projects out of the box. These projects have sensible convention-over-configuration settings that we probably already use ourselves. However, we have the flexibility to change these configuration settings if required for our projects.

Support for Ant Tasks and Maven repositories

Gradle supports Ant Tasks and projects. We can import an Ant build and reuse all the tasks. However, we can also write Gradle tasks dependent on Ant Tasks. The integration also applies for properties, paths, and so on.

Maven and Ivy repositories are supported to publish or fetch dependencies. So, we can continue to use any repository infrastructure that we already have.

Incremental builds

With Gradle, we have incremental builds. This means the tasks in a build are only executed if necessary. For example, a task to compile source code will first check whether the sources have changed since the last execution of the task. If the sources have changed, the task is executed; but if the sources haven't changed, the execution of the task is skipped and the task is marked as being up to date.

Gradle supports this mechanism for a lot of provided tasks. However, we can also use this for tasks that we write ourselves.

Multi-project builds

Gradle has great support for multi-project builds. A project can simply be dependent on other projects or be a dependency of other projects. We can define a graph of dependencies among projects, and Gradle can resolve these dependencies for us. We have the flexibility to define our project layout as we want.

Gradle has support for partial builds. This means that Gradle will figure out whether a project, which our project depends on, needs to be rebuild or not. If the project needs rebuilding, Gradle will do this before building our own project.

Gradle Wrapper

The Gradle Wrapper allows us to execute Gradle builds even if Gradle is not installed on a computer. This is a great way to distribute source code and provide the build system with it so that the source code can be built.

Also in an enterprise environment, we can have a zero-administration way for client computers to build the software. We can use the wrapper to enforce a certain Gradle version to be used so that the whole team is using the same version. We can also update the Gradle version for the wrapper, and the whole team will use the newer version as the wrapper code is checked in to version control.

Free and open source

Gradle is an open source project and it is licensed under the Apache License (ASL).

Getting started

In this section, we will download and install Gradle before writing our first Gradle build script.

Before we install Gradle, we must make sure that we have a Java Development SE Kit (JDK) installed on our computer. Gradle requires JDK 6 or higher. Gradle will use the JDK found on the path of our computer. We can check this by running the following command on the command line:

$ java -version

Although Gradle uses Groovy, we don't have to install Groovy ourselves. Gradle bundles the Groovy libraries with the distribution and will ignore a Groovy installation that is already available on our computer.

Gradle is available on the Gradle website at http://www.gradle.org/downloads. From this page, we can download the latest release of Gradle. We can also download an older version if we want. We can choose among three different distributions to download. We can download the complete Gradle distribution with binaries, sources, and documentation; or we can only download the binaries; or we can only download the sources.

To get started with Gradle, we will download the standard distribution with the binaries, sources, and documentation. At the time of writing this book, the current release is 2.12.

Installing Gradle

Gradle is packaged as a ZIP file for one of the three distributions. So when we have downloaded the Gradle full-distribution ZIP file, we must unzip the file. After unpacking the ZIP file we have:

  • Binaries in the bin directory
  • Documentation with the user guide, Groovy DSL, and API documentation in the doc directory
  • A lot of samples in the samples directory
  • Source code of Gradle in the src directory
  • Supporting libraries for Gradle in the lib directory
  • A directory named init.d, where we can store Gradle scripts that need to be executed each time we run Gradle

Once we have unpacked the Gradle distribution to a directory, we can open a command prompt. We go to the directory where we have installed Gradle. To check our installation, we run gradle -v and get an output with the used JDK and library versions of Gradle, as follows:

$ gradle -v
------------------------------------------------------------
Gradle 2.12
------------------------------------------------------------
Build time:   2016-03-14 08:32:03 UTC
Build number: none
Revision:     b29fbb64ad6b068cb3f05f7e40dc670472129bc0
Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.3 compiled on             December23 2013
JVM:          1.8.0_66 (Oracle Corporation 25.66-b17)
OS:           Mac OS X 10.11.3 x86_64

Here, we can check whether the displayed version is the same as the distribution version that we have downloaded from the Gradle website.

To run Gradle on our computer, we have to only add $GRADLE_HOME/bin to our PATH environment variable. Once we have done that, we can run the gradle command from every directory on our computer.

If we want to add JVM options to Gradle, we can use the JAVA_OPTS and GRADLE_OPTS environment variables. JAVA_OPTS is a commonly used environment variable name to pass extra parameters to a Java application. Gradle also uses the GRADLE_OPTS environment variable to pass extra arguments to Gradle. Both environment variables are used, so we can even set them both with different values. This is mostly used to set, for example, an HTTP proxy or extra memory options.

Installing with SKDMAN!

Software Development Kit Manager (SDKMAN!) is a tool to manage versions of software development kits such as Gradle. Once we have installed SKDMAN!, we can simply use the install command and SDKMAN! downloads Gradle and makes sure that it is added to our $PATH variable. SDKMAN! is available for Unix-like systems, such as Linux, Mac OSX, and Cygwin (on Windows).

First, we need to install SDKMAN! with the following command in our shell:

$ curl -s get.sdkman.io | bash

Next, we can install Gradle with the install command:

$ sdk install gradle
Downloading: gradle 2.12
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0   354    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100 42.6M  100 42.6M    0     0  1982k      0  0:00:22  0:00:22 --:--:-- 3872k
Installing: gradle 2.12
Done installing!
Do you want gradle 2.12 to be set as default? (Y/n): Y
Setting gradle 2.12 as default.

If we have multiple versions of Gradle, it is very easy to switch between versions with the use command:

$ sdk use gradle 2.12
Using gradle version 2.12 in this shell.

Writing our first build script

We now have a running Gradle installation. It is time to create our first Gradle build script. Gradle uses the concept of projects to define a related set of tasks. A Gradle build can have one or more projects. A project is a very broad concept in Gradle, but it is mostly a set of components that we want to build for our application.

A project has one or more tasks. Tasks are a unit of work that need to be executed by the build. Examples of tasks are compiling source code, packaging class files into a JAR file, running tests, and deploying the application.

We now know a task is a part of a project, so to create our first task, we also create our first Gradle project. We use the gradle command to run a build. Gradle will look for a file named build.gradle in the current directory. This file is the build script for our project. We define our tasks that need to be executed in this build script file.

We create a new build.gradle file and open this in a text editor. We type the following code to define our first Gradle task:

task helloWorld << { 
    println 'Hello world.' 
} 

With this code, we will define a helloWorld task. The task will print the words Hello world. to the console. The println is a Groovy method to print text to the console and is basically a shorthand version of the System.out.println Java method.

The code between the brackets is a closure. A closure is a code block that can be assigned to a variable or passed to a method. Java doesn't support closures, but Groovy does. As Gradle uses Groovy to define the build scripts, we can use closures in our build scripts.

The << syntax is, technically speaking, an operator shorthand for the leftShift()method, which actually means add to. Therefore, here we are defining that we want to add the closure (with the println 'Hello world' statement) to our task with the helloWorld name.

First, we save build.gradle, and with the gradle helloWorld command, we execute our build:

$ gradle helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 2.384 secs
This build could be faster, please consider using the Gradle  Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.html

The first line of output shows our line Hello world. Gradle adds some more output such as the fact that the build was successful and the total time of the build. As Gradle runs in the JVM, every time we run a Gradle build, the JVM must be also started. The last line of the output shows a tip that we can use the Gradle daemon to run our builds. We will discuss more about the Gradle daemon later, but it essentially keeps Gradle running in memory so that we don't get the penalty of starting the JVM each time we run Gradle. This drastically speeds up the execution of tasks.

We can run the same build again, but only with the output of our task using the Gradle --quiet or -q command-line option. Gradle will suppress all messages except error messages. When we use the --quiet (or -q) option, we get the following output:

$ gradle --quiet helloWorld
Hello world.

Default Gradle tasks

We can create our simple build script with one task. We can ask Gradle to show us the available tasks for our project. Gradle has several built-in tasks that we can execute. We type gradle -q tasks to see the tasks for our project:

$ gradle -q tasks
------------------------------------------------------------
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        'hello-world'. [incubating]
dependencies - Displays all dependencies declared in root project  'hello-world'.
dependencyInsight - Displays the insight into a specific n      dependency in root project 'hello-world'.
help - Displays a help message.
model - Displays the configuration model of root project   'hello-world'. [incubating]
projects - Displays the sub-projects of root project 'hello-world'.
properties - Displays the properties of root project 'hello-world'.
tasks - Displays the tasks runnable from root project 'hello-world'.
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 <task>

Here, we see our helloWorld task in the Other tasks section. The Gradle built-in tasks are displayed in the Help tasks section. For example, to get some general help information, we execute the help task:

$ gradle -q help
Welcome to Gradle 2.12.
To run a build, run gradle <task> ...
To see a list of available tasks, run gradle tasks
To see a list of command-line options, run gradle --help
To see more detail about a task, run gradle help --task <task>

The properties task is very useful to see the properties available for our project. We haven't defined any property ourselves in the build script, but Gradle provides a lot of built-in properties. The following output shows some of the properties:

$ gradle -q properties
------------------------------------------------------------
Root project
------------------------------------------------------------
allprojects: [root project 'hello-world']
ant: org.gradle.api.internal.project.DefaultAntBuilder@3bd3d05e
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@6aba5d30
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@61d34b4
asDynamicObject: org.gradle.api.internal.ExtensibleDynamicObject@588307f7
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@7df76d99

buildDir: /Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/build
buildFile: /Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/build.gradle
buildScriptSource: org.gradle.groovy.scripts.UriScriptSource@459cfcca
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@2acbc859
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@6ab7ce48
components: []
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@2c6aed22
...

The dependencies task will show dependencies (if any) for our project. Our first project doesn't have any dependencies, as the output shows when we run the task:

$ gradle -q dependencies
------------------------------------------------------------
Root project
------------------------------------------------------------
No configurations

The projects tasks will display subprojects (if any) for a root project. Our project doesn't have any subprojects. Therefore, when we run the projects task, the output shows us our project has no subprojects:

$ gradle -q projects
------------------------------------------------------------
Root project
------------------------------------------------------------
Root project 'hello-world'
No sub-projects
To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :tasks

The model tasks displays information about the model that Gradle builds internally from our project build file. This feature is incubating, which means that the functionality can change in future versions of Gradle:

$ gradle -q model
------------------------------------------------------------
Root project
------------------------------------------------------------
+ model
+ tasks
     | Type:       org.gradle.model.ModelMap<org.gradle.api.Task>
        | Creator:     Project.<init>.tasks()
        + components
              | Type:       org.gradle.api.reporting.components.ComponentReport
              | Value:      task ':components'
              | Creator:     tasks.addPlaceholderAction(components)
              | Rules:
                ⤷ copyToTaskContainer
        + dependencies
              | Type:       org.gradle.api.tasks.diagnostics.DependencyReportTask
              | Value:      task ':dependencies'
              | Creator:     tasks.addPlaceholderAction(dependencies)
              | Rules:
...

We will discuss more about these and the other tasks in this book.

Task name abbreviation

Before we look at more Gradle command-line options, it is good to discuss a real-time save feature of Gradle: task name abbreviation. With task name abbreviation, we don't have to type the complete task name on the command line. We only have to type enough of the name to make it unique within the build.

In our first build, we only have one task, so the gradle h command should work just fine. However, we didn't take the built-in help task into account. So, to uniquely identify our helloWorld task, we use the hello abbreviation:

$ gradle -q hello
Hello world.

We can also abbreviate each word in a CamelCase task name. For example, our helloWorld task name can be abbreviated to hW:

$ gradle -q hW
Hello world.

This feature saves us the time spent in typing the complete task name and can speed up the execution of our tasks.

Executing multiple tasks

With just a simple build script, we already discussed that we have a couple of default tasks besides our own task that we can execute. To execute multiple tasks, we only have to add each task name to the command line. Let's execute our helloWorld custom task and built-in tasks task:

$ gradle helloWorld tasks
:helloWorld
Hello world.
:tasks
------------------------------------------------------------
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 'hello-world'. [incubating]
 dependencies - Displays all dependencies declared in root project 'hello-world'.
dependencyInsight - Displays the insight into a specific  dependency in root project 'hello-world'.
help - Displays a help message.
model - Displays the configuration model of root project 'hello-world'. [incubating]
projects - Displays the sub-projects of root project 'hello-world'.
properties - Displays the properties of root project 'hello-world'.
tasks - Displays the tasks runnable from root project 'hello-world'.
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 <task>
BUILD SUCCESSFUL
Total time: 2.028 secs
This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.html

We see the output of both tasks. First, helloWorld is executed, followed by tasks. In the output, we see the task names prepended  with a colon (:) and the output is in the next lines.

Gradle executes the tasks in the same order as they are defined in the command line. Gradle will only execute a task once during the build. So even if we define the same task multiple times, it will only be executed once. This rule also applies when tasks have dependencies on other tasks. Gradle will optimize the task execution for us and we don't have to worry about that.

Command-line options

The gradle command is used to execute a build. This command accepts several command-line options. We know the --quiet (or -q) option to reduce the output of a build. If we use the --help (or -h or -?) option, we see the complete list of options, as follows:

$ gradle --help
USAGE: gradle [option...] [task...]
-?, -h, --help          Shows this help message.
-a, --no-rebuild        Do not rebuild project dependencies.
-b, --build-file        Specifies the build file.
-c, --settings-file     Specifies the settings file.
--configure-on-demand   Only relevant projects are configured in this build run. This means faster build for large multi-project builds. [incubating]
--console               Specifies which type of console output to generate. Values are 'plain', 'auto' (default) or 'rich'.
--continue              Continues task execution after a task failure.
-D, --system-prop       Set system property of the JVM (e.g. -Dmyprop=myvalue).
-d, --debug             Log in debug mode (includes normal stacktrace).
--daemon                Uses the Gradle daemon to run the build. Starts the daemon if not running.
--foreground            Starts the Gradle daemon in the foreground. [incubating]
-g, --gradle-user-home  Specifies the gradle user home directory.
--gui                   Launches the Gradle GUI.
-I, --init-script       Specifies an initialization script.
-i, --info              Set log level to info.
-m, --dry-run           Runs the builds with all task actions disabled.
--max-workers           Configure the number of concurrent workers Gradle is allowed to use. [incubating]
--no-color              Do not use color in the console output. [deprecated - use --console=plain instead]
--no-daemon             Do not use the Gradle daemon to run the build.
--offline               The build should operate without accessing network resources.
-P, --project-prop      Set project property for the build script (e.g. -Pmyprop=myvalue).
-p, --project-dir       Specifies the start directory for Gradle. Defaults to current directory.
--parallel              Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use. [incubating]
--parallel-threads      Build projects in parallel, using the specified number of executor threads. [deprecated - Please use --parallel, optionally in conjunction with --max-workers.] [incubating]
--profile               Profiles build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir     Specifies the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet             Log errors only.
--recompile-scripts     Force build script recompiling.
--refresh-dependencies  Refresh the state of dependencies.
--rerun-tasks           Ignore previously cached task results.
-S, --full-stacktrace   Print out the full (very verbose) stacktrace for all exceptions.
-s, --stacktrace        Print out the stacktrace for all exceptions.
--stop                  Stops the Gradle daemon if it is running.
-t, --continuous        Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change. [incubating]
-u, --no-search-upward  Don't search in parent folders for a settings.gradle file.
-v, --version           Print version info.
-x, --exclude-task      Specify a task to be excluded from execution.

Logging options

Let's look at some of the options in more detail. The --quiet (or -q), --debug (or -d), --info (or -i), --stacktrace (or-s), and --full-stacktrace (or-S) options control how much output we see when we execute tasks. To get the most detailed output, we use the --debug (or -d) option. This option provides a lot of output with information about the steps and classes used to run the build. The output is very verbose, therefore, we will not use it much.

To get a better insight on the steps that are executed for our task, we can use the --info (or -i) option. The output is not as verbose as with --debug, but it can provide a better understanding of the build steps:

$ gradle --info helloworld
Starting Build
Settings evaluated using settings file '/master/settings.gradle'.
Projects loaded. Root project using build file '/Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/build.gradle'.
Included projects: [root project 'hello-world']
Evaluating root project 'hello-world' using build file '/Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/build.gradle'.
All projects evaluated.
Selected primary task 'helloWorld' from project :
Tasks to be executed: [task ':helloWorld']
:helloWorld (Thread[main,5,main]) started.
:helloWorld
Executing task ':helloWorld' (up-to-date check took 0.001 secs) due to:
  Task has not declared any outputs.
Hello world.
:helloWorld (Thread[main,5,main]) completed. Took 0.021 secs.
BUILD SUCCESSFUL
Total time: 1.325 secs
This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.html

If our build throws exceptions, we can see the stack trace information with the --stacktrace (or -s) and --full-stacktrace (or -S) options. The latter option will output the most information and is the most verbose. The --stacktrace and --full-stacktrace options can be combined with the other logging options.

Changing the build file and directory

We created our build file with the build.gradle name. This is the default name for a build file. Gradle will look for a file with this name in the current directory to execute the build. However, we can change this with the --build-file (or -b) and --project-dir (or -p) command-line options.

Let's run the gradle command from the parent directory of our current directory:

$ cd ..
$ gradle --project-dir hello-world -q helloWorld
Hello world.

We can also rename our build.gradle to, for example, hello.build and still execute our build:

$ mv build.gradle hello.build
$ gradle --build-file hello.build -q helloWorld
Hello world.

Running tasks without execution

With the --dry-run (or -m) option, we can run all tasks without really executing them. When we use the dry-run option, we can see the tasks that are executed, so we get an insight on the tasks that are involved in a certain build scenario. We don't even have to worry whether the tasks are actually executed. Gradle builds up a Directed Acyclic Graph (DAG) with all tasks before any task is executed. The DAG is build so that the tasks will be executed in order of dependencies, and a task is only executed once:

$ gradle --dry-run helloWorld
:helloWorld SKIPPED
BUILD SUCCESSFUL
Total time: 1.307 secs
This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.html

Gradle daemon

We already discussed that Gradle executes in a JVM, and each time we invoke the gradle command, a new JVM is started, the Gradle classes and libraries are loaded, and the build is executed. We can reduce the build execution time if we don't have to load JVM and Gradle classes and libraries each time we execute a build. The --daemon command-line option starts a new Java process that will have all Gradle classes and libraries already loaded and then execute the build. Next time when we run Gradle with the --daemon option, only the build is executed as the JVM with the required Gradle classes and libraries is already running.

The first time we execute Gradle with the --daemon option, the execution speed will not have improved as the Java background process was not started yet. However, the next time, we can see a major improvement:

$ gradle --daemon helloWorld
Starting a new Gradle Daemon for this build (subsequent builds will be faster).
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 2.136 secs
$ gradle helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 0.594 secs

Even though the daemon process is started, we can still run Gradle tasks without using the daemon. We use the --no-daemon command-line option to run a Gradle build, and then the daemon is not used:

$ gradle --no-daemon helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 1.325 secs

To stop the daemon process, we use the --stop command-line option:

$ gradle --stop
Stopping daemon(s).
Gradle daemon stopped.

This will stop the Java background process completely.

To always use the --daemon command-line option, but we don't want to type it every time we run the gradle command, we can create an alias if our operating system supports aliases. For example, on a Unix-based system, we can create an alias and then use the alias to run the Gradle build:

$ alias gradled='gradle --daemon'
$ gradled helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 0.572 secs

Instead of using the --daemon command-line option, we can use the org.gradle.daemon Java system property to enable the daemon. We can add this property to the GRADLE_OPTS environment variable so that it is always used when we run a Gradle build:

$ export GRADLE_OPTS="-Dorg.gradle.daemon=true"
$ gradle helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 0.575 secs

Finally, we can add a gradle.properties file to the root of our project directory. In the file, we can define a org.gradle.daemon property and assign the  true value to enable the Gradle daemon for all builds that are executed from this directory.

Let's create a gradle.properties file with the following contents:

org.gradle.daemon=true 

We can run our example task, helloWorld, and the build will use the Gradle daemon:

$ gradle helloWorld
:helloWorld
Hello world.
BUILD SUCCESSFUL
Total time: 0.58 secs

Profiling

Gradle also provides the --profile command-line option. This option records the time that certain tasks take to complete. The data is saved in an HTML file in the build/reports/profile directory. We can open this file in a web browser and check the time taken for several phases in the build process. The following image shows the HTML contents of the profile report:

Profiling

HTML page with profiling information

Offline usage

If we don't have access to a network at some location, we might get errors from our Gradle build, when a task needs to download something from the Internet, for example. We can use the --offline command-line option to instruct Gradle to not access any network during the build. This way we can still execute the build if all necessary files are already available offline and we don't get an error.

Understanding the Gradle graphical user interface

Finally, we take a look at the --gui command-line option. With this option, we start a graphical shell for our Gradle builds. Until now, we used the command line to start a task. With the Gradle GUI, we have a graphical overview of the tasks in a project and we can execute them by simply clicking on the mouse.

To start the GUI, we invoke the following command:

$ gradle --gui

A window is opened with a graphical overview of our task tree. We only have one task that one is shown in the task tree, as we can seen in the following screenshot:

Understanding the Gradle graphical user interface

Overview of tasks in the Gradle GUI

The output of running a task is shown at the bottom of the window. When we start the GUI for the first time, the tasks task is executed and we see the output in the window.

Task tree

The Task Tree tab shows projects and tasks found in our build project. We can execute a task by double-clicking on the task name.

By default, all the tasks are shown, but we can apply a filter to show or hide certain projects and tasks. The Edit filter button opens a new dialog window where we can define the tasks and properties that are a part of the filter. The Toggle filter button makes the filter active or inactive.

We can also right-click on the project and task names. This opens a context menu where we can choose to execute the task, add it to the favorites, hide it (adds it to the filter), or edit the build file. If we have associated the .gradle extension to a text editor in our operating system, then the editor is opened with the content of the build script. These options can be seen in the following screenshot:

Task tree

Available actions for a task in the Gradle GUI

Favorites

The Favorites tab stores tasks we want to execute regularly. We can add a task by right-clicking on the task in the Task Tree tab and selecting the Add To Favorites menu option, or if we have opened the Favorites tab, we can select the Add button and manually enter the project and task name that we want to add to our favorites list. We can see the Add Favorite dialog window in the following screenshot:

Favorites

Add favorites in the Gradle GUI

Command line

On the Command Line tab, we can enter any Gradle command that we normally would enter on the command prompt. The command can be added to Favorites as well. We see the Command Line tab contents in the following image:

Command line

Execute task with command-line optins

Setup

The last tab is the Setup tab. Here, we can change the project directory, which is set to the current directory by default.

We discussed about the different logging levels as command-line options previously in this chapter. With the GUI, we can select the logging level from the Log Level select box with the different log levels. We can choose debuginfoLifecycle, and error as log levels. The error log level only shows errors and is the least verbose, while debug is the most verbose log level. The lifecycle log level is the default log level.

Here, we also can set how detailed the exeption stack trace information should be. In the Stack Trace Output section, we can choose from the following three options:

  • Exceptions Only: This is for only showing the exceptions when they occur, which is the default value
  • Standard Stack Trace (-s): This is for showing more stack trace information for the exceptions
  • -S): This is for the most verbose stack trace information for exceptions

If we enable the Only Show Output When Error Occurs option, then we only get output from the build process if the build fails. Otherwise, we don't get any output.

Finally, we can define a different way to start Gradle for the build with the Use Custom Gradle Executor option. For example, we can define a different batch or script file with extra setup information to run the build process. The following screenshot shows the Setup tab page and all the options that we can set:

Setup

Setup Gradle options in the Gradle GUI

Summary

So, now we have discussed how to install Gradle on our computers. We have written our first Gradle build script with a simple task.

We have also seen how we use the built-in tasks of Gradle to get more information about a project. We discussed how to use the command-line options to help us run the build scripts. We have looked at the Gradle GUI and how we can use it to run Gradle build scripts.

In the next chapter, we will take a further look at tasks. We will discuss how to add actions to a task. We write more complex tasks, where the tasks will depend on other tasks. We will also discuss how Gradle builds up a task graph internally and how to use this in our projects.

Left arrow icon Right arrow icon

Key benefits

  • Practical and engaging from start to finish covering the fundamentals of Gradle
  • Learn the skills required to develop Java applications with Gradle and integrate at an enterprise level
  • Apply the correct plugin and configuration to our Gradle build files to work with the different languages

Description

Gradle is a project automation tool that has a wide range of applications. The basic aim of Gradle is to automate a wide variety of tasks performed by software developers, including compiling computer source code to binary code, packaging binary codes, running tests, deploying applications to production systems, and creating documentation. The book will start with the fundamentals of Gradle and introduce you to the tools that will be used in further chapters. You will learn to create and work with Gradle scripts and then see how to use Gradle to build your Java Projects. While building Java application, you will find out about other important topics such as dependency management, publishing artifacts, and integrating the application with other JVM languages such as Scala and Groovy. By the end of this book, you will be able to use Gradle in your daily development. Writing tasks, applying plugins, and creating build logic will be your second nature.

Who is this book for?

This book is for Java developers who have working knowledge of build automation processes and are now looking to gain expertise with Gradle and add to their skill set.

What you will learn

  • Write your first Gradle Script
  • Write build logic with the Gradle build language
  • Explore the Java plugins supported by Gradle
  • Understand dependency management in Gradle
  • Package and publish your (web) application
  • Integrate Scala and Groovy with Gradle
  • Write your own custom tasks and plugins
  • Integrate Gradle with your IDE

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 30, 2016
Length: 368 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784396114
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 30, 2016
Length: 368 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784396114
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 6,685.97
Mastering Gradle
₱2500.99
Gradle Essentials
₱1683.99
Gradle Effective Implementations Guide
₱2500.99
Total 6,685.97 Stars icon

Table of Contents

12 Chapters
1. Starting with Gradle Chevron down icon Chevron up icon
2. Creating Gradle Build Scripts Chevron down icon Chevron up icon
3. Working with Gradle Build Scripts Chevron down icon Chevron up icon
4. Using Gradle for Java Projects Chevron down icon Chevron up icon
5. Dependency Management Chevron down icon Chevron up icon
6. Testing, Building, and Publishing Artifacts Chevron down icon Chevron up icon
7. Multi-project Builds Chevron down icon Chevron up icon
8. Mixed Languages Chevron down icon Chevron up icon
9. Maintaining Code Quality Chevron down icon Chevron up icon
10. Writing Custom Tasks and Plugins Chevron down icon Chevron up icon
11. Gradle in the Enterprise Chevron down icon Chevron up icon
12. IDE Support Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(3 Ratings)
5 star 33.3%
4 star 66.7%
3 star 0%
2 star 0%
1 star 0%
Damian Sep 08, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book remains no doubts about how the Gradle works and does it in a very pleasant way. I couldn’t stop the reading.
Amazon Verified review Amazon
Roman May 14, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A little outdated (book based on Gradle version 2.11), but gives a strong basis and understanding what is going under the hood.Written in simple language, no problem to understand for non-native speakers.Best gradle book so far.
Amazon Verified review Amazon
Amazon Customer Apr 27, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a very good introduction to Gradle. Even though the project is advancing at a fast pace, most of the book is relevant. The only downside is that the book is a bit pricey.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.