This Tutorial Covers how to use Gradle to create a Project and Write Tasks in Groovy and run Tasks with Gradle Wrapper Using both the IDE & Build Command:
Being contemporary developers, we need to know about certain terms like Shift-Left, DevOps, Continuous Integration (CI), Continuous Delivery (CD), etc.
In this tutorial, we will learn about Groovy and Gradle along with their use to create Gradle build tasks and build projects respectively. Groovy is a multi-faceted language – with concise, familiar, and easy to use the syntax for Java platform and it can be used to write build and automation tasks.
This language glues well with Gradle, which is one of the popular tools used in integrating a developer’s workflow in a CI/CD pipeline.
This tutorial explains Gradle for Java developers. It includes details on how it works; how to use Gradle to build source code written in Java, for deployment on any platform.
It provides plugins for most of the IDE’s and makes it easier to deliver software faster. To follow us along the journey of learning the above-stated concepts, it will be great if you look at the repository of a sample project that we have created on Github.
Table of Contents:
System Requirements And Prerequisites
This section includes the step of installing an IDE – IntelliJ IDEA and Java Development Kit (JDK). The details on the basic concepts in the Groovy language to get ourselves to speed towards writing our first build task are explained with the help of a code snippet.
Install IntelliJ IDEA
Install an IDE (Integrated Development Environment) for creating the Java project. We use IntelliJ IDEA (Community Edition) for this tutorial. Please follow the respective links to download and install it on Windows/Mac/Linux.
Windows: Click here
Mac: Click here
Linux: Click here
Install And Setup JDK
Download JDK. One needs to sign up for a RedHat account to complete the step. Once it is downloaded, run the setup to install it on your Windows PC. Once it is installed, open the command prompt and run the below-given commands to check whether it is working or not.
The below commands can be used to know where the JDK is installed or not.
D:\softwaretestinghelp>where java
D:\softwaretestinghelp>where javac
Now let us configure the installed JDK with our IDE. Open the Platform settings in IntelliJ IDEA and Add the JDK by following the steps shown below. Please remember that this JDK is applicable to all the projects that you will work on using this IDE.
Step 1: Add the downloaded JDK to SDK under platform settings as shown in the image.
Step 2: Update Project SDK in the project settings as shown in the images
After applying the configured settings, please build the project once using the small green hammer icon in the IDE.
Set Up An Example Project
There are two ways to start with the project. We may either download the project zip file from the Github project page and import it as a Gradle project in the Intellij IDEA, or Clone the project from the Github repository.
Steps to clone the project from Github are given below:
Open the IDE by double-clicking the shortcut icon on your desktop. Please close any existing project if already opened. Please remember that Git plugin is by default bundled with IntelliJ IDEA. Thus, please do not install it.
Step 1: On the Welcome Screen of the IDE click on Get from Version Control.
Step 2: Provide the Github repository URL and click on Clone.
Step 3: Click on Yes when the Checkout file prompt is shown.
Step 4: Wait for the background process to finish and check the output.
Step 5: Click on the folded Project pane to look at the project structure in the explorer.
Write Your First Program In Groovy – Hello World
In the project, open the Gradle build file called build.gradle using the file explorer of your IDE and write the below-given code at the end of the file.
task helloWorld { doLast { println("Hello, World!") } }
Now run the first task by clicking Run on the context menu of the play task icon and observe the output of the println inbuilt method of Groovy. We can use “CTRL+SHIFT+F10” as well. (Please refer to the image below)
The output should look something similar to the one shown above.
Basics Of Groovy Language
Now that you have learned how to create your first program in Groovy, we can accelerate and learn about the basics of the language. This section will cover concepts such as variable names, syntax, operators, methods/functions/Closures, etc.
We will also cover the concepts that are more relevant from the project perspective such as accessing the properties of a project and importing closures/functions written in another build.gradle file.
Observe the below-given code snippet and comments to learn about various concepts of the language. This code snippet is quite handy for a quick walkthrough and a revision on the concepts of Groovy.
// Primer on Groovy def var1 = "var1" // A string variable declared and assigned outside a closure/function def var2 = 4 // An integer // Both of the above given variables are of type Object task task1 { doLast { println("Hello, World!") // A single line comment /* A Multi line comment Print a stored variable. Strings can be concatenated. Parentheses are not mandatory */ println var1 + " is my variable " println var1 + 2 // adding a digit to a string - No string conversion required. // operators for strings and numbers println(var2 + 3) def var3 = var2 + 2 // type of var3 is integer and var2 and var1 are Objects println(var3 * var2) // multiplication print(var3 / var2 + "\n") // division prints float and observe the concatenation of new line "\n" def mylist = [1, 2, 3] // creating a list // for loop on list items for (def i=0; i <= mylist.size() -1 ; i++){ // loop using for println(mylist[i]) } // While loop on list items def i=0 while (i<=mylist.size() - 1) { println(mylist[i]) i++ } } }
In both the loops, notice that the list has a zero-based index. Further details are mentioned at Groovy.
Now let’s learn about Gradle and see how to run a task.
What Is Gradle?
It is a build automation system. It supports building projects written in multiple languages. In this tutorial, we are using Java. This section explains the method of running Gradle commands from the command line. We are going to use it for building, testing, and deployment of our sample project.
Gradle Dependencies
You might already know how important it is to install dependencies in any open-source software project. Gradle can search for dependencies on public repositories such as Maven, Jcenter, and Google.
Mention these repositories in build.gradle file as shown below:
repositories { mavenCentral() jcenter() google() }
Now mention the compile-time dependencies as shown below.
dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' // https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59' }
The mentioned dependencies are automatically downloaded and included in the project’s CLASSPATH by the Gradle plugin. Check the downloaded dependencies in the project explorer of the IDE.
Check the Gradle version by using the below-given command.
Features And Advantages Of Using Gradle
Enlisted below are some of the features that help in easy standardization and adoption of Gradle as a part of DevOps in an organization.
- It uses a DSL based language called Groovy. It is easier to write build tasks in Groovy than in XML. Moreover, XML’s are cumbersome and not easy to read. However, Groovy is easier to learn and read.
- It supports creation builds for projects based on both monolithic and microservices architectures.
- It can be used to create multiple artifacts such as Documents, API’s. implementation jars, etc. and publish them as part of the same build.
- It has quite a powerful language construct to order the interdependent tasks as a part of the builds.
There are many more features that enable the teams to customize their builds while packaging the software with higher quality. More details on the features are given here.
Now let us move ahead and run a Gradle build task.
Run A Gradle Task
Run the command shown below under the project’s root directory to run the build task called task1.
D:\softwaretestinghelp\gitrepo>.\gradlew.bat task1
Check the output as shown below.
Build A Gradle Project
In this section, we will go through the project structure, understand its various components, and build the project.
Structure Of The Sample Project
The sample project under discussion has an src folder with two main directories (folders) viz. Main and test. The main directory has Java source code related to a sample command-line application called HelloWorld.
The HelloWorld class has two methods i.e. The main method, which prints the first argument out of the given list of arguments and a method1 method, which prints 1st argument concatenated with the first 3 characters of the second argument.
The test folder has a JUnit test class that has tests to test the above-mentioned methods in our Application. Please check the source code of these tests.
The sample project also has a Gradle wrapper folder. You must use the mentioned Gradle wrapper version while running your build tasks.
The Version of Gradle is very important and whenever developers want to share their code it is always beneficial to share a wrapper along with the project files. It saves a lot of time as wrapper automatically downloads the declared version of the Gradle.
Examples Of Build Tasks
Documenting the code is considered as one of the most important attributes of a developer. It is a usual practice to share the documentation in html format. Gradle helps in generating javadocs in html format projects. We can generate javadocs using the below command.
D:\softwaretestinghelp\gitrepo>.\gradlew.bat javadoc
Please check the javadoc under build directory in the project and you should see the results similar to the ones shown in the image below.
Please follow the javadoc style guide given at this link while writing Java documentation.
Now let’s change the build.gradle file to generate the documentation for test resources as well.
Update the build.gradle file with the snippet shown below
javadoc { classpath += sourceSets.test.compileClasspath source += sourceSets.test.allJava }
Again run the Gradle javadoc command to generate the documentation for main as well as test sources.
More details on the Gradle build tasks can be seen here.
Command to know more Gradle tasks is given below.
D:\softwaretestinghelp\gitrepo> .\gradlew.bat tasks
Now let’s build the project.
Build The Gradle Project
Follow the below-mentioned steps, to build the sample project from the command line:
- Change the project path.
- Use the below command to build the project.
However, you can also build the project by clicking the small hammer icon in the IDE.
D:\softwaretestinghelp\gitrepo> .\gradlew.bat build
The output of the build command will be as shown below.
Failures in the build run results are intentional for the purpose of this tutorial and can be neglected.
If you want to see the results of the tests that were run as part of this build, then you can check the reports folder as shown in the image below.
To check the results you can open the index.html file in a browser.
Automate Gradle Build Using Git Actions
As developers, we have to set up our workflows to build, test, and publish our projects, in order to collaborate with the operations team.
Moreover, setting up an environment by ourselves can be a daunting task and might have repercussions on our productivity. With the advent of a new culture of DevOps, we need to automate our workflows to reduce the challenges, arising out of build failures.
Meanwhile, software projects with developers, who are geographically distributed, need collaboration with the help of SCM software such as Git.
Thanks to Github Actions. Now you can see an additional tab on any Github repository that you create. You can create your development workflows and run them on any Github event such as push, release, pull_request, etc. This is revolutionary in terms of giving the power of CI/CD to the developer-community.
Open the Git Actions configurations at .github/workflows/gradle.yml file in the project. Notice that we are developing our project on Windows and in Git Actions we are testing it on ubuntu_latest.
Github Actions also has community-powered workflows that we can leverage on and increase the speed of delivering your project to customers. Based on the status of your build you can decide whether to release the project or not. We have given the example of a pre-release of the repository of the sample project.
An Optional Exercise
Given below are some of the steps for you to try.
- Create a new repository in Github.
- Add a reference of the new remote in the gradle_sample project.
- Use the commands to publish the changes to the new repository.
- Observe the results for your Gradle build under Git Actions.
Conclusion
Gradle is being used by teams in companies such as LinkedIn, Adobe, Netflix, etc. and it is a great tool to master. Working with Gradle is much easier than working in other build tools such as Maven and Ant.
These days it is all about speed and agility. Learning Gradle and Groovy can help you in adopting DevOps principles more easily.
To summarize, we covered concepts on the creation of a Gradle project, on writing build tasks in Groovy and on running tasks with Gradle wrapper during development using both the IDE and Gradle build command.
We also tested the build on a different target platform such as ubuntu_latest. We can use it with a build status, that can help in making a decision related to a project release.
If you are an automation engineer using Selenium Webdriver, then don’t fail to read our upcoming tutorial on configuring and setting up a Selenium project with Gradle.
Hope this tutorial would have enriched your knowledge on Gradle Concepts!!