Install Gradle via APT on Ubuntu 24.04

Ubuntu 24.04 provides Gradle through its default APT repositories, although this version may not be the most recent. The instructions below explain how to use APT to install Gradle and its dependencies on your server.

Step 1: Refresh the Package Database

Begin by updating your system’s package index.

Step 2: Install Gradle

Use APT to install the Gradle package.

$ sudo apt install gradle -y

Step 3: Confirm the Installed Version

Verify which version of Gradle was installed.

Sample Output:

openjdk version "21.0.5" 2024-10-15
OpenJDK Runtime Environment (build 21.0.5+11-Ubuntu-1ubuntu124.04)
OpenJDK 64-Bit Server VM (build 21.0.5+11-Ubuntu-1ubuntu124.04, mixed mode, sharing)
------------------------------------------------------------
Gradle 4.4.1
------------------------------------------------------------
Build time:   2012-12-21 00:00:00 UTC
Revision:     none
Groovy:       2.4.21
Ant:          Apache Ant(TM) version 1.10.14 compiled on September 25 2023
JVM:          21.0.5 (Ubuntu 21.0.5+11-Ubuntu-1ubuntu124.04)
OS:           Linux 6.8.0-48-generic amd64

Install Gradle via Snap on Ubuntu 24.04

Gradle is also distributed through the Snap Store, which may offer newer versions with faster update cycles. Follow the steps below to install Gradle using Snap on your system.

Step 1: Install the Snap Daemon

If Snap is not already installed, use APT to install the daemon.

$ sudo apt install snapd -y

Step 2: Search for Gradle in the Snap Store

Query the Snap Store to see which Gradle versions are currently available.

Expected Output:

Name           Version   Publisher      Notes    Summary
gradle         7.2       snapcrafters✪  classic  An open-source build automation tool
gum            0.13.0    aalmiray       classic  Gum is a Gradle/Maven/Ant/Bach/JBang wrapper written in Go
jreleaser      1.0.0-M1  aalmiray       -        Release Java projects quickly and easily with JReleaser
om26er-gradle  4.7       om26er         -        Accelerate developer productivity
jrel-test      1.0.0-M9  aalmiray       -        Release projects quickly and easily with JReleaser

From the above results, version 7.2 is the available Gradle release in the Snap Store.

Step 3: Install Gradle via Snap

Run the following command to install Gradle with classic confinement.

$ sudo snap install gradle --classic

Step 4: Verify the Gradle Installation

After installation, check the Gradle version to confirm it’s working as expected.

$ sudo snap run gradle --version

Sample Output:

Welcome to Gradle 7.2!
Here are the highlights of this release:
 - Toolchain support for Scala
 - More cache hits when Java source files have platform-specific line endings
 - More resilient remote HTTP build cache behavior
For more details see https://docs.gradle.org/7.2/release-notes.html
------------------------------------------------------------
Gradle 7.2
------------------------------------------------------------

Create a Simple Java App with Gradle

Follow the instructions below to build a basic Java application using Gradle and execute it on your Ubuntu server.

Step 1: Make a New Project Directory

Create a directory named sample_project to serve as your Gradle workspace.

Step 2: Change to the Project Directory

Navigate into the newly created directory.

Step 3: Initialize a Gradle Java Application

Initialize a Java-based Gradle project with the default application structure.

$ gradle init --type java-application

Expected output:

.........  
BUILD SUCCESSFUL in 6s  
2 actionable tasks: 2 executed  
Press Enter to use the default Java version in your project.  

Starting a Gradle Daemon (subsequent builds will be faster)  

Enter target Java version (min: 7, default: 21):  
Verify your project name and press Enter.  

Project name (default: sample_project):  
Enter 1 to set up a single application project.  

Select application structure:  
  1: Single application project  
  2: Application and library project  
Enter selection (default: Single application project) [1..2]  
Select your desired build language. For example, enter 1 to select Kotlin as the build script language.  

Select build script DSL:  
  1: Kotlin  
  2: Groovy  
Enter selection (default: Kotlin) [1..2]  
Select the target test framework. For example, enter 1 to select JUnit 4.  

Select test framework:  
  1: JUnit 4  
  2: TestNG  
  3: Spock  
  4: JUnit Jupiter  
