/guide-liberty-deep-dive-gradle

An end-to-end tutorial on cloud-native Java application development and deployment using Jakarta EE, MicroProfile & Open Liberty.

Primary LanguageJavaOtherNOASSERTION

A Technical Deep Dive on Liberty

Note
This repository contains the documentation source. To view this exercise in published form, view it on the Open Liberty website.

Liberty is a cloud-optimized Java runtime that is fast to start up with a low memory footprint and the dev mode for quick iteration. With Liberty, adopting the latest open cloud-native Java APIs, like MicroProfile and Jakarta EE, is as simple as adding features to your server configuration. The Liberty zero migration architecture lets you focus on what’s important and not the APIs changing under you.

What you’ll learn

You will learn how to build a RESTful microservice on Liberty with Jakarta EE and MicroProfile. You will use Gradle throughout this exercise to build the microservice and to interact with the running Liberty instance. Then, you’ll build a container image for the microservice. You will also learn how to secure the REST endpoints and use JSON Web Tokens to communicate with the provided system secured microservice.

The microservice that you’ll work with is called inventory. The inventory microservice persists data into a PostgreSQL database.

Inventory microservice

Additional prerequisites

Before you begin, Podman needs to be installed before you start the Persisting Data module. For installation instructions, refer to the official Podman documentation. You will build and run the microservices in containers.

If you are running Mac or Windows, make sure to start your Podman-managed VM before you proceed.

Getting started

Clone the Git repository:

git clone https://github.com/openliberty/guide-liberty-deep-dive-gradle.git
cd guide-liberty-deep-dive-gradle

The start directory is an empty directory where you will build the inventory service.

The finish directory contains the finished projects of different modules that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Getting started with Liberty and REST

Liberty now offers an easier way to get started with developing your application: the Open Liberty Starter. This tool provides a simple and quick way to get the necessary files to start building an application on Liberty. Through this tool, you can specify your application and project name. You can also choose a build tool from either Maven or Gradle, and pick the Java SE, Jakarta EE, and MicroProfile versions for your application.

In this workshop, the starting project is provided for you or you can use the Open Liberty Starter to create the starting point of the application. Gradle is used as the selected build tool and the application uses of Jakarta EE 10 and MicroProfile 6.

To get started with this tool, see the Getting Started page: https://openliberty.io/start/

On that page, enter the following properties in the Create a starter application wizard.

  • Under Group specify: io.openliberty.deepdive

  • Under Artifact specify: inventory

  • Under Build Tool select: Gradle

  • Under Java SE Version select: your version

  • Under Java EE/Jakarta EE Version select: 10

  • Under MicroProfile Version select: 6.0

Then, click Generate Project, which downloads the starter project as inventory.zip file to the start directory of this project. You can replace the provided inventory.zip file.

Next, extract the inventory.zip file to the guide-liberty-deepdive-gradle/start/inventory directory.

Use Powershell for the following commands:

cd start
Expand-Archive -LiteralPath .\inventory.zip -DestinationPath inventory
cd start
unzip inventory.zip -d inventory

Building the application

This application is configured to be built with Gradle. Every Gradle-configured project contains a settings.gradle and a build.gradle file that defines the project configuration, dependencies, and plug-ins.

settings.gradle

link:finish/module-getting-started/settings.gradle[]

build.gradle

link:finish/module-getting-started/build.gradle[]

Your settings.gradle and build.gradle files are located in the start/inventory directory and is configured to include the io.openliberty.tools.gradle.Liberty Liberty Gradle plugin. Using the plug-in, you can install applications into Liberty and manage the associated Liberty instances.

To begin, open a command-line session and navigate to your application directory.

cd inventory

Build and deploy the inventory microservice to Liberty by running the Gradle libertyRun task:

gradlew libertyRun
./gradlew libertyRun

The gradlew command initiates a Gradle build, during which the target directory is created to store all build-related files.

The libertyRun argument specifies the Liberty run task, which starts a Liberty server instance in the foreground. As part of this phase, a Liberty server runtime is downloaded and installed into the build/wlp directory. Additionally, a server instance is created and configured in the build/wlp/usr/servers/defaultServer directory, and the application is installed into that server by using loose config.

For more information about the Liberty Gradle plug-in, see its GitHub repository.

While the server starts up, various messages display in your command-line session. Wait for the following message, which indicates that the server startup is complete:

[INFO] [AUDIT] CWWKF0011I: The server defaultServer is ready to run a smarter planet.

When you need to stop the server, press CTRL+C in the command-line session where you ran the server, or run the libertyStop goal from the start/inventory directory in another command-line session:

gradlew libertyStop
./gradlew libertyStop

Starting and stopping the Liberty server in the background

Although you can start and stop the server in the foreground by using the Gradle libertyRun task, you can also start and stop the server in the background with the Gradle libertyStart and libertyStop goals:

gradlew libertyStart
gradlew libertyStop
./gradlew libertyStart
./gradlew libertyStop

Updating the server configuration without restarting the server

The Liberty Gradle plug-in includes a dev task that listens for any changes in the project, including application source code or configuration. The Liberty server automatically reloads the configuration without restarting. This goal allows for quicker turnarounds and an improved developer experience.

If the Liberty server is running, stop it and restart it in dev mode by running the libertyDev goal in the start/inventory directory:

gradlew libertyDev
./gradlew libertyDev

After you see the following message, your application server in dev mode is ready:

**************************************************************
*    Liberty is running in dev mode.

Dev mode automatically picks up changes that you make to your application and allows you to run tests by pressing the enter/return key in the active command-line session. When you’re working on your application, rather than rerunning Gradle tasks, press the enter/return key to verify your change.

Developing a RESTful microservice

Now that a basic Liberty application is running, the next step is to create the additional application and resource classes that the application needs. Within these classes, you use Jakarta REST and other MicroProfile and Jakarta APIs.

Create the Inventory class.
src/main/java/io/openliberty/deepdive/rest/Inventory.java

Inventory.java

link:finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/Inventory.java[]

This Inventory class stores a record of all systems and their system properties. The getSystem() method within this class retrieves and returns the system data from the system. The add() method enables the addition of a system and its data to the inventory. The update() method enables a system and its data on the inventory to be updated. The removeSystem() method enables the deletion of a system from the inventory.

Create the model subdirectory, then create the SystemData class. The SystemData class is a Plain Old Java Object (POJO) that represents a single inventory entry.

mkdir src\main\java\io\openliberty\deepdive\rest\model
mkdir src/main/java/io/openliberty/deepdive/rest/model
Create the SystemData class.
src/main/java/io/openliberty/deepdive/rest/model/SystemData.java

SystemData.java

link:finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]

The SystemData class contains the hostname, operating system name, Java version, and heap size properties. The various methods within this class allow the viewing or editing the properties of each system in the inventory.

Create the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

RestApplication.java

link:finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/RestApplication.java[]

In Jakarta RESTful Web Services, a single class like the SystemResource.java class must represent a single resource, or a group of resources of the same type. In this application, a resource might be a system property, or a set of system properties. It is efficient to have a single class handle multiple different resources, but keeping a clean separation between types of resources helps with maintainability.

The @Path annotation on this class indicates that this resource responds to the /systems path in the RESTful application. The @ApplicationPath annotation in the RestApplication class, together with the @Path annotation in the SystemResource class, indicates that this resource is available at the /api/systems path.

The Jakarta RESTful Web Services API maps the HTTP methods on the URL to the methods of the class by using annotations. This application uses the GET annotation to map an HTTP GET request to the /api/systems path.

The @GET annotation on the listContents method indicates that the method is to be called for the HTTP GET method. The @Produces annotation indicates the format of the content that is returned. The value of the @Produces annotation is specified in the HTTP Content-Type response header. For this application, a JSON structure is returned for these Get methods. The Content-Type for a JSON response is application/json with MediaType.APPLICATION_JSON instead of the String content type. Using a constant such as MediaType.APPLICATION_JSON is better as in case of a spelling error, a compile failure occurs.

The Jakarta RESTful Web Services API supports a number of ways to marshal JSON. The Jakarta RESTful Web Services specification mandates JSON-Binding (JSON-B). The method body returns the result of inventory.getSystems(). Because the method is annotated with @Produces(MediaType.APPLICATION_JSON), the Jakarta RESTful Web Services API uses JSON-B to automatically convert the returned object to JSON data in the HTTP response.

Running the application

Because you started the Liberty server in dev mode at the beginning of this exercise, all the changes were automatically picked up.

Check out the service that you created at the http://localhost:9080/inventory/api/systems URL. If successful, it returns [] to you.

Documenting APIs

Next, you will investigate how to document and filter RESTful APIs from annotations, POJOs, and static OpenAPI files by using MicroProfile OpenAPI.

The OpenAPI specification, previously known as the Swagger specification, defines a standard interface for documenting and exposing RESTful APIs. This specification allows both humans and computers to understand or process the functionalities of services without requiring direct access to underlying source code or documentation. The MicroProfile OpenAPI specification provides a set of Java interfaces and programming models that allow Java developers to natively produce OpenAPI v3 documents from their RESTful applications.

build.gradle

link:finish/module-openapi/build.gradle[]

server.xml

link:finish/module-openapi/src/main/liberty/config/server.xml[]

The MicroProfile OpenAPI API is included in the microProfile dependency that is specified in your build.gradle file. The microProfile feature that includes the mpOpenAPI feature is also enabled in the server.xml file.

Generating the OpenAPI document

Because the Jakarta RESTful Web Services framework handles basic API generation for Jakarta RESTful Web Services annotations, a skeleton OpenAPI tree can be generated from the existing inventory service. You can use this tree as a starting point and augment it with annotations and code to produce a complete OpenAPI document.

To see the generated OpenAPI tree, you can either visit the http://localhost:9080/openapi URL or visit the http://localhost:9080/openapi/ui URL for a more interactive view of the APIs. Click the interactive UI link on the welcome page. Within this UI, you can view each of the endpoints that are available in your application and any schemas. Each endpoint is color coordinated to easily identify the type of each request (for example GET, POST, PUT, DELETE, etc.). Clicking each endpoint within this UI enables you to view further details of each endpoint’s parameters and responses. This UI is used for the remainder of this workshop to view and test the application endpoints.

Augmenting the existing Jakarta RESTful Web Services annotations with OpenAPI annotations

Because all Jakarta RESTful Web Services annotations are processed by default, you can augment the existing code with OpenAPI annotations without needing to rewrite portions of the OpenAPI document that are already covered by the Jakarta RESTful Web Services framework.

Replace the SystemResources class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-openapi/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

Add OpenAPI @APIResponseSchema, @APIResponses, @APIResponse, @Parameters, @Parameter, and @Operation annotations to the REST methods, listContents(), getSystem(), addSystem(), updateSystem(), removeSystem(), and addSystemClient().

Note, the @Parameter annotation can be placed either inline or outline. Examples of both are provided within this workshop.

Many OpenAPI annotations are available and can be used according to what’s best for your application and its classes. You can find all the annotations in the MicroProfile OpenAPI specification.

Because the Liberty server was started in dev mode at the beginning of this exercise, your changes were automatically picked up. Go to the http://localhost:9080/openapi URL to see the updated endpoint descriptions. The endpoints at which your REST methods are served now more meaningful:

---
openapi: 3.0.3
info:
  title: Generated API
  version: "1.0"
servers:
- url: http://localhost:9080/inventory
- url: https://localhost:9443/inventory
paths:
  /api/systems:
    get:
      summary: List contents.
      description: Returns the currently stored host:properties pairs in the inventory.
      operationId: listContents
      responses:
        "200":
          description: Returns the currently stored host:properties pairs in the inventory.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SystemData'
...

You can also visit the http://localhost:9080/openapi/ui URL to see each endpoint’s updated description. Click each of the icons within the UI to see the updated descriptions for each of the endpoints.

Augmenting POJOs with OpenAPI annotations

OpenAPI annotations can also be added to POJOs to describe what they represent. Currently, the OpenAPI document doesn’t have a meaningful description of the SystemData POJO so it’s difficult to tell exactly what this POJO is used for. To describe the SystemData POJO in more detail, augment the SystemData.java file with some OpenAPI annotations.

Replace the SystemData class.
src/main/java/io/openliberty/deepdive/rest/model/SystemData.java

SystemData.java

link:finish/module-openapi/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]

Add OpenAPI @Schema annotations to the SystemData class and the hostname variable.

Refresh the http://localhost:9080/openapi URL to see the updated OpenAPI tree. You should see much more meaningful data for the Schema:

components:
  schemas:
    SystemData:
      description: POJO that represents a single inventory entry.
      required:
      - hostname
      - properties
      type: object
      properties:
        hostname:
          type: string
        properties:
          type: object

Again, you can also view this at the http://localhost:9080/openapi/ui URL. Scroll down in the UI to the schemas section and open up the SystemData schema icon.

You can also use this UI to try out the various endpoints. In the UI, head to the POST request /api/systems. This endpoint enables you to create a system. Once you’ve opened this icon up, click the Try it out button. Now enter appropriate values for each of the required parameters and click the Execute button.

You can verify that this system was created by testing the /api/systems GET request that returns the currently stored system data in the inventory. Execute this request in the UI, then in the response body you should see your system and its data listed.

You can follow these same steps for updating and deleting systems: visiting the corresponding endpoint in the UI, executing the endpoint, and then verifying the result by using the /api/systems GET request endpoint.

You can learn more about MicroProfile OpenAPI from the Documenting RESTful APIs guide.

Configuring the microservice

Next, you can externalize your Liberty server configuration and inject configuration for your microservice by using MicroProfile Config.

Enabling configurable ports and context root

So far, you used hardcoded values to set the HTTP and HTTPS ports and the context root for the Liberty server. These configurations can be externalized so you can easily change their values when you want to deploy your microservice by different ports and context root.

Replace the server.xml file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-config/src/main/liberty/config/server.xml[]

Add variables for the HTTP port, HTTPS port, and the context root to the server.xml file. Change the httpEndpoint element to reflect the new default.http.port and default.http.port variables and change the contextRoot to use the new default.context.root variable too.

Replace the build.gradle file.
build.gradle

build.gradle

link:staging/module-config/build.gradle[]

Set the archiveVersion property to an empty string for the war task and add properties for the HTTP port, HTTPS port, and the context root to the build.gradle file.

  • liberty.server.var.'default.http.port' to 9081

  • liberty.server.var.'default.https.port' to 9445

  • liberty.server.var.'default.context.root' to /trial

Because you are using dev mode, these changes are automatically picked up by the server. After you see the following message, your application server in dev mode is ready again:

**************************************************************
*    Liberty is running in dev mode.

Now, you can access the application by the http://localhost:9081/trial/api/systems URL. Alternatively, for the updated OpenAPI UI, use the following URL http://localhost:9081/openapi/ui/.

build.gradle

link:finish/module-config/build.gradle[]

When you are finished trying out changing this configuration, change the variables back to their original values.

  • update liberty.server.var.'default.http.port' to 9080

  • update liberty.server.var.'default.https.port' to 9443

  • update liberty.server.var.'default.context.root' to /inventory

Wait until you see the following message:

**************************************************************
*    Liberty is running in dev mode.

Injecting static configuration

You can now explore how to use MicroProfile’s Config API to inject static configuration into your microservice.

The MicroProfile Config API is included in the MicroProfile dependency that is specified in your build.gradle file. Look for the dependency with the microprofile artifact ID. This dependency provides a library that allows the use of the MicroProfile Config API. The microProfile feature is also enabled in the server.xml file.

First, you need to edit the SystemResource class to inject static configuration into the CLIENT_PORT variable.

Replace the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-config/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

The @Inject annotation injects the value from other configuration sources to the CLIENT_PORT variable. The @ConfigProperty defines the external property name as client.https.port.

Update the POST request so that the /client/{hostname} endpoint prints the CLIENT_PORT value.

Adding the microprofile-config.properties file

Define the configurable variables in the microprofile-config.properties configuration file for MicroProfile Config at the src/main/resources/META-INF directory.

mkdir src\main\resources\META-INF
mkdir -p src/main/resources/META-INF
Create the microprofile-config.properties file.
src/main/resources/META-INF/microprofile-config.properties

microprofile-config.properties

link:finish/module-config/src/main/resources/META-INF/microprofile-config.properties[]

Using the config_ordinal variable in this properties file, you can set the ordinal of this file and thus other configuration sources.

The client.https.port variable enables the client port to be overwritten.

