How to Build Java Projects Using Gradle

How to Build Java Projects Using Gradle

Overview

Gradle is an automated project building tool that uses the concepts of both Apache Ant and Apache Maven but is based on a domain specific language rather than the traditional XML approach. Gradle is designed to support multi-project builds that are quite large and are difficult to manage via Ant or Maven.

This article will discuss the concepts of Gradle as a project building tool and also show how to configure and build a sample Java project.

Introduction

Gradle is an build tool that can be used to automate the process of building, testing, publishing, deploying, generating API documentations, etc.

Features: Gradle comes with following list of features:

  • Declarative build– Gradle provides declarative language elements that we can be assembled as per our choice. This declarative language is extensible which enables us to add our own new language or enhance the existing one. These elements also provide build by convention support for Java, Groovy and other modern Java based technologies.
  • Language for dependency based programming– The declarative language is very flexible and enables Gradle to support the specific requirements.
  • Structure the build– Gradle allows us to apply common design principles to our build, which enables us to create a structured build for our applications.
  • Scalability– Gradle has the ability to easily scale from a simple single project build to a huge enterprise multi-project build. It enables the incremental build and also has the ability to tackle the performance issues that plague large enterprise build scripts.
  • Multi-project support– Gradle supports multi-project builds. It enables us to maintain the relationships between different projects in the case of a multi-project build environment. It also supports partial builds. We can build a single subproject out of an enterprise application. While building the single subproject, Gradle takes care of the other subprojects if the said subproject has dependency on other subprojects.
  • Dependency Management– Gradle provides different ways to manage internal as well as external dependencies. It provides supports for all kinds of dependency management, starting from transitive dependency management with remote access to Maven or any other repository– even the local file system.
  • Integration tool– Gradle can easily import any Ant project and its targets and converts them into native Gradle tasks at runtime. Gradle also provides conversion mechanism to convert the maven pom.xml file into Gradle script.
  • Migration– Gradle easily adapts to any structure. We can easily develop the Gradle build in the same production branch.
  • Groovy Support – Gradle scripts are written in Groovy and not XML based.

Gradle Architecture

The following diagram shows the architecture components of Gradle build tool.

Installation and Use

Gradle comes in a zip bundle and can be downloaded from http://www.gradle.org/downloads. On the website, you can find three downloadable files:

  • gradle--all.zip – This bundle contains all components including binaries, source and documentation.
  • gradle--bin.zip – This bundle contains only the binaries.
  • gradle--src.zip – This bundle contains only the source files.

As a beginner, my advice is to download the gradle--all.zip file. Unzip this bundle on your UNIX system and append the bin folder to the path.

Steps to Complete the Installation

: As a prerequisite install JDK 1.5 or higher. Groovy library comes with the Gradle bundle so no need to install Groovy separately.

  • Download Gradle distribution from http://www.gradle.org/downloads
  • The Gradle distribution comes as a ZIP file. Unpack the distribution.
  • Add GRADLE_HOME/bin to your PATH environment variable.
  • Run Gradle via the gradle command. Check Gradle installation by using gradle -v command. It will display Gradle version and other details.

To test the installation, simply type ‘gradle’ on your terminal, you should see the following output:

Listing 1: Sample showing testing the installation

: helpWelcome to Gradle .To run a build, run gradle ...To see a list of available tasks, run gradle tasksTo see a list of command-line options, run gradle --helpBUILD SUCCESSFULTotal time: 3.135 secs

Once we are done with the installation, to check this, let us create a sample java project that has a simple java class:

Listing 2: Sample showing simple Java application

package com.home.gradletest;public class MyGradleSample {		public static void main( String[] args ) {		System.out.println( " Hello Every one . " ); 		System.out.println( " If you can see this output , it means that your gradle installation is successful ! " );	}}

In order to run Gradle you should have a ‘build.gradle’. If you don’t have this file, still you can check what tasks are available for the project. Simply type the following –

Listing 3: Sample showing available tasks

gradle tasks

You should see the following output:

:tasks== All tasks runnable from root project== Build Setup taskssetupBuild - Initializes a new Gradle build. [incubating]wrapper - Generates Gradle wrapper files. [incubating]== Help tasksdependencies - Displays all dependencies declared in root project 'gradletest'.dependencyInsight - Displays the insight into a specific dependency in root project 'gradletest'.help - Displays a help messageprojects - Displays the sub-projects of root project 'gradletest'.properties - Displays the properties of root project 'gradletest'.tasks - Displays the tasks runnable from root project 'gradletest'.To see all tasks and more detail, run with --all.BUILD SUCCESSFULTotal time: 2.667 secs

To begin, let’s create a simple build.gradle file.

Listing 4: Sample showing build.gradle file

apply plugin: 'java'apply plugin: 'eclipse'// tag::repositories[]repositories {    mavenCentral()}// end::repositories[]// tag::jar[]jar {    baseName = 'gradletest'    version =  '0.9'}// end::jar[]// tag::dependencies[]dependencies {    compile "joda-time:joda-time:2.2"}// end::dependencies[]// tag::wrapper[]task wrapper(type: Wrapper) {    gradleVersion = ''}// end::wrapper[]

The gradle file above is a very basic one. Now if we run the ‘gradle task’ command again, we can see a list of tasks available to build the project, create javadocs etc. Here we will use the ‘gradle build’ task more frequently. This task is responsible for:

  • Compiling the source code
  • Running the test classes
  • Assembling the code in a jar or a war file.

Once the build task is executed, and we see ‘BUILD SUCCESSFUL’ message we can see several folders being added inside the build folder. The most common ones are:

  • Classes – This contains the class files of the project.
  • Reports – This contains the reports generated by the build e.g. junit reports (if any)
  • libs – This contains the assembled project libraries (usually jar or war files).

Now let’s go inside the above script

  • The first couple of lines mentions the plugins that we need during the build process.
  • Next part is the repositories. This is the location where we include the third party libraries. Once declared, we are ready for the third party libraries. Here we are using the joda time library version 2.2 of the joda time group. This is explained in the dependencies block. Other important dependencies are:
    • providedCompile – This includes the dependencies used for compiling the project.
    • testCompile – This includes the dependencies used for compiling and running the test cases of a project.
  • In the last block we specify the name of our jar file along with its version.

 

About the Author

Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies. You can find more of his work at www.techalpine.com and you can email him here.

devx-admin

devx-admin

Share the Post:
Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles