https://github.com/openliberty/guide-gradle-intro
An introductory guide on how to build and test a simple web application using Gradle and Open Liberty: https://openliberty.io/guides/gradle-intro.html
https://github.com/openliberty/guide-gradle-intro
Last synced: about 1 year ago
JSON representation
An introductory guide on how to build and test a simple web application using Gradle and Open Liberty: https://openliberty.io/guides/gradle-intro.html
- Host: GitHub
- URL: https://github.com/openliberty/guide-gradle-intro
- Owner: OpenLiberty
- License: other
- Created: 2017-12-20T21:04:19.000Z (over 8 years ago)
- Default Branch: prod
- Last Pushed: 2025-03-05T20:06:01.000Z (over 1 year ago)
- Last Synced: 2025-03-22T21:51:07.603Z (about 1 year ago)
- Language: Java
- Homepage:
- Size: 426 KB
- Stars: 3
- Watchers: 5
- Forks: 17
- Open Issues: 3
-
Metadata Files:
- Readme: README.adoc
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
// Copyright (c) 2017, 2025 IBM Corporation and others.
// Licensed under Creative Commons Attribution-NoDerivatives
// 4.0 International (CC BY-ND 4.0)
// https://creativecommons.org/licenses/by-nd/4.0/
//
// Contributors:
// IBM Corporation
//
:projectid: gradle-intro
:page-layout: guide-multipane
:page-duration: 15 minutes
:page-description: Learn how to build and test a web application using a build configuration script, the Gradle War plug-in and Open Liberty Gradle plug-in.
:page-releasedate: 2017-12-27
:page-guide-category: basic
:page-essential: true
:page-essential-order: 2
:page-permalink: /guides/{projectid}
:page-related-guides: ['maven-intro']
:common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/prod
:page-seo-title: Building a Java web application using Gradle
:page-seo-description: A getting started tutorial with examples of how to build and test a Java web application with a Gradle build configuration script using the Gradle War plug-in and Open Liberty Gradle plug-in.
:source-highlighter: prettify
:guide-author: Open Liberty
= Building a web application with Gradle
[.hidden]
NOTE: This repository contains the guide documentation source. To view the guide in published form, view it on the https://openliberty.io/guides/{projectid}.html[Open Liberty website].
Learn how to build and test a simple web application using Gradle and Open Liberty.
== What you'll learn
You will learn how to build and test a simple web servlet application using the Gradle `war`
plug-in and the Liberty Gradle plug-in. The `war` plug-in compiles and builds the application
code. The https://github.com/WASdev/ci.gradle/blob/main/README.md[`liberty` Gradle plug-in^]
installs the Open Liberty runtime, creates an instance, and installs the application to run and test.
The application displays a simple web page with a link. When you click that link, the application
calls the servlet to return a simple response of `Hello! Is Gradle working for you?`.
One benefit of using a build tool like Gradle is that you can define the details of the project and any dependencies it has, and Gradle automatically downloads and installs the dependencies.
Another benefit of using Gradle is that it can run repeatable, automated tests on the application.
You can, of course, test your application manually by starting a Liberty instance and pointing a web browser at the application URL.
However, automated tests are a much better approach because you can easily rerun the same tests each time the application is built.
If the tests don't pass after you change the application, the build fails, and you know that you introduced a regression that requires a fix to your code.
Choosing a build tool often comes down to personal or organizational preference, but you might choose to use Gradle for several reasons.
Gradle defines its builds by using https://docs.gradle.org/current/userguide/writing_build_scripts.html[Groovy build scripts^], which gives you a lot of control and customization in your builds.
Gradle also uses a build cache that rebuilds only the parts of your application that changed, which saves build time in larger projects.
So Gradle can be a good choice in larger, more complex projects.
Using this guide, you will create a Gradle build definition file (`build.gradle`) for the
web application project, and use it to build the application. You will then create a simple,
automated test, and configure Gradle to run it after building the application.
Learn more about Gradle on the https://docs.gradle.org/current/userguide/userguide.html[official Gradle website^].
[role='command']
include::{common-includes}/gitclone.adoc[]
== Creating the application
The web application that you will build using Gradle and Open Liberty is provided for you
in the `start` directory so that you can focus on learning about Gradle. The application uses
the standard Gradle directory structure. Using this directory structure saves you from
customizing the `build.gradle` file later.
All the application source code, including the Open Liberty `server.xml` configuration file,
is in the `start/src` directory:
[source, role="no_copy"]
----
└── src
└── main
└── java
└── liberty
└── config
└── webapp
└── WEB-INF
----
== Testing Gradle
If you do not have Gradle installed, make sure that the `JAVA_HOME` environment variable is set, or that the Java application can run. Running the Gradle Wrapper automatically installs Gradle. To learn more about the Gradle Wrapper, see the https://docs.gradle.org/current/userguide/gradle_wrapper.html[Gradle Wrapper documentation^].
Run the following commands to navigate to the `start` directory and verify that Gradle was installed correctly:
include::{common-includes}/os-tabs.adoc[]
[.tab_content.windows_section]
--
[role='command']
----
cd start
gradlew.bat -v
----
--
[.tab_content.mac_section.linux_section]
--
[role='command']
----
cd start
./gradlew -v
----
--
You should see information about the Gradle installation similar to this example:
[source, role="no_copy"]
----
------------------------------------------------------------
Gradle 8.6
------------------------------------------------------------
Build time: 2024-02-02 16:47:16 UTC
Revision: d55c486870a0dc6f6278f53d21381396d0741c6e
Kotlin: 1.9.20
Groovy: 3.0.17
Ant: Apache Ant(TM) version 1.10.13 compiled on January 4 2023
JVM: 17.0.12 (Eclipse OpenJ9 openj9-0.46.0)
OS: Mac OS X 15.2 aarch64
----
== Configure your project
//file 0
settings.gradle
[source, gradle, linenums, role='code_column']
----
include::finish/settings.gradle[]
----
//file 1
build.gradle
[source, gradle, linenums, role='code_column']
----
include::finish/build.gradle[]
----
The project configuration is defined in the Gradle settings and build files.
You will create these project configurations one section at a time.
Gradle https://docs.gradle.org/current/dsl/org.gradle.api.initialization.Settings.html[settings^]
are used to instantiate and configure the project. This sample uses the [hotspot file=0]`settings.gradle`
to name the project `GradleSample`.
[role="code_command hotspot file=0", subs="quotes"]
----
#Create the Gradle settings file in the `start` directory.#
`settings.gradle`
----
This [hotspot file=0]`settings.gradle` file isn't required for a single-module Gradle project.
Without this definition, by default, the project name is set as the name of the folder in
which it is contained (`start` for this example).
Let's go through the [hotspot file=1]`build.gradle`
file so that you understand each part.
[cols="40, 100"]
|===
| *Configuration* | *Purpose*
| Plug-ins used | The first part of the build file specifies the plug-ins required to
build the project and some basic project configuration.
| buildscript | Where to find plug-ins for download.
| repositories | Where to find dependencies for download.
| dependencies | Java dependencies that are required for compiling, testing,
and running the application are included here.
| ext | Gradle extra properties extension for project level properties.
| test | Unit test and integration test configuration.
|===
[role="code_command hotspot file=1", subs="quotes"]
----
#Create the build file in the `start` directory.#
`build.gradle`
----
The first section of code defines the [hotspot=war file=1]`war` and [hotspot=liberty file=1]`liberty` plug-ins
that you want to use. The [hotspot=war file=1]`war` plug-in contains all the tasks to compile
Java files, build the WAR file structure, and assemble the archive. The [hotspot=liberty file=1]`liberty`
plug-in contains the tasks used to install the Liberty runtime and create and manage
the associated Liberty instances. The compatibility and encoding settings are for Java.
The [hotspot=buildscript file=1]`buildscript` section defines plug-in versions to use in the
build and where to find them. This guide uses the [hotspot=liberty-dependency file=1]`liberty` plug-in,
which is available from the [hotspot=buildmaven file=1]`Maven Central Repository`.
The [hotspot=repositories file=1]`repositories` section defines where to find the dependencies
that you are using in the build. For this build, everything you need is in [hotspot=maven file=1]`Maven Central`.
The [hotspot=dependencies file=1]`dependencies` section defines what is needed to compile and
test the code. This section also defines how to run the application. The
[hotspot=providedcompile file=1]`providedCompile` dependencies are APIs that are needed to compile the
application, but they do not need to be packaged with the application because Open Liberty
provides their implementation at run time. The [hotspot=testimplementation file=1]`testImplementation` dependencies
are needed to compile and run tests.
The Gradle [hotspot=ext file=1]`extra properties` extension allows you to add properties to a Gradle project.
If you use a value more than once in your build file, you can simplify updates by defining
it as a variable here and referring to the variable later in the build file.
This project defines variables for the application ports and the context-root.
You can view the default and Liberty tasks available by running the following command:
include::{common-includes}/os-tabs.adoc[]
[.tab_content.windows_section]
--
[source, role="command"]
----
gradlew.bat tasks
----
--
[.tab_content.mac_section.linux_section]
--
[source, role="command"]
----
./gradlew tasks
----
--
== Running the application
Start Open Liberty in https://openliberty.io/docs/latest/development-mode.html[dev mode^], which starts the Open Liberty instance and listens for file changes:
[role='command']
----
./gradlew libertyDev
----
After you see the following message, your Liberty instance is ready in dev mode.
[role="no_copy"]
----
**********************************************
* Liberty is running in dev mode.
----
The dev mode holds your command prompt to listen for file changes.
You need to open another command prompt to continue, or simply open the project in your editor.
Navigate your browser to the http://localhost:9080/GradleSample/servlet[^] URL to access the application.
The servlet returns a simple response of `Hello! Is Gradle working for you?`.
== Testing the web application
//file 0
EndpointIT.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/src/test/java/io/openliberty/guides/hello/it/EndpointIT.java[]
----
//file 1
build.gradle
[source, groovy, linenums, role='code_column']
----
include::finish/build.gradle[]
----
//file 2
HelloServlet.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/src/main/java/io/openliberty/guides/hello/HelloServlet.java[]
----
One of the benefits of building an application with a build system like Gradle is that
it can be configured to run a set of automated tests. The [hotspot=war file=1]`war`
plug-in extends the https://docs.gradle.org/current/userguide/java_plugin.html[Java plug-in^],
which provides test tasks. You can write tests for the individual units of code outside
of a running Liberty instance (unit tests), or you can write them to call the application
that runs on the Liberty instance (integration tests). In this example, you will create a simple
integration test that checks that the web page opens and that the correct response is
returned when the link is clicked.
[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `EndpointIT` test class.#
`src/test/java/io/openliberty/guides/hello/it/EndpointIT.java`
----
The test class name ends in `IT` to indicate that it contains an integration test.
The integration tests are put in the `it` folder by convention.
The [hotspot=tests file=1]`test` section in your build file is added by the Java plug-in, and the
[hotspot=junitplatform file=1]`useJUnitPlatform()` line configures Gradle to add JUnit 5 support.
The [hotspot=systemproperty file=1]`systemProperty` configuration defines some variables needed by
the test class. While the port number and context-root information can be
hardcoded in the test class, it is better to specify it in a single place like the Gradle
[hotspot file=1]`build.gradle` file, in case they need to change.
The [hotspot=systemproperty file=1]`systemProperty` lines passes these details to the test JVMs
as a series of system properties, resolving the [hotspot=httpport file=1]`http.port`
and [hotspot=contextroot file=1]`context.root` variables.
The [hotspot=init file=0]`init()` method in the `EndpointIT.java` test class uses these
system variables to build the URL of the application.
In the test class, after defining how to build the application URL, the [hotspot=test file=0]`@Test`
annotation indicates the start of the test method.
In the [hotspot=try file=0]`try` block of the test method, an HTTP `GET` request to the
URL of the application returns a status code. If the response to the request includes the
string `Hello! Is Gradle working for you?`, the test passes. If that string is not in the
response, the test fails. The HTTP client then disconnects from the application.
In the [hotspot=import file=0]`import` statements of this test class, you'll notice that the
test has some new dependencies. Earlier you added some [hotspot=testimplementation file=1]`testImplementation`
dependencies. The Apache [hotspot=commons file=1]`httpclient` and [hotspot=junit file=1]`org.junit`
dependencies are needed to compile and run the integration test [hotspot=endpointit file=0]`EndpointIT`
class.
The scope for each of the dependencies is set to [hotspot=testimplementation file=1]`testImplementation`
because the libraries are needed only during the Gradle test phase and do not need to be
packaged with the application.
Now, the created WAR file contains the web application, and dev mode can run any integration
test classes that it finds. Integration test classes are classes with names that end in `IT`.
The directory structure of the project in the `start` folder should now look like this
example:
[source, role="no_copy"]
----
└── build.gradle
├── settings.gradle
└── src
├── main
│ ├── java
│ ├── liberty
│ │ └── config
│ └── webapp
│ └── WEB_INF
└── test
└── java
----
=== A few more pieces
We show a few more Gradle tricks in this example with the [hotspot=openbrowser file=1]`openBrowser` task.
This task displays your application and the test report in the default browser.
The final Gradle magic to add is the task dependency directives.
The [hotspot=depends file=1]`dependency directives` organizes task execution.
In this case, the test task is set to run after the Liberty instance is started, and the
[hotspot=openbrowser file=1]`openBrowser` task is executed after the test task is finalized.
=== Running the tests
Because you started Open Liberty in dev mode at the start of the guide, press the `enter/return`
key from the command-line session where you started dev mode to run the tests.
You will see that the browser opened up the test summary page, which ran one successful test.
To see whether the test detects a failure, change the [hotspot=responsestring file=2]`response string` in the
[hotspot file=2]`src/main/java/io/openliberty/guides/hello/HelloServlet.java` file
so that it doesn't match the string that the test is looking for. Then rerun the Gradle
test to automatically restart and retest your application to check to see if the test fails.
[role='command']
include::{common-includes}/devmode-quit-ctrlc.adoc[]
== Great work! You're done!
You built and tested a web application project running on an Open Liberty instance using Gradle.
include::{common-includes}/attribution.adoc[subs="attributes"]