Revisit the OpenAPI UI http://localhost:9080/openapi/ui to view these changes. Open the /api/systems/client/{hostname} endpoint and run it within the UI to view the CLIENT_PORT value.

You can learn more about MicroProfile Config from the Configuring microservices guide.

Persisting data

Next, you’ll persist the system data into the PostgreSQL database by using the Jakarta Persistence API (JPA).

Navigate to your application directory.

cd start/inventory

Defining a JPA entity class

To store Java objects in a database, you must define a JPA entity class. A JPA entity is a Java object whose nontransient and nonstatic fields are persisted to the database. Any POJO class can be designated as a JPA entity. However, the class must be annotated with the @Entity annotation, must not be declared final, and must have a public or protected nonargument constructor. JPA maps an entity type to a database table and persisted instances will be represented as rows in the table.

The SystemData class is a data model that represents systems in the inventory microservice. Annotate it with JPA annotations.

Replace the SystemData class.
src/main/java/io/openliberty/deepdive/rest/model/SystemData.java

SystemData.java

link:finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]

The following table breaks down the new annotations:

Annotation Description

@Entity

Declares the class as an entity.

@Table

Specifies details of the table such as name.

@NamedQuery

Specifies a predefined database query that is run by an EntityManager instance.

@Id

Declares the primary key of the entity.

@GeneratedValue

Specifies the strategy that is used for generating the value of the primary key. The strategy = GenerationType.IDENTITY code indicates that the database automatically increments the inventoryid upon inserting it into the database.

@Column

Specifies that the field is mapped to a column in the database table. The name attribute is optional and indicates the name of the column in the table.

Performing CRUD operations using JPA

The create, retrieve, update, and delete (CRUD) operations are defined in the Inventory. To perform these operations by using JPA, you need to update the Inventory class.

Replace the Inventory class.
src/main/java/io/openliberty/deepdive/rest/Inventory.java

Inventory.java

link:finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/Inventory.java[]

To use the entity manager at run time, inject it into your CDI bean through the @PersistenceContext annotation. The entity manager interacts with the persistence context. Every EntityManager instance is associated with a persistence context. The persistence context manages a set of entities and is aware of the different states that an entity can have. The persistence context synchronizes with the database when a transaction commits.

SystemData.java

link:finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]

The Inventory class has a method for each CRUD operation, so let’s break them down:

  • The add() method persists an instance of the SystemData entity class to the data store by calling the persist() method on an EntityManager instance. The entity instance becomes managed and changes to it are tracked by the entity manager.

  • The getSystems() method demonstrates a way to retrieve system objects from the database. This method returns a list of instances of the SystemData entity class by using the SystemData.findAll query that is specified in the @NamedQuery annotation on the SystemData class. Similarly, the getSystem() method uses the SystemData.findSystem named query to find a system with the given hostname.

  • The update() method creates a managed instance of a detached entity instance. The entity manager automatically tracks all managed entity objects in its persistence context for changes and synchronizes them with the database. However, if an entity becomes detached, you must merge that entity into the persistence context by calling the merge() method so that changes to loaded fields of the detached entity are tracked.

  • The removeSystem() method removes an instance of the SystemData entity class from the database by calling the remove() method on an EntityManager instance. The state of the entity is changed to removed and is removed from the database upon transaction commit.

Declare the endpoints with transaction management.

Replace the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

The @Transactional annotation is used in the POST, PUT, and DELETE endpoints of the SystemResource class to declaratively control the transaction boundaries on the inventory CDI bean. This configuration ensures that the methods run within the boundaries of an active global transaction, and therefore you don’t need to explicitly begin, commit, or rollback transactions. At the end of the transactional method invocation, the transaction commits and the persistence context flushes any changes to the Event entity instances that it is managing to the database.

Configuring JPA

The persistence.xml file is a configuration file that defines a persistence unit. The persistence unit specifies configuration information for the entity manager.

Create the configuration file.
src/main/resources/META-INF/persistence.xml

persistence.xml

link:finish/module-persisting-data/src/main/resources/META-INF/persistence.xml[]

The persistence unit is defined by the persistence-unit XML element. The name attribute is required. This attribute identifies the persistent unit when you use the @PersistenceContext annotation to inject the entity manager later in this exercise. The transaction-type="JTA" attribute specifies to use Java Transaction API (JTA) transaction management. When you use a container-managed entity manager, you must use JTA transactions.

A JTA transaction type requires a JTA data source to be provided. The jta-data-source element specifies the Java Naming and Directory Interface (JNDI) name of the data source that is used.

Configure the jdbc/postgresql data source in the Liberty server configuration file.

Replace the server.xml configuration file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-persisting-data/src/main/liberty/config/server.xml[]

The library element tells the Liberty server where to find the PostgreSQL library. The dataSource element points to where the Java Database Connectivity (JDBC) driver connects, along with some database vendor-specific properties. For more information, see the Data source configuration and dataSource element documentation.

To use a PostgreSQL database, you need to download its library and store it to the Liberty shared resources directory. Configure the Liberty Maven plug-in in the build.gradle file.

Replace the build.gradle file.
build.gradle

build.gradle

link:finish/module-persisting-data/build.gradle[]

The postgresql dependency under the jdbcLib configuration ensures that Gradle downloads the PostgreSQL library to local project. The copyJdbcLibs task copies the library to the Liberty shared resources directory and ensures that the driver is available for the Liberty server’s use each time the project is built. To make the persistence.xml file available in the Liberty loose application configuration, set the value for the Gradle resourcesDir output directory location to be the Gradle destinationDirectory directory. The Gradle project generates the resources artifacts into the resourcesDir directory and the Java class files into the destinationDirectory directory.

Starting PostgreSQL database

Use Docker to run an instance of the PostgreSQL database for a fast installation and setup.

A container file is provided for you. First, navigate to the finish/postgres directory. Then, run the following commands to use the Dockerfile to build the image, run the image in a Docker container, and map 5432 port from the container to your machine:

cd ../../finish/postgres
podman build -t postgres-sample .
podman run --name postgres-container -p 5432:5432 -d postgres-sample

Running the application

In your dev mode console for the inventory microservice, type r and press enter/return key to restart the server.

After you see the following message, your application server in dev mode is ready again:

**************************************************************
*    Liberty is running in dev mode.

Point your browser to the http://localhost:9080/openapi/ui URL. This URL displays the available REST endpoints.

First, make a POST request to the /api/systems/ endpoint. To make this request, expand the first POST endpoint on the UI, click the Try it out button, provide values to the heapSize, hostname, javaVersion, and osName parameters, and then click the Execute button. The POST request adds a system with the specified values to the database.

Next, make a GET request to the /api/systems endpoint. To make this request, expand the GET endpoint on the UI, click the Try it out button, and then click the Execute button. The GET request returns all systems from the database.

Next, make a PUT request to the /api/systems/{hostname} endpoint. To make this request, expand the PUT endpoint on the UI, click the Try it out button. Then, provide the same value to the hostname parameter as in the previous step, provide different values to the heapSize, javaVersion, and osName parameters, and click the Execute button. The PUT request updates the system with the specified values.

To see the updated system, make a GET request to the /api/systems/{hostname} endpoint. To make this request, expand the GET endpoint on the UI, click the Try it out button, provide the same value to the hostname parameter as the previous step, and then click the Execute button. The GET request returns the system from the database.

Next, make a DELETE request to the /api/systems/{hostname} endpoint. To make this request, expand the DELETE endpoint on the UI, click the Try it out button, and then click Execute. The DELETE request removes the system from the database. Run the GET request again to see that the system no longer exists in the database.

Securing RESTful APIs

Now you can secure your RESTful APIs. Navigate to your application directory.

cd start/inventory

Begin by adding some users and user groups to your server.xml Liberty configuration file.

Replace the server.xml file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-securing/src/main/liberty/config/server.xml[]

The basicRegistry element contains a list of all users for the application and their passwords, as well as all of the user groups. Note that this basicRegistry element is a very simple case for learning purposes. For more information about the different user registries, see the User registries documentation. The admin group tells the application which of the users are in the administrator group. The user group tells the application that users are in the user group.

The security-role maps the admin role to the admin group, meaning that all users in the admin group have the administrator role. Similarly, the user role is mapped to the user group, meaning all users in the user group have the user role.

Your application has the following users and passwords:

Username

Password

Role

bob

bobpwd

admin, user

alice

alicepwd

user

Now you can secure the inventory service.

Replace the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-securing/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

This class now has role-based access control. The role names that are used in the @RolesAllowed annotations are mapped to group names in the groups claim of the JSON Web Token (JWT). This mapping results in an authorization decision wherever the security constraint is applied.

The /{hostname} endpoint that is annotated with the @PUT annotation updates a system in the inventory. This PUT endpoint is annotated with the @RolesAllowed({ "admin", "user" }) annotation. Only authenticated users with the role of admin or user can access this endpoint.

The /{hostname} endpoint that is annotated with the @DELETE annotation removes a system from the inventory. This DELETE endpoint is annotated with the @RolesAllowed({ "admin" }) annotation. Only authenticated users with the role of admin can access this endpoint.

You can manually check that the inventory microservice is secured by making requests to the PUT and DELETE endpoints.

Before making requests, you must add a system to the inventory. Try adding a system by using the POST endpoint /systems by running the following command:

curl -X POST "http://localhost:9080/inventory/api/systems?hostname=localhost&osName=mac&javaVersion=11&heapSize=1"

You can expect the following response:

{ "ok" : "localhost was added." }

This command calls the /systems endpoint and adds a system localhost to the inventory. You can validate that the command worked by calling the /systems endpoint with a GET request to retrieve all the systems in the inventory, with the following curl command:

curl -s "http://localhost:9080/inventory/api/systems"

You can now expect the following response:

[{"heapSize":1,"hostname":"localhost","javaVersion":"11","osName":"mac","id":23}]

Now try calling your secure PUT endpoint to update the system that you just added by the following curl command:

curl -k --user alice:alicepwd -X PUT "http://localhost:9080/inventory/api/systems/localhost?heapSize=2097152&javaVersion=11&osName=linux"

As this endpoint is accessible to the groups user and admin, you must log in with user credentials to update the system.

You should see the following response:

{ "ok" : "localhost was updated." }

This response means that you logged in successfully as an authenticated user, and that the endpoint works as expected.

Now try calling the DELETE endpoint. As this endpoint is only accessible to admin users, you can expect this command to fail if you attempt to access it with a user in the user group.

You can check that your application is secured against these requests with the following command:

curl -k --user alice:alicepwd -X DELETE "https://localhost:9443/inventory/api/systems/localhost"

As alice is part of the user group, this request cannot work. In your dev mode console, you can expect the following output:

jakarta.ws.rs.ForbiddenException: Unauthorized

Now attempt to call this endpoint with an authenticated admin user that can work correctly. Run the following curl command:

curl -k --user bob:bobpwd -X DELETE "https://localhost:9443/inventory/api/systems/localhost"

You can expect to see the following response:

{ "ok" : "localhost was removed." }

This response means that your endpoint is secure. Validate that it works correctly by calling the /systems endpoint with the following curl command:

curl "http://localhost:9080/inventory/api/systems"

You can expect to see the following output:

[]

This response shows that the endpoints work as expected and that the system you added was successfully deleted.

Consuming the secured RESTful APIs by JWT

You can now implement JSON Web Tokens (JWT) and configure them as Single Sign On (SSO) cookies to use the RESTful APIs. The JWT that is generated by Liberty is used to communicate securely between the inventory and system microservices. You can implement the /client/{hostname} POST endpoint to collect the properties from the system microservices and create a system in the inventory.

The system microservice is provided for you.

Writing the RESTful client interface

Create the client subdirectory. Then, create a RESTful client interface for the system microservice in the inventory microservice.

mkdir src\main\java\io\openliberty\deepdive\rest\client
mkdir src/main/java/io/openliberty/deepdive/rest/client
Create the SystemClient interface.
src/main/java/io/openliberty/deepdive/rest/client/SystemClient.java

SystemClient.java

link:finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/SystemClient.java[]

This interface declares methods for accessing each of the endpoints that are set up for you in the system service. The MicroProfile Rest Client feature automatically builds and generates a client implementation based on what is defined in the SystemClient interface. You don’t need to set up the client and connect with the remote service.

Now create the required exception classes that are used by the SystemClient instance.

Create the UnknownUriException class.
src/main/java/io/openliberty/deepdive/rest/client/UnknownUriException.java

UnknownUriException.java

link:finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/UnknownUriException.java[]

This class is an exception that is thrown when an unknown URI is passed to the SystemClient.

Create the UnknownUriExceptionMapper class.
src/main/java/io/openliberty/deepdive/rest/client/UnknownUriExceptionMapper.java

UnknownUriExceptionMapper.java

link:finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/UnknownUriExceptionMapper.java[]

This class links the UnknownUriException class with the corresponding response code through a ResponseExceptionMapper mapper class.

Implementing the /client/{hostname} endpoint

Now implement the /client/{hostname} POST endpoint of the SystemResource class to consume the secured system microservice.

Replace the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

The getSystemClient() method builds and returns a new instance of the SystemClient class for the hostname provided. The /client/{hostname} POST endpoint uses this method to create a REST client that is called customRestClient to consume the system microservice.

A JWT instance is injected to the jwt field variable by the jwtSso feature. It is used to create the authHeader authentication header. It is then passed as a parameter to the endpoints of the customRestClient to get the properties from the system microservice. A system is then added to the inventory.

Configuring the JSON Web Token

Next, add the JSON Web Token (Single Sign On) feature to the server configuration file for the inventory service.

Replace the server.xml file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-jwt/src/main/liberty/config/server.xml[]

microprofile-config.properties

link:finish/system/src/main/webapp/META-INF/microprofile-config.properties[]

The jwtSso feature adds the libraries that are required for JWT SSO implementation. Configure the jwtSso feature by adding the jwtBuilder configuration to your server.xml. Also, configure the MicroProfile JWT with the audiences and issuer properties that match the microprofile-config.properties defined at the system/src/main/webapp/META-INF directory under the system project. For more information, see the JSON Web Token Single Sign-On feature, jwtSso element, and jwtBuilder element documentation.

The keyStore element is used to define the repository of security certificates used for SSL encryption. The id attribute is a unique configuration ID that is set to defaultKeyStore. The password attribute is used to load the keystore file, and its value can be stored in clear text or encoded form. To learn more about other attributes, see the keyStore attribute documentation.

Because the keystore file is not provided at the src directory, Liberty creates a Public Key Cryptography Standards #12 (PKCS12) keystore file for you by default. This file needs to be replaced, as the keyStore configuration must be the same in both system and inventory microservices. As the configured system microservice is already provided for you, copy the key.p12 keystore file from the system microservice to your inventory service.

mkdir src\main\liberty\config\resources\security
copy ..\..\finish\system\src\main\liberty\config\resources\security\key.p12 src\main\liberty\config\resources\security\key.p12
mkdir -p src/main/liberty/config/resources/security
cp ../../finish/system/src/main/liberty/config/resources/security/key.p12 src/main/liberty/config/resources/security/key.p12

Now configure the client https port in the build.gradle configuration file.

Replace the build.gradle file.
build.gradle

build.gradle

link:finish/module-jwt/build.gradle[]

Configure the client https port by setting the liberty.server.var.'client.https.port' to 9444.

In your dev mode console for the inventory microservice, press CTRL+C to stop the server. Then, restart the dev mode of the inventory microservice.

gradlew libertyDev
./gradlew libertyDev

After you see the following message, your application server in dev mode is ready again:

**************************************************************
*    Liberty is running in dev mode.

Running the /client/{hostname} endpoint

Open another command-line session and run the system microservice from the finish directory.

cd finish\system
gradlew libertyRun
cd finish/system
./gradlew libertyRun

Wait until the following message displays on the system microservice console.

CWWKF0011I: The defaultServer server is ready to run a smarter planet. ...

You can check that the system microservice is secured against unauthenticated requests at the https://localhost:9444/system/api/heapsize URL. You can expect to see the following error in the console of the system microservice:

CWWKS5522E: The MicroProfile JWT feature cannot perform authentication because a MicroProfile JWT cannot be found in the request.

You can check that the /client/{hostname} endpoint you updated can access the system microservice.

Make an authorized request to the new /client/{hostname} endpoint. As this endpoint is restricted to admin, you can use the login credentials for bob, which is in the admin group.

curl -k --user bob:bobpwd -X POST "https://localhost:9443/inventory/api/systems/client/localhost"

You can expect the following output:

{ "ok" : "localhost was added." }

You can verify that this endpoint works as expected by running the following command:

curl "http://localhost:9080/inventory/api/systems"

You can expect to see your system listed in the output.

[
  {
    "heapSize": 2999975936,
    "hostname": "localhost",
    "id": 11,
    "javaVersion": "11.0.11",
    "osName": "Linux"
  }
]

Adding health checks

Next, you’ll use MicroProfile Health to report the health status of the microservice and PostgreSQL database connection.

Navigate to your application directory

cd start/inventory

A health report is generated automatically for all health services that enable MicroProfile Health.

All health services must provide an implementation of the HealthCheck interface, which is used to verify their health. MicroProfile Health offers health checks for startup, liveness, and readiness.

A startup check allows applications to define startup probes that are used for initial verification of the application before the liveness probe takes over. For example, a startup check might check which applications require additional startup time on their first initialization.

A liveness check allows third-party services to determine whether a microservice is running. If the liveness check fails, the application can be terminated. For example, a liveness check might fail if the application runs out of memory.

A readiness check allows third-party services, such as Kubernetes, to determine whether a microservice is ready to process requests.

Create the health subdirectory before creating the health check classes.

mkdir src\main\java\io\openliberty\deepdive\rest\health
mkdir src/main/java/io/openliberty/deepdive/rest/health
Create the StartupCheck class.
src/main/java/io/openliberty/deepdive/rest/health/StartupCheck.java

StartupCheck.java

link:finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/StartupCheck.java[]

The @Startup annotation indicates that this class is a startup health check procedure. Navigate to the http://localhost:9080/health/started URL to check the status of the startup health check. In this case, you are checking the cpu usage. If more than 95% of the cpu is being used, a status of DOWN is returned.

Create the LivenessCheck class.
src/main/java/io/openliberty/deepdive/rest/health/LivenessCheck.java

LivenessCheck.java

link:finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/LivenessCheck.java[]

The @Liveness annotation indicates that this class is a liveness health check procedure. Navigate to the http://localhost:9080/health/live URL to check the status of the liveness health check. In this case, you are checking the heap memory usage. If more than 90% of the maximum memory is being used, a status of DOWN is returned.

Create the ReadinessCheck class.
src/main/java/io/openliberty/deepdive/rest/health/ReadinessCheck.java

ReadinessCheck.java

link:finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/ReadinessCheck.java[]

The @Readiness annotation indicates that this class is a readiness health check procedure. Navigate to the http://localhost:9080/health/ready URL to check the status of the readiness health check. This readiness check tests the connection to the PostgreSQL container that was created earlier in the guide. If the connection is refused, a status of DOWN is returned.

Or, you can visit the http://localhost:9080/health URL to see the overall health status of the application.

Providing metrics

Next, you can learn how to use MicroProfile Metrics to provide metrics from the inventory microservice.

Go to your application directory.

cd start/inventory

Enable the bob user to access the /metrics endpoints.

Replace the server.xml file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-metrics/src/main/liberty/config/server.xml[]

The administrator-role configuration authorizes the bob user as an administrator.

Use annotations that are provided by MicroProfile Metrics to instrument the inventory microservice to provide application-level metrics data.

Replace the SystemResource class.
src/main/java/io/openliberty/deepdive/rest/SystemResource.java

SystemResource.java

link:finish/module-metrics/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]

Import the Counted annotation and apply it to the POST /api/systems, PUT /api/systems/{hostname}, DELETE /api/systems/{hostname}, and POST /api/systems/client/{hostname} endpoints to monotonically count how many times that the endpoints are accessed.

Additional information about the annotations that MicroProfile metrics provides, relevant metadata fields, and more are available at the MicroProfile Metrics Annotation Javadoc.

Point your browser to the http://localhost:9080/openapi/ui URL to try out your application and call some of the endpoints that you annotated.

MicroProfile Metrics provides 4 different REST endpoints.

  • The /metrics endpoint provides you with all the metrics in text format.

  • The /metrics?scope=application endpoint provides you with application-specific metrics.

  • The /metrics?scope=base endpoint provides you with metrics that are defined in MicroProfile specifications. Metrics in the base scope are intended to be portable between different MicroProfile-compatible runtimes.

  • The /metrics?scope=vendor endpoint provides you with metrics that are specific to the runtime.

Point your browser to the https://localhost:9443/metrics URL to review all the metrics that are enabled through MicroProfile Metrics. Log in with bob as your username and bobpwd as your password. You can see the metrics in text format.

To see only the application metrics, point your browser to https://localhost:9443/metrics?scope=application. You can expect to see your application metrics in the output.

# HELP updateSystem_total Number of times updating a system endpoint is called
# TYPE updateSystem_total counter
updateSystem_total{mp_scope="application",} 1.0
# HELP removeSystem_total Number of times removing a system endpoint is called
# TYPE removeSystem_total counter
removeSystem_total{mp_scope="application",} 1.0
# HELP addSystemClient_total Number of times adding a system by client is called
# TYPE addSystemClient_total counter
addSystemClient_total{mp_scope="application",} 0.0
# HELP addSystem_total Number of times adding system endpoint is called
# TYPE addSystem_total counter
addSystem_total{mp_scope="application",} 1.0

You can see the system metrics at the https://localhost:9443/metrics?scope=base URL. You can also see the vendor metrics at the https://localhost:9443/metrics?scope=vendor URL.

Building the container 

Press CTRL+C in the command-line session to stop the gradlew libertyDev dev mode that you started in the previous section.

Navigate to your application directory:

cd start/inventory

The first step to containerizing your application inside of a container is creating a Containerfile. A Containerfile is a collection of instructions for building a container image that can then be run as a container.

Make sure to start your podman daemon before you proceed.

Create the Containerfile in the start/inventory directory.
Containerfile

Containerfile

link:finish/module-kubernetes/Containerfile[]

The FROM instruction initializes a new build stage and indicates the parent image from which your image is built. In this case, you’re using the icr.io/appcafe/open-liberty:full-java11-openj9-ubi image that comes with the latest Open Liberty runtime as your parent image.

To help you manage your images, you can label your container images with the LABEL command.

The COPY instructions are structured as COPY [--chown=<user>:<group>] <source> <destination>. They copy local files into the specified destination within your container image. In this case, the first COPY instruction copies the server configuration file that is at src/main/liberty/config/server.xml to the /config/ destination directory. Similarly, the second COPY instruction copies the .war file to the /config/apps destination directory. The third COPY instruction copies the PostgreSQL library file to the Liberty shared resources directory.

Next, make the PostgreSQL database configurable in the Liberty server configuraton file.

Replace the server.xml file.
src/main/liberty/config/server.xml

server.xml

link:finish/module-kubernetes/src/main/liberty/config/server.xml[]

Instead of the hard-coded serverName, portNumber, user, and password values in the properties.postgresql properties, use ${postgres/hostname}, ${postgres/portnum}, ${postgres/username}, and ${postgres/password}, which are defined by the variable elements.

Building the container image

Run the war task from the start/inventory directory so that the .war file resides in the build/libs directory.

gradlew war
./gradlew war

Build your container image with the following commands:

podman build -t liberty-deepdive-inventory:1.0-SNAPSHOT .

When the build finishes, run the following command to list all local container images:

podman images

Verify that the liberty-deepdive-inventory:1.0-SNAPSHOT image is listed among the container images, for example:

REPOSITORY                             TAG
localhost/liberty-deepdive-inventory   1.0-SNAPSHOT
icr.io/appcafe/open-liberty            full-java11-openj9-ubi

Running the application in container

Now that the inventory container image is built, you will run the application in container with the PostgreSQL container IP address.

Retrieve the PostgreSQL container IP address by running the following command:

podman inspect -f "{{.NetworkSettings.IPAddress }}" postgres-container

The command returns the PostgreSQL container IP address:

10.88.0.10

Run the container with the PostgreSQL container IP address. If your PostgreSQL container IP address is not 10.88.0.10, replace the command with the right IP address.

podman run -d --name inventory -p 9080:9080 -e POSTGRES_HOSTNAME=10.88.0.10 liberty-deepdive-inventory:1.0-SNAPSHOT

The following table describes the flags in this command:

Flag Description

-d

Runs the container in the background.

--name

Specifies a name for the container.

-p

Maps the host ports to the container ports. For example: -p <HOST_PORT>:<CONTAINER_PORT>

-e

Sets environment variables within the container. For example: -e <VARIABLE_NAME>=<value>

Next, run the podman ps command to verify that your container is started:

podman ps

Make sure that your container is running and show Up as their status:

CONTAINER ID    IMAGE                                              COMMAND                CREATED          STATUS          PORTS                                        NAMES
2b584282e0f5    localhost/liberty-deepdive-inventory:1.0-SNAPSHOT  /opt/ol/wlp/bin/s...   8 seconds ago    Up 8 second     0.0.0.0:9080->9080/tcp   inventory

If a problem occurs and your container exit prematurely, the container don’t appear in the container list that the podman ps command displays. Instead, your container appear with an Exited status when you run the podman ps -a command. Run the podman logs inventory command to view the container logs for any potential problems. Run the podman stats inventory command to display a live stream of usage statistics for your container. You can also double-check that your Containerfile file is correct. When you find the cause of the issues, remove the faulty container with the podman rm inventory command. Rebuild your image, and start the container again.

Now, you can access the application by the http://localhost:9080/inventory/api/systems URL. Alternatively, for the updated OpenAPI UI, use the following URL http://localhost:9080/openapi/ui/.

When you’re finished trying out the application, run the following commands to stop the inventory container and the PostgreSQL container that was started in the previous section:

podman stop inventory postgres-container
podman rm inventory postgres-container

To learn how to optimize the image size, check out the Containerizing microservices with Podman guide.

Support Licensing

Open Liberty is open source under the Eclipse Public License v1 so there is no fee to use it in production. Community support is available at StackOverflow, Gitter, or the mail list, and bugs can be raised in GitHub. Commercial support is available for Open Liberty from IBM. For more information, see the IBM Marketplace. The WebSphere Liberty product is built on Open Liberty. No migration is required to use WebSphere Liberty, you simply point to WebSphere Liberty in your build. WebSphere Liberty users get support for the packaged Open Liberty function.

WebSphere Liberty is also available in Maven Central.

You can use WebSphere Liberty for development even without purchasing it. However, if you have production entitlement, you can easily change to use it with the following steps.

In the build.gradle, add the liberty element as the following:

liberty {
    runtime = [ 'group':'com.ibm.websphere.appserver.runtime',
                'name':'wlp-kernel']
}

Rebuild and restart the inventory service by dev mode:

./gradlew clean
./gradlew libertyDev

In the Containerfile, replace the Liberty image at the FROM statement with websphere-liberty as shown in the following example:

FROM icr.io/appcafe/websphere-liberty:full-java11-openj9-ubi

ARG VERSION=1.0
ARG REVISION=SNAPSHOT
...

Great work! You’re done!

You just completed a hands-on deep dive on Liberty!