Lab 1: Introduction to Maven and Gradle: Overview of Build Automation Tools,
Key Differences Between Maven and Gradle, Installation and Setup
Build automation is a critical part of software development. It refers to the process of automating the
creation of executable applications from source code. In Java development, build automation tools
like Maven and Gradle are widely used to simplify and streamline the build process, dependency
management, and deployment tasks.
Maven and Gradle are two popular build tools in the Java ecosystem, each with its strengths and
weaknesses. Understanding how to work with these tools is crucial for modern software
development practices.
Maven Overview
Maven is a build automation tool primarily for Java projects. It uses an XML configuration file called
pom.xml (Project Object Model) to manage the build lifecycle and dependencies. Maven simplifies
tasks like dependency management, building, packaging, and testing, and is widely used for large-
scale Java applications.
Maven Features:
Centralized Dependency Management: Automatically resolves project dependencies from a
central repository.
Project Object Model (POM): Configuration for project structure, dependencies, and build
tasks.
Extensible Plugin System: Allows the addition of custom tasks through plugins.
Repository Support: Uses Maven Central for downloading project dependencies.
Maven Lifecycle Phases:
1. validate: Validate the project structure.
2. compile: Compile the source code.
3. test: Run unit tests.
4. package: Package the compiled code into a distributable format (e.g., JAR, WAR).
5. install: Install the packaged artifact to the local repository.
6. deploy: Deploy the artifact to a remote repository for sharing with other projects.
Gradle Overview
Gradle is a modern, flexible, and powerful build automation tool. Unlike Maven, it uses a Groovy-
based Domain Specific Language (DSL) for defining builds, which makes it more concise and
expressive. Gradle is known for its incremental build approach, which improves build times.
Gradle Features:
Groovy-based DSL: Allows for more concise and readable build scripts.
Incremental Builds: Builds only the parts of the project that have changed, reducing build
times.
Multi-project Builds: Easily handles complex multi-project setups.
Extensibility: Supports custom plugins and scripts to tailor the build process.
Dependency Management: Supports Maven and Ivy repositories.
Gradle Build Lifecycle:
1. Initialization: Determines which projects will be part of the build.
2. Configuration: Configures the project tasks based on build scripts.
3. Execution: Executes the tasks that were configured.
Key Differences Between Maven and Gradle
Feature Maven Gradle
Build Script
XML (pom.xml) Groovy-based DSL (build.gradle)
Language
Flexibility Less flexible, with predefined lifecycle Highly flexible and customizable
Slower, as it doesn’t support Faster, thanks to incremental builds
Build Performance
incremental builds by default and caching
Dependency Maven Central and custom Supports Maven Central, Ivy, and
Management repositories custom repositories
Extensive, but limited to predefined Extensible, allows for custom
Plugin System
tasks plugins
Multi-Project Builds Complex and less efficient Native support, easier configuration
Easier for beginners due to
Learning Curve More difficult due to flexibility
standardization
Community and Growing community, more recent
Mature with a large community
Ecosystem tool
Installation and Setup
1. Maven Installation and Setup
Step 1: Install Java
Maven requires JDK to be installed on your system. Make sure you have Java 8 or later
installed. To verify, run:
java -version
Step 2: Download Maven
Visit Download Apache Maven – Maven and download the latest binary zip or tar file for
your system.
Step 3: Install Maven
Extract the downloaded zip/tar file to a directory, e.g., C:\apache-maven (Windows) or
/usr/local/apache-maven (Linux/Mac).
Step 4: Set Up Environment Variables
Add Maven’s bin directory to your system's PATH:
o For Windows:
Add C:\apache-maven\bin to the Path environment variable.
o For Linux/Mac:
Add the following to your .bashrc or .bash_profile:
export M2_HOME=/path/to/apache-maven
export PATH=$PATH:$M2_HOME/bin
Step 5: Verify Installation
Run the following command to verify Maven is installed correctly:
mvn -version
2. Gradle Installation and Setup
Step 1: Install Java
Ensure Java is installed on your system. Use the same method as for Maven.
Step 2: Download Gradle
Go to the Gradle Downloads Page and download the latest version of Gradle.
Step 3: Install Gradle
Extract the downloaded Gradle zip/tar file to a directory, e.g., C:\gradle (Windows) or
/opt/gradle (Linux/Mac).
Step 4: Set Up Environment Variables
Add Gradle’s bin directory to your system's PATH:
o For Windows:
Add C:\gradle\bin to the Path environment variable.
o For Linux/Mac:
Add the following to your .bashrc or .bash_profile:
export GRADLE_HOME=/path/to/gradle
export PATH=$PATH:$GRADLE_HOME/bin
Step 5: Verify Installation
Run the following command to verify Gradle is installed correctly:
gradle -v
Lab 2: Working with Maven: Creating a Maven Project, Understanding the
POM File, Dependency Management and Plugins
Maven is a powerful build automation tool that is primarily used for Java projects. It uses the Project
Object Model (POM) to define the project structure, dependencies, build configuration, and other
essential information. Maven automates the process of building and managing Java projects,
including compiling code, packaging it, running tests, and resolving dependencies.
One of the key advantages of using Maven is the dependency management system, where Maven can
automatically download, manage, and update external libraries required for the project. Additionally,
Maven is highly extensible through plugins that help automate tasks like testing, code quality checks,
and deployment.
1. Creating a Maven Project
To start working with Maven, first, create a new Maven project using the Maven Archetype Plugin.
This will help you generate a basic project structure with predefined configurations.
Step 1: Create the Project
1. Open a terminal or command prompt.
2. Run the following Maven command to create a new project:
mvn archetype:generate -DgroupId=com.example -DartifactId=myapp -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Explanation of parameters:
o -DgroupId=com.example: This specifies the group (package) ID for your project.
o -DartifactId=myapp: This is the name of your project.
o -DarchetypeArtifactId=maven-archetype-quickstart: This specifies the archetype
(template) for the project.
o -DinteractiveMode=false: Prevents Maven from prompting for input during the
project setup.
3. After executing the command, Maven will create the following directory structure:
myapp
├── pom.xml
└── src
├── main
│ └── java
│ └── com
│ └── example
│ └── App.java
└── test
└── java
└── com
└── example
└── AppTest.java
2. Understanding the POM (Project Object Model) File
The pom.xml file is the heart of any Maven project. It defines the project structure, dependencies,
plugins, build settings, and more. Let's examine a simple pom.xml file.
Basic Structure of the POM File:
Here is a basic structure of a pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myapp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Dependencies will be added here -->
</dependencies>
<build>
<plugins>
<!-- Plugins will be added here -->
</plugins>
</build>
</project>
Key Elements in the POM File:
modelVersion: Specifies the version of the POM model. Usually, this is set to 4.0.0.
groupId: The group or organization of the project (usually the reverse domain name).
artifactId: The unique name for the project or artifact.
version: The version of the artifact, often set to 1.0-SNAPSHOT during development.
dependencies: A section where external libraries (dependencies) are defined.
build: A section to configure plugins and build tasks.
3. Dependency Management in Maven
Maven allows you to manage external dependencies (such as libraries or frameworks) by declaring
them in the dependencies section of the pom.xml file. Maven will automatically download the
required libraries from a repository (usually Maven Central).
Step 1: Add Dependencies to POM
For example, let's say you want to add JUnit for unit testing. You would add the following
dependency in the dependencies section of the pom.xml file:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
In this example:
groupId: Specifies the group or organization of the dependency (JUnit in this case).
artifactId: Specifies the artifact or library name (JUnit).
version: Specifies the version of the dependency.
scope: Specifies when the dependency is needed (e.g., test scope means it will only be used
during testing).
Step 2: Resolve Dependencies
Once dependencies are added, Maven automatically downloads them from Maven Central or another
specified repository. To resolve and download dependencies, run the following command:
mvn clean install
This command will:
Clean any previous builds.
Resolve and download the dependencies.
Compile and package the project.
4. Working with Maven Plugins
Maven plugins are used to extend the functionality of Maven. They can automate tasks such as
compiling code, running tests, packaging artifacts, generating documentation, and deploying
applications.
Step 1: Adding a Plugin to the POM
To add a plugin, you need to define it in the <plugins> section of the pom.xml file. For example, to
add the Maven Compiler Plugin, which compiles your project’s Java source files, you would add
the following to the build section:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
This configuration tells Maven to use Java 8 for compiling the project.
Step 2: Using the Plugin
Once the plugin is configured, you can use it to perform tasks. For example, to compile the project
using the Maven Compiler Plugin, run:
mvn compile
This will compile the Java source files based on the configuration provided in the POM file.
5. Running Tests with Maven
Maven can run unit tests as part of the build process. If JUnit or another testing framework is defined
as a dependency, you can use the mvn test command to run the tests.
Example:
mvn test
This will:
Run the tests using the configured testing framework (e.g., JUnit).
Display the test results in the terminal.
Lab 3: Working with Gradle: Setting Up a Gradle Project, Understanding Build
Scripts (Groovy and Kotlin DSL), Dependency Management and Task
Automation
Gradle is a modern and powerful build automation tool that is widely used for Java, Groovy, Kotlin,
and other JVM-based projects. It provides features such as dependency management, multi-project
builds, and incremental builds, which help streamline the build process. One of Gradle's strengths is
its flexibility, which allows users to write build scripts using either Groovy DSL or Kotlin DSL.
Gradle enables dependency management through repositories and can automatically resolve and
download required dependencies. Additionally, Gradle’s task system allows for extensive task
automation, making it ideal for CI/CD pipelines and complex build workflows.
1. Setting Up a Gradle Project
Step 1: Install Gradle
Before starting, ensure Gradle is installed on your system. If you don’t have Gradle installed, follow
these steps:
1. Visit the Gradle installation page to download and install Gradle.
2. After installation, verify it by running the following command in the terminal:
gradle -v
This command will print the Gradle version if the installation is successful.
Step 2: Create a New Gradle Project
To create a new Gradle project, you can use Gradle's init task, which generates a basic project
structure.
1. Open a terminal/command prompt.
2. Navigate to the directory where you want to create the project.
3. Run the following command to initialize the project:
gradle init --type java-application
This command creates a basic Java application project with the following structure:
my-gradle-project/
├── build.gradle
├── settings.gradle
└── src/
├── main/
│ └── java/
│ └── App.java
└── test/
└── java/
└── AppTest.java
Step 3: Project Structure
build.gradle: The main Gradle build script, which defines the project configuration,
dependencies, and tasks.
settings.gradle: A file used to configure multi-project builds (optional for a simple project).
src/: The directory structure where your application’s source code and tests reside.
o src/main/java/: Contains your main application code.
o src/test/java/: Contains your test code.
2. Understanding Gradle Build Scripts
Gradle build scripts define how the project is built, including dependency management, tasks, and
plugins. Gradle offers two types of DSLs for writing build scripts:
Groovy DSL: The traditional DSL used by Gradle. It’s based on Groovy syntax.
Kotlin DSL: A more modern, type-safe alternative using Kotlin syntax.
Groovy DSL Example:
In the build.gradle file, the Groovy-based DSL looks like this:
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework:spring-core:5.3.8'
testImplementation 'junit:junit:4.13.2'
}
task hello {
doLast {
println 'Hello, Gradle!'
}
}
plugins: Defines the plugins used by the project, such as java for Java-based projects.
repositories: Defines the repositories where Gradle will search for dependencies (e.g., Maven
Central).
dependencies: Specifies the libraries (dependencies) needed for the project.
task hello: Defines a custom task that prints "Hello, Gradle!" when executed.
Kotlin DSL Example:
The Kotlin-based DSL (build.gradle.kts) would look like this:
plugins {
kotlin("jvm") version "1.5.10"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("junit:junit:4.13.2")
}
tasks.register("hello") {
doLast {
println("Hello, Gradle!")
}
}
The Kotlin DSL provides the advantage of type safety and IDE support, making it easier to
write and refactor build scripts.
3. Dependency Management in Gradle
Gradle automatically handles dependency management, enabling you to declare and manage external
libraries and dependencies for your project.
Step 1: Adding Dependencies
In the build.gradle file, dependencies are specified within the dependencies block. For example, to
add JUnit and Spring Framework, you can do the following:
dependencies {
implementation 'org.springframework:spring-core:5.3.8' // Spring core library
testImplementation 'junit:junit:4.13.2' // JUnit for unit testing
}
Step 2: Resolving Dependencies
After specifying the dependencies, you can resolve them using the following command:
gradle build
This command:
Resolves and downloads the dependencies.
Compiles the code.
Runs tests (if specified).
Gradle supports multiple repositories (such as Maven Central and JCenter), so you can manage
dependencies from various sources.
4. Task Automation with Gradle
Gradle automates common build tasks, such as compilation, testing, and packaging. You can also
define custom tasks specific to your project needs.
Step 1: Running Standard Gradle Tasks
Gradle provides several standard tasks for common operations:
gradle build: Builds the project by compiling the code, running tests, and creating a JAR file.
gradle test: Runs the tests in the src/test/java directory.
gradle clean: Deletes the build directory and all the artifacts generated during previous builds.
Step 2: Defining Custom Tasks
Custom tasks can be defined in the build.gradle file. For example, you can define a task to print a
message:
task hello {
doLast {
println 'Hello, Gradle!'
}
}
To execute this task, run:
gradle hello
This will print "Hello, Gradle!" in the terminal.
Step 3: Task Dependencies
Tasks can depend on other tasks, allowing for the creation of complex build workflows. For
example:
task buildApp {
dependsOn compileJava, test
doLast {
println 'Build Completed!'
}
}
Here, the buildApp task depends on compileJava and test, meaning these tasks will run before
buildApp.
Step 4: Custom Task with Kotlin DSL
The Kotlin DSL allows for the same functionality. A custom task would look like this:
kotlin
tasks.register("hello") {
doLast {
println("Hello, Gradle!")
}
}
To run this task, you can execute:
gradle hello
5. Using Plugins in Gradle
Plugins are a powerful feature of Gradle, and they can be used to add functionality such as compiling
code, packaging JARs, running tests, and deploying applications. For example, the java plugin is
commonly used for Java projects.
Step 1: Apply a Plugin
To apply the Java Plugin, add the following to the build.gradle file:
Groovy code:
plugins {
id 'java'
}
Step 2: Using Plugin Tasks
Once the java plugin is applied, Gradle automatically provides tasks like compile Java, test, and jar:
gradle build # Builds the project (compiles, tests, and packages)
gradle test # Runs the tests
gradle jar # Creates a JAR file
Lab 4: Practical Exercise: Build and Run a Java Application with Maven,
Migrate the Same Application to Gradle
In modern software development, build automation tools like Maven and Gradle are widely used to
streamline the build, dependency management, and testing processes. Both Maven and Gradle are
highly configurable and enable developers to automate common tasks such as compiling code,
running tests, packaging applications, and managing external dependencies.
Maven is XML-based and uses a declarative approach to define the build process, whereas Gradle is
more flexible and uses Groovy or Kotlin DSL for configuration. This exercise demonstrates how to
build and run a simple Java application with Maven and then migrate that same application to
Gradle. By doing this, you will learn how to work with both tools and understand their differences.
1. Build and Run a Java Application with Maven
Step 1: Set Up a Java Application
First, we will create a simple Java application using Maven.
1. Open a terminal or command prompt and create a new directory for the project:
mkdir maven-java-app
cd maven-java-app
2. Create the Maven project using the Maven archetype plugin:
mvn archetype:generate -DgroupId=com.example -DartifactId=maven-java-app -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command will generate a Maven project with the following structure:
maven-java-app/
├── pom.xml
└── src/
├── main/
│ └── java/
│ └── com/
│ └── example/
│ └── App.java
└── test/
└── java/
└── com/
└── example/
└── AppTest.java
3. Open src/main/java/com/example/App.java and modify it to make a simple application that
prints "Hello, Maven!" to the console:
package com.example;
public class App {
public static void main(String[] args) {
System.out.println("Hello, Maven!");
}
}
Step 2: Configure the pom.xml File
In Maven, the pom.xml (Project Object Model) file contains the project configuration, dependencies,
and build instructions. By default, the pom.xml file is already set up with basic information about the
project.
Here’s an example of a basic pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>maven-java-app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Add any dependencies if needed -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 3: Build and Run the Maven Application
Now that the project is set up, you can build and run the application using Maven.
1. To build the project, use the following command:
mvn clean install
This command will:
o Clean any previous builds.
o Compile the source code.
o Package the application into a JAR file.
2. To run the application, use the exec:java plugin:
mvn exec:java -Dexec.mainClass=com.example.App
This will output:
Hello, Maven!
2. Migrate the Java Application to Gradle
Step 1: Set Up a Gradle Project
Next, let's migrate the project from Maven to Gradle. Follow these steps:
1. Create a new directory for the Gradle project:
mkdir gradle-java-app
cd gradle-java-app
2. Initialize the Gradle project using the following command:
gradle init --type java-application
This will create the following structure:
gradle-java-app/
├── build.gradle
├── settings.gradle
└── src/
├── main/
│ └── java/
│ └── com/
│ └── example/
│ └── App.java
└── test/
└── java/
└── com/
└── example/
└── AppTest.java
Step 2: Modify the build.gradle File
Open the build.gradle file and configure it to match the Maven build setup. Here’s an example of a
Gradle build file for the project:
Groovy code:
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
// JUnit dependency for testing (optional)
testImplementation 'junit:junit:4.13.2'
}
s
tasks.withType(JavaCompile) {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
Step 3: Move the Java Code to Gradle
Copy the App.java file from the Maven project’s src/main/java/com/example directory to the same
location in the Gradle project. The Java code should remain unchanged:
package com.example;
public class App {
public static void main(String[] args) {
System.out.println("Hello, Gradle!");
}
}
Step 4: Build and Run the Gradle Application
Now that the Gradle project is set up, you can build and run the application.
1. To build the project and resolve dependencies, run the following command:
gradle build
2. To run the application, use the following command:
gradle run
This will output:
Hello, Gradle!
3. Comparison Between Maven and Gradle
Feature Maven Gradle
Configuration
XML (pom.xml) Groovy or Kotlin (build.gradle)
Language
Ease of Use Declarative, more rigid configuration More flexible and extensible
Feature Maven Gradle
Build Process Linear, more verbose More efficient, parallel execution
Dependency Uses pom.xml to specify Uses build.gradle to specify
Management dependencies dependencies
Custom Task Very flexible, allows defining custom
Less flexible, uses plugins and goals
Creation tasks
Slower due to XML processing and Faster due to incremental builds and
Build Speed
limited parallelism parallel execution
Community and Gaining popularity, especially for
Mature and widely used
Support Android
Lab 5: Introduction to Jenkins: What is Jenkins?, Installing Jenkins on Local or
Cloud Environment, Configuring Jenkins for First Use
Jenkins is an open-source automation server used to build, test, and deploy software continuously. It
facilitates continuous integration (CI) and continuous delivery (CD) by automating repetitive tasks in
software development. Jenkins supports various plugins, making it highly extensible for different
environments and workflows.
Features of Jenkins:
Open-source and highly customizable
Supports integration with numerous tools via plugins
Automates build, test, and deployment processes
Provides distributed builds with master-slave architecture
Supports scripting with Groovy and pipeline as code
Software and Hardware Requirements:
Software:
Java Development Kit (JDK) 8 or later
Jenkins (Latest stable version)
Web browser (Google Chrome, Mozilla Firefox, etc.)
Operating System (Windows, Linux, or macOS)
Cloud Provider (Optional: AWS, Azure, GCP, etc.)
Hardware:
Minimum 4GB RAM (Recommended 8GB or higher)
Minimum 10GB free disk space
Internet connection (for downloading dependencies)
Step 1: Installing Jenkins on Local MachineWindows:Download the Jenkins Windows Installer
(from https://www.jenkins.io).
Run the installer and follow the setup wizard.
Select the Java path when prompted.
Choose the installation directory.
After installation, Jenkins will start as a Windows service.
Open a web browser and navigate to http://localhost:8080 to access Jenkins.
Linux (Ubuntu/Debian-based):Update system packages:
sudo apt update && sudo apt upgrade -yInstall Java:
sudo apt install openjdk-11-jdk -yAdd Jenkins repository and install Jenkins:
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ >
/etc/apt/sources.list.d/jenkins.list'
sudo apt update
sudo apt install jenkins -yStart and enable Jenkins service:
sudo systemctl start jenkins
sudo systemctl enable jenkinsAccess Jenkins at http://localhost:8080.
Step 2: Installing Jenkins on Cloud Environment AWS:
Launch an EC2 instance with Ubuntu.
Configure security groups to allow port 8080.
Connect via SSH and follow Linux installation steps.
Access Jenkins using http://<EC2-Public-IP>:8080.
Azure:
Create a Virtual Machine (VM) with Ubuntu.
Open necessary ports.
Install Jenkins following Linux instructions.
GCP:
Create a Compute Engine instance.
Open firewall rules for port 8080.
Install Jenkins using Linux steps.
Step 3: Configuring Jenkins for First UseOpen a web browser and navigate to http://localhost:8080.
Retrieve the initial administrator password:
sudo cat /var/lib/jenkins/secrets/initialAdminPasswordEnter the password in the Jenkins setup page.
Choose between:
Install suggested plugins (recommended for beginners)
Select plugins manually (for advanced users)
Create an admin user by providing username, password, and email.
Set the Jenkins URL and finalize the configuration.
Click Save and Finish and start using Jenkins.
Output:
Successful installation and access to Jenkins at http://localhost:8080
Ability to log in and configure Jenkins for the first time
Result:
Jenkins was successfully installed on the local/cloud environment, and initial configuration was
completed.