Enter selection (default: JUnit Jupiter) [1..4]  
Press yes to use new APIs with Gradle and initialize your project.  

Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no]  

Step 4: Add Your Application Source File

Create the source folder structure required to store your Java class.

Now create a Java file named App.java using a text editor like nano.

$ nano src/main/java/App.java

Insert the following Java code into the file:

public class App {
    public static void main(String[] args) {
        System.out.println("Greetings!");
    }
}

This program will print Greetings! when run.

Step 5: Edit build.gradle File

Open the build.gradle file and define the necessary plugin and application entry point.

Insert the following configuration:

plugins {
    id 'application'
}

application {
    // Define the main class
    mainClass = 'App'
}

jar {
    manifest {
        attributes(
            'Main-Class': 'App'
        )
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // Add dependencies here if needed
}

Step 6: Build the Application

Compile the Java code and package it into a .jar file using the following command:

Example output:

Calculating task graph as no cached configuration is available for tasks: build

BUILD SUCCESSFUL in 1m 12s  
12 actionable tasks: 12 executed  
Configuration cache entry stored.

Step 7: Run the Java App with Gradle

Execute the application using Gradle’s run task.

Example output:

> Task :run  
Greetings!  

> Task :app:run  
Hello World!  

BUILD SUCCESSFUL in 1s  
4 actionable tasks: 2 executed, 2 up-to-date

Step 8: Run the JAR File Manually

Use Java to manually execute the packaged application JAR.

$ java -jar build/libs/sample_project.jar App

Expected output:

Greetings!

Add Web Server Dependencies in Gradle

Gradle allows you to incorporate libraries and tools to extend your application’s capabilities. The following steps demonstrate how to add the Spark Java framework to create lightweight HTTP server functionality directly in your Java application.

Step 1: Edit build.gradle to Add Spark Java

Begin by opening the build.gradle file to modify the dependencies.

Update the dependencies block by adding the Spark Java library:

dependencies {
    // Add Spark Java for lightweight HTTP server
    implementation 'com.sparkjava:spark-core:2.9.4'
}

After modification, the full dependencies section might look like this:

dependencies {
    // Add dependencies here if needed
    // Add Spark Java for lightweight HTTP server
    implementation 'com.sparkjava:spark-core:2.9.4'
}

Step 2: Replace Your App.java File

Backup the original App.java file first.

$ mv src/main/java/App.java src/main/java/App.ORIG

Recreate the App.java file with updated web server logic:

$ nano src/main/java/App.java

Add the following Spark-based server logic to the file:

import static spark.Spark.*;

public class App {
public static void main(String[] args) {
port(8080); // Set the port number

// Define a route for the root URL
get(“/”, (req, res) -> {
res.type(“text/html”);
return “<h1>Greetings!</h1>”;
});

System.out.println(“Server is running at http://localhost:8080/”);
}
}

This version of your app initializes an HTTP server that returns a custom greeting via port 8080.

Step 3: Configure Firewall for Port 8080

Permit incoming connections on TCP port 8080 through your firewall:

Reload UFW to activate the changes:

Step 4: Run the Web Application

Execute the application using Gradle:

Example output:

> Task :run  
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".  
SLF4J: Defaulting to no-operation (NOP) logger implementation  
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.  
Server is running at http://localhost:8080/  
<====---------> 37% EXECUTING [49s]  
> :run

Open your browser and navigate to your server’s IP address at port 8080 to view the web page output.

Uninstall Gradle on Ubuntu 24.04

If you ever need to remove Gradle, follow the appropriate steps depending on your installation method.

Remove Manual Installation

Delete the Gradle binary files:

$ sudo rm -rf /opt/gradle/gradle-8.12/bin/gradle

Remove the environment variable configuration:

$ sudo rm /etc/profile.d/gradle.sh

Remove Gradle Installed via APT

If you used APT to install Gradle, use this command:

$ sudo apt autoremove gradle -y

Remove Gradle Installed via Snap

If you installed it using Snap, run:

Conclusion

You have successfully installed Gradle on Ubuntu 24.04, created and deployed a basic Java application, and integrated a lightweight web server. Gradle’s scalability and flexibility make it a powerful tool for managing builds and dependencies across diverse development environments. For additional options and configuration guidance, consult the official Gradle documentation.

Source: vultr.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: