A Technical Deep Dive on Liberty

duration 120 minutes
New

Prerequisites:

Liberty is a cloud-optimized Java runtime that is fast to start up with a low memory footprint and a 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 Liberty 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 Maven 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 and deploy it to Kubernetes in a Liberty Docker container. 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

Docker must be installed before you start the Persisting Data module. For installation instructions, refer to the official Docker documentation. You’ll build and run the application in Docker containers.

Make sure to start your Docker daemon before you proceed.

Also, if you are using Linux, Kubernetes must be installed before you start the Deploying the microservice to Kubernetes.

You will use Minikube as a single-node Kubernetes cluster that runs locally in a virtual machine. Make sure that you have kubectl installed. If you need to install kubectl, see the kubectl installation instructions. For Minikube installation instructions, see the Minikube documentation.

Getting started

Clone the Git repository:

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

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 Open Liberty Starter is used to create the starting point of the application. Maven 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: Maven

  • Under Java SE Version select: 17

  • Under Java EE/Jakarta EE Version select: 10.0

  • Under MicroProfile Version select: 6.1

Then, click Generate Project, which downloads the starter project as inventory.zip file.

Next, extract the inventory.zip file on your system. Move the contents of this extracted inventory directory to the start directory of this project, which is at the following path: guide-liberty-deepdive/start/inventory.

Instead of manually downloading and extracting the project, run the following commands in the start directory:

curl -o inventory.zip 'https://start.openliberty.io/api/start?a=inventory&b=maven&e=10.0&g=io.openliberty.deepdive&j=17&m=6.1'
Expand-Archive -Path .\inventory.zip
curl -o inventory.zip 'https://start.openliberty.io/api/start?a=inventory&b=maven&e=10.0&g=io.openliberty.deepdive&j=17&m=6.1'
unzip inventory.zip -d inventory

Building the application

This application is configured to be built with Maven. Every Maven-configured project contains a pom.xml file that defines the project configuration, dependencies, and plug-ins.

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5    <modelVersion>4.0.0</modelVersion>
 6
 7    <groupId>io.openliberty.deepdive</groupId>
 8    <artifactId>inventory</artifactId>
 9    <version>1.0-SNAPSHOT</version>
10    <packaging>war</packaging>
11
12    <properties>
13        <maven.compiler.source>17</maven.compiler.source>
14        <maven.compiler.target>17</maven.compiler.target>
15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16    </properties>
17
18    <dependencies>
19        <dependency>
20            <groupId>jakarta.platform</groupId>
21            <artifactId>jakarta.jakartaee-api</artifactId>
22            <version>10.0.0</version>
23            <scope>provided</scope>
24        </dependency>
25        <dependency>
26            <groupId>org.eclipse.microprofile</groupId>
27            <artifactId>microprofile</artifactId>
28            <version>6.1</version>
29            <type>pom</type>
30            <scope>provided</scope>
31        </dependency>
32    </dependencies>
33
34    <build>
35        <finalName>inventory</finalName>
36        <pluginManagement>
37            <plugins>
38                <plugin>
39                    <groupId>org.apache.maven.plugins</groupId>
40                    <artifactId>maven-war-plugin</artifactId>
41                    <version>3.3.2</version>
42                </plugin>
43                <!-- tag::libertyMavenPlugin[] -->
44                <plugin>
45                    <groupId>io.openliberty.tools</groupId>
46                    <artifactId>liberty-maven-plugin</artifactId>
47                    <version>3.10.2</version>
48                </plugin>
49                <!-- end::libertyMavenPlugin[] -->
50            </plugins>
51        </pluginManagement>
52        <plugins>
53            <plugin>
54                <groupId>io.openliberty.tools</groupId>
55                <artifactId>liberty-maven-plugin</artifactId>
56            </plugin>
57        </plugins>
58    </build>
59</project>

Your pom.xml file is located in the start/inventory directory and is configured to include the liberty-maven-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 start/inventory

Build and deploy the inventory microservice to Liberty by running the Maven liberty:run goal:

mvn liberty:run

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

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

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

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

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

When you need to stop the Liberty instance, press CTRL+C in the command-line session where you ran the Liberty.

Starting and stopping the Liberty in the background

Although you can start and stop the Liberty instance in the foreground by using the Maven liberty:run goal, you can also start and stop the instance in the background with the Maven liberty:start and liberty:stop goals:

mvn liberty:start
mvn liberty:stop

Updating the Liberty configuration without restarting the instance

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

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

mvn liberty:dev

After you see the following message, your Liberty instance is ready in dev mode:

**************************************************************
*    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 Maven commands, 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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest;
13
14import java.util.ArrayList;
15import java.util.Collections;
16import java.util.List;
17
18import io.openliberty.deepdive.rest.model.SystemData;
19import jakarta.enterprise.context.ApplicationScoped;
20
21@ApplicationScoped
22public class Inventory {
23
24    private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
25
26    public List<SystemData> getSystems() {
27        return systems;
28    }
29
30    // tag::getSystem[]
31    public SystemData getSystem(String hostname) {
32        for (SystemData s : systems) {
33            if (s.getHostname().equalsIgnoreCase(hostname)) {
34                return s;
35            }
36        }
37        return null;
38    }
39    // end::getSystem[]
40
41    // tag::add[]
42    public void add(String hostname, String osName, String javaVersion, Long heapSize) {
43        systems.add(new SystemData(hostname, osName, javaVersion, heapSize));
44    }
45    // end::add[]
46
47    // tag::update[]
48    public void update(SystemData s) {
49        for (SystemData systemData : systems) {
50            if (systemData.getHostname().equalsIgnoreCase(s.getHostname())) {
51                systemData.setOsName(s.getOsName());
52                systemData.setJavaVersion(s.getJavaVersion());
53                systemData.setHeapSize(s.getHeapSize());
54            }
55        }
56    }
57    // end::update[]
58
59    // tag::removeSystem[]
60    public boolean removeSystem(SystemData s) {
61        return systems.remove(s);
62    }
63    // end::removeSystem[]
64}

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest.model;
13
14public class SystemData {
15
16    private int id;
17    private String hostname;
18    private String osName;
19    private String javaVersion;
20    private Long   heapSize;
21
22    public SystemData() {
23    }
24
25    public SystemData(String hostname, String osName, String javaVer, Long heapSize) {
26        this.hostname = hostname;
27        this.osName = osName;
28        this.javaVersion = javaVer;
29        this.heapSize = heapSize;
30    }
31
32    public int getId() {
33        return id;
34    }
35
36    public void setId(int id) {
37        this.id = id;
38    }
39
40    public String getHostname() {
41        return hostname;
42    }
43
44    public void setHostname(String hostname) {
45        this.hostname = hostname;
46    }
47
48    public String getOsName() {
49        return osName;
50    }
51
52    public void setOsName(String osName) {
53        this.osName = osName;
54    }
55
56    public String getJavaVersion() {
57        return javaVersion;
58    }
59
60    public void setJavaVersion(String javaVersion) {
61        this.javaVersion = javaVersion;
62    }
63
64    public Long getHeapSize() {
65        return heapSize;
66    }
67
68    public void setHeapSize(Long heapSize) {
69        this.heapSize = heapSize;
70    }
71
72    @Override
73    public boolean equals(Object host) {
74      if (host instanceof SystemData) {
75        return hostname.equals(((SystemData) host).getHostname());
76      }
77      return false;
78    }
79}

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.util.List;
 15
 16import io.openliberty.deepdive.rest.model.SystemData;
 17import jakarta.enterprise.context.ApplicationScoped;
 18import jakarta.inject.Inject;
 19import jakarta.ws.rs.Consumes;
 20import jakarta.ws.rs.DELETE;
 21import jakarta.ws.rs.GET;
 22import jakarta.ws.rs.POST;
 23import jakarta.ws.rs.PUT;
 24import jakarta.ws.rs.Path;
 25import jakarta.ws.rs.PathParam;
 26import jakarta.ws.rs.Produces;
 27import jakarta.ws.rs.QueryParam;
 28import jakarta.ws.rs.core.MediaType;
 29import jakarta.ws.rs.core.Response;
 30
 31@ApplicationScoped
 32//tag::path[]
 33@Path("/systems")
 34//end::path[]
 35public class SystemResource {
 36
 37    @Inject
 38    Inventory inventory;
 39
 40    //tag::getListContents[]
 41    @GET
 42    //end::getListContents[]
 43    @Path("/")
 44    //tag::producesListContents[]
 45    @Produces(MediaType.APPLICATION_JSON)
 46    //end::producesListContents[]
 47    public List<SystemData> listContents() {
 48        //tag::getSystems[]
 49        return inventory.getSystems();
 50        //end::getSystems[]
 51    }
 52
 53    //tag::getGetSystem[]
 54    @GET
 55    //end::getGetSystem[]
 56    @Path("/{hostname}")
 57    //tag::producesGetSystem[]
 58    @Produces(MediaType.APPLICATION_JSON)
 59    //end::producesGetSystem[]
 60    public SystemData getSystem(@PathParam("hostname") String hostname) {
 61        return inventory.getSystem(hostname);
 62    }
 63
 64    @POST
 65    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 66    @Produces(MediaType.APPLICATION_JSON)
 67    public Response addSystem(
 68        @QueryParam("hostname") String hostname,
 69        @QueryParam("osName") String osName,
 70        @QueryParam("javaVersion") String javaVersion,
 71        @QueryParam("heapSize") Long heapSize) {
 72
 73        SystemData s = inventory.getSystem(hostname);
 74        if (s != null) {
 75            return fail(hostname + " already exists.");
 76        }
 77        inventory.add(hostname, osName, javaVersion, heapSize);
 78        return success(hostname + " was added.");
 79    }
 80
 81    @PUT
 82    @Path("/{hostname}")
 83    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 84    @Produces(MediaType.APPLICATION_JSON)
 85    public Response updateSystem(
 86        @PathParam("hostname") String hostname,
 87        @QueryParam("osName") String osName,
 88        @QueryParam("javaVersion") String javaVersion,
 89        @QueryParam("heapSize") Long heapSize) {
 90
 91        SystemData s = inventory.getSystem(hostname);
 92        if (s == null) {
 93            return fail(hostname + " does not exists.");
 94        }
 95        s.setOsName(osName);
 96        s.setJavaVersion(javaVersion);
 97        s.setHeapSize(heapSize);
 98        inventory.update(s);
 99        return success(hostname + " was updated.");
100    }
101
102    @DELETE
103    @Path("/{hostname}")
104    @Produces(MediaType.APPLICATION_JSON)
105    public Response removeSystem(@PathParam("hostname") String hostname) {
106        SystemData s = inventory.getSystem(hostname);
107        if (s != null) {
108            inventory.removeSystem(s);
109            return success(hostname + " was removed.");
110        } else {
111            return fail(hostname + " does not exists.");
112        }
113    }
114
115    @POST
116    @Path("/client/{hostname}")
117    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
118    @Produces(MediaType.APPLICATION_JSON)
119    public Response addSystemClient(@PathParam("hostname") String hostname) {
120        return fail("This api is not implemented yet.");
121    }
122
123    private Response success(String message) {
124        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
125    }
126
127    private Response fail(String message) {
128        return Response.status(Response.Status.BAD_REQUEST)
129                       .entity("{ \"error\" : \"" + message + "\" }")
130                       .build();
131    }
132}

RestApplication.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest;
13
14import jakarta.ws.rs.ApplicationPath;
15import jakarta.ws.rs.core.Application;
16
17//tag::applicationPath[]
18@ApplicationPath("/api")
19//end::applicationPath[]
20public class RestApplication extends Application {
21}

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 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.

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5    <modelVersion>4.0.0</modelVersion>
 6
 7    <groupId>io.openliberty.deepdive</groupId>
 8    <artifactId>inventory</artifactId>
 9    <version>1.0-SNAPSHOT</version>
10    <packaging>war</packaging>
11
12    <properties>
13        <maven.compiler.source>17</maven.compiler.source>
14        <maven.compiler.target>17</maven.compiler.target>
15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16    </properties>
17
18    <dependencies>
19        <dependency>
20            <groupId>jakarta.platform</groupId>
21            <artifactId>jakarta.jakartaee-api</artifactId>
22            <version>10.0.0</version>
23            <scope>provided</scope>
24        </dependency>
25        <!-- tag::mp5[] -->
26        <dependency>
27            <groupId>org.eclipse.microprofile</groupId>
28            <artifactId>microprofile</artifactId>
29            <version>6.1</version>
30            <type>pom</type>
31            <scope>provided</scope>
32        </dependency>
33        <!-- end::mp5[] -->
34    </dependencies>
35
36    <build>
37        <finalName>inventory</finalName>
38        <pluginManagement>
39            <plugins>
40                <plugin>
41                    <groupId>org.apache.maven.plugins</groupId>
42                    <artifactId>maven-war-plugin</artifactId>
43                    <version>3.3.2</version>
44                </plugin>
45                <plugin>
46                    <groupId>io.openliberty.tools</groupId>
47                    <artifactId>liberty-maven-plugin</artifactId>
48                    <version>3.10.2</version>
49                </plugin>
50            </plugins>
51        </pluginManagement>
52        <plugins>
53            <plugin>
54                <groupId>io.openliberty.tools</groupId>
55                <artifactId>liberty-maven-plugin</artifactId>
56            </plugin>
57        </plugins>
58    </build>
59</project>

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <!-- Enable features -->
 5    <featureManager>
 6        <feature>jakartaee-10.0</feature>
 7        <!-- tag::mp5[] -->
 8        <feature>microProfile-6.1</feature>
 9        <!-- end::mp5[] -->
10    </featureManager>
11
12    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
13    <httpEndpoint id="defaultHttpEndpoint"
14                  httpPort="9080"
15                  httpsPort="9443" />
16
17    <!-- Automatically expand WAR files and EAR files -->
18    <applicationManager autoExpand="true"/>
19
20    <!-- Configures the application on a specified context root -->
21    <webApplication contextRoot="/inventory" location="inventory.war" />
22
23    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
24    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
25</server>

The MicroProfile OpenAPI API is included in the microProfile dependency that is specified in your pom.xml file. The microProfile feature that includes the mpOpenAPI feature is also enabled in the server.xml configuration 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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.util.List;
 15
 16import org.eclipse.microprofile.openapi.annotations.Operation;
 17import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 18import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 19import org.eclipse.microprofile.openapi.annotations.media.Schema;
 20import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 22import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 25
 26import io.openliberty.deepdive.rest.model.SystemData;
 27import jakarta.enterprise.context.ApplicationScoped;
 28import jakarta.inject.Inject;
 29import jakarta.ws.rs.Consumes;
 30import jakarta.ws.rs.DELETE;
 31import jakarta.ws.rs.GET;
 32import jakarta.ws.rs.POST;
 33import jakarta.ws.rs.PUT;
 34import jakarta.ws.rs.Path;
 35import jakarta.ws.rs.PathParam;
 36import jakarta.ws.rs.Produces;
 37import jakarta.ws.rs.QueryParam;
 38import jakarta.ws.rs.core.MediaType;
 39import jakarta.ws.rs.core.Response;
 40
 41@ApplicationScoped
 42@Path("/systems")
 43public class SystemResource {
 44
 45    @Inject
 46    Inventory inventory;
 47
 48    // tag::listContents[]
 49    @GET
 50    @Path("/")
 51    @Produces(MediaType.APPLICATION_JSON)
 52    // tag::listContentsAPIResponseSchema[]
 53    @APIResponseSchema(value = SystemData.class,
 54        responseDescription = "A list of system data stored within the inventory.",
 55        responseCode = "200")
 56    // end::listContentsAPIResponseSchema[]
 57    // tag::listContentsOperation[]
 58    @Operation(
 59        summary = "List contents.",
 60        description = "Returns the currently stored system data in the inventory.",
 61        operationId = "listContents")
 62    // end::listContentsOperation[]
 63    public List<SystemData> listContents() {
 64        return inventory.getSystems();
 65    }
 66    // end::listContents[]
 67
 68    // tag::getSystem[]
 69    @GET
 70    @Path("/{hostname}")
 71    @Produces(MediaType.APPLICATION_JSON)
 72    // tag::getSystemAPIResponseSchema[]
 73    @APIResponseSchema(value = SystemData.class,
 74        responseDescription = "System data of a particular host.",
 75        responseCode = "200")
 76    // end::getSystemAPIResponseSchema[]
 77    // tag::getSystemOperation[]
 78    @Operation(
 79        summary = "Get System",
 80        description = "Retrieves and returns the system data from the system "
 81                      + "service running on the particular host.",
 82        operationId = "getSystem")
 83    // end::getSystemOperation[]
 84    public SystemData getSystem(
 85        // tag::getSystemParameter[]
 86        @Parameter(
 87            name = "hostname", in = ParameterIn.PATH,
 88            description = "The hostname of the system",
 89            required = true, example = "localhost",
 90            schema = @Schema(type = SchemaType.STRING))
 91        // end::getSystemParameter[]
 92        @PathParam("hostname") String hostname) {
 93        return inventory.getSystem(hostname);
 94    }
 95    // end::getSystem[]
 96
 97    // tag::addSystem[]
 98    @POST
 99    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
100    @Produces(MediaType.APPLICATION_JSON)
101    // tag::addSystemAPIResponses[]
102    @APIResponses(value = {
103        // tag::addSystemAPIResponse[]
104        @APIResponse(responseCode = "200",
105            description = "Successfully added system to inventory"),
106        @APIResponse(responseCode = "400",
107            description = "Unable to add system to inventory")
108        // end::addSystemAPIResponse[]
109    })
110    // end::addSystemAPIResponses[]
111    // tag::addSystemParameters[]
112    @Parameters(value = {
113        // tag::addSystemParameter[]
114        @Parameter(
115            name = "hostname", in = ParameterIn.QUERY,
116            description = "The hostname of the system",
117            required = true, example = "localhost",
118            schema = @Schema(type = SchemaType.STRING)),
119        @Parameter(
120            name = "osName", in = ParameterIn.QUERY,
121            description = "The operating system of the system",
122            required = true, example = "linux",
123            schema = @Schema(type = SchemaType.STRING)),
124        @Parameter(
125            name = "javaVersion", in = ParameterIn.QUERY,
126            description = "The Java version of the system",
127            required = true, example = "17",
128            schema = @Schema(type = SchemaType.STRING)),
129        @Parameter(
130            name = "heapSize", in = ParameterIn.QUERY,
131            description = "The heap size of the system",
132            required = true, example = "1048576",
133            schema = @Schema(type = SchemaType.NUMBER)),
134        // end::addSystemParameter[]
135    })
136    // end::addSystemParameters[]
137    // tag::addSystemOperation[]
138    @Operation(
139        summary = "Add system",
140        description = "Add a system and its data to the inventory.",
141        operationId = "addSystem"
142    )
143    // end::addSystemOperation[]
144    public Response addSystem(
145        @QueryParam("hostname") String hostname,
146        @QueryParam("osName") String osName,
147        @QueryParam("javaVersion") String javaVersion,
148        @QueryParam("heapSize") Long heapSize) {
149
150        SystemData s = inventory.getSystem(hostname);
151        if (s != null) {
152            return fail(hostname + " already exists.");
153        }
154        inventory.add(hostname, osName, javaVersion, heapSize);
155        return success(hostname + " was added.");
156    }
157    // end::addSystem[]
158
159    // tag::updateSystem[]
160    @PUT
161    @Path("/{hostname}")
162    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
163    @Produces(MediaType.APPLICATION_JSON)
164    // tag::updateSystemAPIResponses[]
165    @APIResponses(value = {
166        // tag::updateSystemAPIResponse[]
167        @APIResponse(responseCode = "200",
168            description = "Successfully updated system"),
169        @APIResponse(responseCode = "400",
170            description =
171                "Unable to update because the system does not exist in the inventory.")
172        // end::updateSystemAPIResponse[]
173    })
174    // end::updateSystemAPIResponses[]
175    // tag::updateSystemParameters[]
176    @Parameters(value = {
177        // tag::updateSystemParameter[]
178        @Parameter(
179            name = "hostname", in = ParameterIn.PATH,
180            description = "The hostname of the system",
181            required = true, example = "localhost",
182            schema = @Schema(type = SchemaType.STRING)),
183        @Parameter(
184            name = "osName", in = ParameterIn.QUERY,
185            description = "The operating system of the system",
186            required = true, example = "linux",
187            schema = @Schema(type = SchemaType.STRING)),
188        @Parameter(
189            name = "javaVersion", in = ParameterIn.QUERY,
190            description = "The Java version of the system",
191            required = true, example = "17",
192            schema = @Schema(type = SchemaType.STRING)),
193        @Parameter(
194            name = "heapSize", in = ParameterIn.QUERY,
195            description = "The heap size of the system",
196            required = true, example = "1048576",
197            schema = @Schema(type = SchemaType.NUMBER)),
198        // end::updateSystemParameter[]
199    })
200    // end::updateSystemParameters[]
201    // tag::updateSystemOperation[]
202    @Operation(
203        summary = "Update system",
204        description = "Update a system and its data on the inventory.",
205        operationId = "updateSystem"
206    )
207    // end::updateSystemOperation[]
208    public Response updateSystem(
209        @PathParam("hostname") String hostname,
210        @QueryParam("osName") String osName,
211        @QueryParam("javaVersion") String javaVersion,
212        @QueryParam("heapSize") Long heapSize) {
213
214        SystemData s = inventory.getSystem(hostname);
215        if (s == null) {
216            return fail(hostname + " does not exists.");
217        }
218        s.setOsName(osName);
219        s.setJavaVersion(javaVersion);
220        s.setHeapSize(heapSize);
221        inventory.update(s);
222        return success(hostname + " was updated.");
223    }
224    // end::updateSystem[]
225
226    // tag::removeSystem[]
227    @DELETE
228    @Path("/{hostname}")
229    @Produces(MediaType.APPLICATION_JSON)
230    // tag::removeSystemAPIResponses[]
231    @APIResponses(value = {
232        // tag::removeSystemAPIResponse[]
233        @APIResponse(responseCode = "200",
234            description = "Successfully deleted the system from inventory"),
235        @APIResponse(responseCode = "400",
236            description =
237                "Unable to delete because the system does not exist in the inventory")
238        // end::removeSystemAPIResponse[]
239    })
240    // end::removeSystemAPIResponses[]
241    // tag::removeSystemParameter[]
242    @Parameter(
243        name = "hostname", in = ParameterIn.PATH,
244        description = "The hostname of the system",
245        required = true, example = "localhost",
246        schema = @Schema(type = SchemaType.STRING)
247    )
248    // end::removeSystemParameter[]
249    // tag::removeSystemOperation[]
250    @Operation(
251        summary = "Remove system",
252        description = "Removes a system from the inventory.",
253        operationId = "removeSystem"
254    )
255    // end::removeSystemOperation[]
256    public Response removeSystem(@PathParam("hostname") String hostname) {
257        SystemData s = inventory.getSystem(hostname);
258        if (s != null) {
259            inventory.removeSystem(s);
260            return success(hostname + " was removed.");
261        } else {
262            return fail(hostname + " does not exists.");
263        }
264    }
265    // end::removeSystem[]
266
267    // tag::addSystemClient[]
268    @POST
269    @Path("/client/{hostname}")
270    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
271    @Produces(MediaType.APPLICATION_JSON)
272    // tag::addSystemClientAPIResponses[]
273    @APIResponses(value = {
274        // tag::addSystemClientAPIResponse[]
275        @APIResponse(responseCode = "200",
276            description = "Successfully added system client"),
277        @APIResponse(responseCode = "400",
278            description = "Unable to add system client")
279        // end::addSystemClientAPIResponse[]
280    })
281    // end::addSystemClientAPIResponses[]
282    // tag::addSystemClientParameter[]
283    @Parameter(
284        name = "hostname", in = ParameterIn.PATH,
285        description = "The hostname of the system",
286        required = true, example = "localhost",
287        schema = @Schema(type = SchemaType.STRING)
288    )
289    // end::addSystemClientParameter[]
290    // tag::addSystemClientOperation[]
291    @Operation(
292        summary = "Add system client",
293        description = "This adds a system client.",
294        operationId = "addSystemClient"
295    )
296    // end::addSystemClientOperation[]
297    public Response addSystemClient(@PathParam("hostname") String hostname) {
298        return fail("This api is not implemented yet.");
299    }
300    // end::addSystemClient[]
301
302    private Response success(String message) {
303        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
304    }
305
306    private Response fail(String message) {
307        return Response.status(Response.Status.BAD_REQUEST)
308                       .entity("{ \"error\" : \"" + message + "\" }")
309                       .build();
310    }
311}

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 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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest.model;
13
14import org.eclipse.microprofile.openapi.annotations.media.Schema;
15//tag::SystemDataSchema[]
16@Schema(name = "SystemData",
17        description = "POJO that represents a single inventory entry.")
18public class SystemData {
19//end::SystemDataSchema[]
20
21    private int id;
22
23    //tag::hostnameSchema[]
24    @Schema(required = true)
25    private String hostname;
26    //end::hostnameSchema[]
27
28    private String osName;
29    private String javaVersion;
30    private Long   heapSize;
31
32    public SystemData() {
33    }
34
35    public SystemData(String hostname, String osName, String javaVer, Long heapSize) {
36        this.hostname = hostname;
37        this.osName = osName;
38        this.javaVersion = javaVer;
39        this.heapSize = heapSize;
40    }
41
42    public int getId() {
43        return id;
44    }
45
46    public void setId(int id) {
47        this.id = id;
48    }
49
50    public String getHostname() {
51        return hostname;
52    }
53
54    public void setHostname(String hostname) {
55        this.hostname = hostname;
56    }
57
58    public String getOsName() {
59        return osName;
60    }
61
62    public void setOsName(String osName) {
63        this.osName = osName;
64    }
65
66    public String getJavaVersion() {
67        return javaVersion;
68    }
69
70    public void setJavaVersion(String javaVersion) {
71        this.javaVersion = javaVersion;
72    }
73
74    public Long getHeapSize() {
75        return heapSize;
76    }
77
78    public void setHeapSize(Long heapSize) {
79        this.heapSize = heapSize;
80    }
81
82    @Override
83    public boolean equals(Object host) {
84      if (host instanceof SystemData) {
85        return hostname.equals(((SystemData) host).getHostname());
86      }
87      return false;
88    }
89}

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 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. 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 Liberty server.xml configuration file.
src/main/liberty/config/server.xml

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <!-- Enable features -->
 5    <featureManager>
 6        <feature>jakartaee-10.0</feature>
 7        <feature>microProfile-6.1</feature>
 8    </featureManager>
 9
10    <!-- tag::httpPortVariable[] -->
11    <variable name="http.port" defaultValue="9080" />
12    <!-- end::httpPortVariable[] -->
13    <!-- tag::httpsPortVariable[] -->
14    <variable name="https.port" defaultValue="9443" />
15    <!-- end::httpsPortVariable[] -->
16    <!-- tag::contextRootVariable[] -->
17    <variable name="context.root" defaultValue="/inventory" />
18    <!-- end::contextRootVariable[] -->
19
20    <!-- To access this server from a remote client,
21         add a host attribute to the following element, e.g. host="*" -->
22    <!-- tag::editedHttpEndpoint[] -->
23    <httpEndpoint id="defaultHttpEndpoint"
24                  httpPort="${http.port}" 
25                  httpsPort="${https.port}" />
26    <!-- end::editedHttpEndpoint[] -->
27    
28    <!-- Automatically expand WAR files and EAR files -->
29    <applicationManager autoExpand="true"/>
30
31    <!-- Configures the application on a specified context root -->
32    <!-- tag::editedContextRoot[] -->
33    <webApplication contextRoot="${context.root}" 
34                    location="inventory.war" /> 
35    <!-- end::editedContextRoot[] -->
36
37    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
38    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
39</server>

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

Replace the pom.xml file.
pom.xml

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5    <modelVersion>4.0.0</modelVersion>
 6
 7    <groupId>io.openliberty.deepdive</groupId>
 8    <artifactId>inventory</artifactId>
 9    <version>1.0-SNAPSHOT</version>
10    <packaging>war</packaging>
11
12    <properties>
13        <maven.compiler.source>17</maven.compiler.source>
14        <maven.compiler.target>17</maven.compiler.target>
15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16        <!-- tag::httpPort[] -->
17        <liberty.var.http.port>9081</liberty.var.http.port>
18        <!-- end::httpPort[] -->
19        <!-- tag::httpsPort[] -->
20        <liberty.var.https.port>9445</liberty.var.https.port>
21        <!-- end::httpsPort[] -->
22        <!-- tag::contextRoot[] -->
23        <liberty.var.context.root>/trial</liberty.var.context.root>
24        <!-- end::contextRoot[] -->
25    </properties>
26
27    <dependencies>
28        <dependency>
29            <groupId>jakarta.platform</groupId>
30            <artifactId>jakarta.jakartaee-api</artifactId>
31            <version>10.0.0</version>
32            <scope>provided</scope>
33        </dependency>
34        <dependency>
35            <groupId>org.eclipse.microprofile</groupId>
36            <artifactId>microprofile</artifactId>
37            <version>6.1</version>
38            <type>pom</type>
39            <scope>provided</scope>
40        </dependency>
41    </dependencies>
42
43    <build>
44        <finalName>inventory</finalName>
45        <pluginManagement>
46            <plugins>
47                <plugin>
48                    <groupId>org.apache.maven.plugins</groupId>
49                    <artifactId>maven-war-plugin</artifactId>
50                    <version>3.3.2</version>
51                </plugin>
52                <plugin>
53                    <groupId>io.openliberty.tools</groupId>
54                    <artifactId>liberty-maven-plugin</artifactId>
55                    <version>3.10.2</version>
56                </plugin>
57            </plugins>
58        </pluginManagement>
59        <plugins>
60            <plugin>
61                <groupId>io.openliberty.tools</groupId>
62                <artifactId>liberty-maven-plugin</artifactId>
63            </plugin>
64        </plugins>
65    </build>
66</project>

Add properties for the HTTP port, HTTPS port, and the context root to the pom.xml file.

  • liberty.var.http.port to 9081

  • liberty.var.https.port to 9445

  • liberty.var.context.root to /trial.

Because you are using dev mode, these changes are automatically picked up by the Liberty instance.

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/.

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

  • update liberty.var.http.port to 9080

  • update liberty.var.https.port to 9443

  • update liberty.var.context.root to /inventory.

Replace the pom.xml file.
pom.xml

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5    <modelVersion>4.0.0</modelVersion>
 6
 7    <groupId>io.openliberty.deepdive</groupId>
 8    <artifactId>inventory</artifactId>
 9    <version>1.0-SNAPSHOT</version>
10    <packaging>war</packaging>
11
12    <properties>
13        <maven.compiler.source>17</maven.compiler.source>
14        <maven.compiler.target>17</maven.compiler.target>
15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16        <!-- tag::httpPort[] -->
17        <liberty.var.http.port>9080</liberty.var.http.port>
18        <!-- end::httpPort[] -->
19        <!-- tag::httpsPort[] -->
20        <liberty.var.https.port>9443</liberty.var.https.port>
21        <!-- end::httpsPort[] -->
22        <!-- tag::contextRoot[] -->
23        <liberty.var.context.root>/inventory</liberty.var.context.root>
24        <!-- end::contextRoot[] -->
25    </properties>
26
27    <dependencies>
28        <dependency>
29            <groupId>jakarta.platform</groupId>
30            <artifactId>jakarta.jakartaee-api</artifactId>
31            <version>10.0.0</version>
32            <scope>provided</scope>
33        </dependency>
34        <dependency>
35            <groupId>org.eclipse.microprofile</groupId>
36            <artifactId>microprofile</artifactId>
37            <version>6.1</version>
38            <type>pom</type>
39            <scope>provided</scope>
40        </dependency>
41    </dependencies>
42
43    <build>
44        <finalName>inventory</finalName>
45        <pluginManagement>
46            <plugins>
47                <plugin>
48                    <groupId>org.apache.maven.plugins</groupId>
49                    <artifactId>maven-war-plugin</artifactId>
50                    <version>3.3.2</version>
51                </plugin>
52                <plugin>
53                    <groupId>io.openliberty.tools</groupId>
54                    <artifactId>liberty-maven-plugin</artifactId>
55                    <version>3.10.2</version>
56                </plugin>
57            </plugins>
58        </pluginManagement>
59        <plugins>
60            <plugin>
61                <groupId>io.openliberty.tools</groupId>
62                <artifactId>liberty-maven-plugin</artifactId>
63            </plugin>
64        </plugins>
65    </build>
66</project>

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 pom.xml 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 configuration 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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.util.List;
 15
 16import org.eclipse.microprofile.openapi.annotations.Operation;
 17import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 18import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 19import org.eclipse.microprofile.openapi.annotations.media.Schema;
 20import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 22import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 25
 26import org.eclipse.microprofile.config.inject.ConfigProperty;
 27
 28import io.openliberty.deepdive.rest.model.SystemData;
 29import jakarta.enterprise.context.ApplicationScoped;
 30import jakarta.inject.Inject;
 31import jakarta.ws.rs.Consumes;
 32import jakarta.ws.rs.DELETE;
 33import jakarta.ws.rs.GET;
 34import jakarta.ws.rs.POST;
 35import jakarta.ws.rs.PUT;
 36import jakarta.ws.rs.Path;
 37import jakarta.ws.rs.PathParam;
 38import jakarta.ws.rs.Produces;
 39import jakarta.ws.rs.QueryParam;
 40import jakarta.ws.rs.core.MediaType;
 41import jakarta.ws.rs.core.Response;
 42
 43@ApplicationScoped
 44@Path("/systems")
 45public class SystemResource {
 46
 47    @Inject
 48    Inventory inventory;
 49
 50    // tag::inject[]
 51    @Inject
 52    // end::inject[]
 53    // tag::configProperty[]
 54    @ConfigProperty(name = "client.https.port")
 55    // end::configProperty[]
 56    String CLIENT_PORT;
 57
 58
 59    @GET
 60    @Path("/")
 61    @Produces(MediaType.APPLICATION_JSON)
 62    @APIResponseSchema(value = SystemData.class,
 63        responseDescription = "A list of system data stored within the inventory.",
 64        responseCode = "200")
 65    @Operation(
 66        summary = "List contents.",
 67        description = "Returns the currently stored system data in the inventory.",
 68        operationId = "listContents")
 69    public List<SystemData> listContents() {
 70        return inventory.getSystems();
 71    }
 72
 73    @GET
 74    @Path("/{hostname}")
 75    @Produces(MediaType.APPLICATION_JSON)
 76    @APIResponseSchema(value = SystemData.class,
 77        responseDescription = "System data of a particular host.",
 78        responseCode = "200")
 79    @Operation(
 80        summary = "Get System",
 81        description = "Retrieves and returns the system data from the system "
 82        + "service running on the particular host.",
 83        operationId = "getSystem"
 84    )
 85    public SystemData getSystem(
 86        @Parameter(
 87            name = "hostname", in = ParameterIn.PATH,
 88            description = "The hostname of the system",
 89            required = true, example = "localhost",
 90            schema = @Schema(type = SchemaType.STRING)
 91        )
 92        @PathParam("hostname") String hostname) {
 93        return inventory.getSystem(hostname);
 94    }
 95
 96    @POST
 97    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 98    @Produces(MediaType.APPLICATION_JSON)
 99    @APIResponses(value = {
100        @APIResponse(responseCode = "200",
101            description = "Successfully added system to inventory"),
102        @APIResponse(responseCode = "400",
103            description = "Unable to add system to inventory")
104    })
105    @Parameters(value = {
106        @Parameter(
107            name = "hostname", in = ParameterIn.QUERY,
108            description = "The hostname of the system",
109            required = true, example = "localhost",
110            schema = @Schema(type = SchemaType.STRING)),
111        @Parameter(
112            name = "osName", in = ParameterIn.QUERY,
113            description = "The operating system of the system",
114            required = true, example = "linux",
115            schema = @Schema(type = SchemaType.STRING)),
116        @Parameter(
117            name = "javaVersion", in = ParameterIn.QUERY,
118            description = "The Java version of the system",
119            required = true, example = "17",
120            schema = @Schema(type = SchemaType.STRING)),
121        @Parameter(
122            name = "heapSize", in = ParameterIn.QUERY,
123            description = "The heap size of the system",
124            required = true, example = "1048576",
125            schema = @Schema(type = SchemaType.NUMBER)),
126    })
127    @Operation(
128        summary = "Add system",
129        description = "Add a system and its data to the inventory.",
130        operationId = "addSystem"
131    )
132    public Response addSystem(
133        @QueryParam("hostname") String hostname,
134        @QueryParam("osName") String osName,
135        @QueryParam("javaVersion") String javaVersion,
136        @QueryParam("heapSize") Long heapSize) {
137
138        SystemData s = inventory.getSystem(hostname);
139        if (s != null) {
140            return fail(hostname + " already exists.");
141        }
142        inventory.add(hostname, osName, javaVersion, heapSize);
143        return success(hostname + " was added.");
144    }
145
146    @PUT
147    @Path("/{hostname}")
148    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
149    @Produces(MediaType.APPLICATION_JSON)
150    @APIResponses(value = {
151        @APIResponse(responseCode = "200",
152            description = "Successfully updated system"),
153        @APIResponse(responseCode = "400",
154           description =
155               "Unable to update because the system does not exist in the inventory.")
156    })
157    @Parameters(value = {
158        @Parameter(
159            name = "hostname", in = ParameterIn.PATH,
160            description = "The hostname of the system",
161            required = true, example = "localhost",
162            schema = @Schema(type = SchemaType.STRING)),
163        @Parameter(
164            name = "osName", in = ParameterIn.QUERY,
165            description = "The operating system of the system",
166            required = true, example = "linux",
167            schema = @Schema(type = SchemaType.STRING)),
168        @Parameter(
169            name = "javaVersion", in = ParameterIn.QUERY,
170            description = "The Java version of the system",
171            required = true, example = "17",
172            schema = @Schema(type = SchemaType.STRING)),
173        @Parameter(
174            name = "heapSize", in = ParameterIn.QUERY,
175            description = "The heap size of the system",
176            required = true, example = "1048576",
177            schema = @Schema(type = SchemaType.NUMBER)),
178    })
179    @Operation(
180        summary = "Update system",
181        description = "Update a system and its data on the inventory.",
182        operationId = "updateSystem"
183    )
184    public Response updateSystem(
185        @PathParam("hostname") String hostname,
186        @QueryParam("osName") String osName,
187        @QueryParam("javaVersion") String javaVersion,
188        @QueryParam("heapSize") Long heapSize) {
189
190        SystemData s = inventory.getSystem(hostname);
191        if (s == null) {
192            return fail(hostname + " does not exists.");
193        }
194        s.setOsName(osName);
195        s.setJavaVersion(javaVersion);
196        s.setHeapSize(heapSize);
197        inventory.update(s);
198        return success(hostname + " was updated.");
199    }
200
201    @DELETE
202    @Path("/{hostname}")
203    @Produces(MediaType.APPLICATION_JSON)
204    @APIResponses(value = {
205        @APIResponse(responseCode = "200",
206            description = "Successfully deleted the system from inventory"),
207        @APIResponse(responseCode = "400",
208            description =
209                "Unable to delete because the system does not exist in the inventory")
210    })
211    @Parameter(
212        name = "hostname", in = ParameterIn.PATH,
213        description = "The hostname of the system",
214        required = true, example = "localhost",
215        schema = @Schema(type = SchemaType.STRING)
216    )
217    @Operation(
218        summary = "Remove system",
219        description = "Removes a system from the inventory.",
220        operationId = "removeSystem"
221    )
222    public Response removeSystem(@PathParam("hostname") String hostname) {
223        SystemData s = inventory.getSystem(hostname);
224        if (s != null) {
225            inventory.removeSystem(s);
226            return success(hostname + " was removed.");
227        } else {
228            return fail(hostname + " does not exists.");
229        }
230    }
231
232    @POST
233    @Path("/client/{hostname}")
234    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
235    @Produces(MediaType.APPLICATION_JSON)
236    @APIResponses(value = {
237        @APIResponse(responseCode = "200",
238            description = "Successfully added system client"),
239        @APIResponse(responseCode = "400",
240            description = "Unable to add system client")
241    })
242    @Parameter(
243        name = "hostname", in = ParameterIn.PATH,
244        description = "The hostname of the system",
245        required = true, example = "localhost",
246        schema = @Schema(type = SchemaType.STRING)
247    )
248    @Operation(
249        summary = "Add system client",
250        description = "This adds a system client.",
251        operationId = "addSystemClient"
252    )
253    //tag::printClientPort[]
254    public Response addSystemClient(@PathParam("hostname") String hostname) {
255        System.out.println(CLIENT_PORT);
256        return success("Client Port: " + CLIENT_PORT);
257    }
258    //end::printClientPort[]
259
260    private Response success(String message) {
261        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
262    }
263
264    private Response fail(String message) {
265        return Response.status(Response.Status.BAD_REQUEST)
266                       .entity("{ \"error\" : \"" + message + "\" }")
267                       .build();
268    }
269}

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

1# tag::ordinal[]
2config_ordinal=100
3# end::ordinal[]
4
5# tag::configPort[]
6client.https.port=5555
7# end::configPort[]

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest.model;
 13
 14import java.io.Serializable;
 15
 16import org.eclipse.microprofile.openapi.annotations.media.Schema;
 17
 18import jakarta.persistence.Column;
 19import jakarta.persistence.Entity;
 20import jakarta.persistence.GeneratedValue;
 21import jakarta.persistence.GenerationType;
 22import jakarta.persistence.Id;
 23import jakarta.persistence.NamedQuery;
 24import jakarta.persistence.SequenceGenerator;
 25import jakarta.persistence.Table;
 26
 27@Schema(name = "SystemData",
 28        description = "POJO that represents a single inventory entry.")
 29// tag::Entity[]
 30@Entity
 31// end::Entity[]
 32// tag::Table[]
 33@Table(name = "SystemData")
 34// end::Table[]
 35// tag::findAll[]
 36@NamedQuery(name = "SystemData.findAll", query = "SELECT e FROM SystemData e")
 37//end::findAll[]
 38//tag::findSystem[]
 39@NamedQuery(name = "SystemData.findSystem",
 40            query = "SELECT e FROM SystemData e WHERE e.hostname = :hostname")
 41// end::findSystem[]
 42// tag::SystemData[]
 43public class SystemData implements Serializable {
 44    private static final long serialVersionUID = 1L;
 45
 46    // tag::GeneratedValue[]
 47    @SequenceGenerator(name = "SEQ",
 48                       sequenceName = "systemData_id_seq",
 49                       allocationSize = 1)
 50    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SEQ")
 51    // end::GeneratedValue[]
 52    // tag::Id[]
 53    @Id
 54    // end::Id[]
 55    // tag::columnId[]
 56    @Column(name = "id")
 57    // end::columnId[]
 58    private int id;
 59
 60    @Schema(required = true)
 61    // tag::columnHostname[]
 62    @Column(name = "hostname")
 63    // end::columnHostname[]
 64    private String hostname;
 65
 66    // tag::columnOsName[]
 67    @Column(name = "osName")
 68    // end::columnOsName[]
 69    private String osName;
 70    // tag::columnJavaVersion[]
 71    @Column(name = "javaVersion")
 72    // end::columnJavaVersion[]
 73    private String javaVersion;
 74    // tag::columnHeapSize[]
 75    @Column(name = "heapSize")
 76    // end::columnHeapSize[]
 77    private Long heapSize;
 78
 79    public SystemData() {
 80    }
 81
 82    public SystemData(String hostname, String osName, String javaVer, Long heapSize) {
 83        this.hostname = hostname;
 84        this.osName = osName;
 85        this.javaVersion = javaVer;
 86        this.heapSize = heapSize;
 87    }
 88
 89    public int getId() {
 90        return id;
 91    }
 92
 93    public void setId(int id) {
 94        this.id = id;
 95    }
 96
 97    public String getHostname() {
 98        return hostname;
 99    }
100
101    public void setHostname(String hostname) {
102        this.hostname = hostname;
103    }
104
105    public String getOsName() {
106        return osName;
107    }
108
109    public void setOsName(String osName) {
110        this.osName = osName;
111    }
112
113    public String getJavaVersion() {
114        return javaVersion;
115    }
116
117    public void setJavaVersion(String javaVersion) {
118        this.javaVersion = javaVersion;
119    }
120
121    public Long getHeapSize() {
122        return heapSize;
123    }
124
125    public void setHeapSize(Long heapSize) {
126        this.heapSize = heapSize;
127    }
128
129    @Override
130    public int hashCode() {
131        return hostname.hashCode();
132    }
133
134    @Override
135    public boolean equals(Object host) {
136        if (host instanceof SystemData) {
137            return hostname.equals(((SystemData) host).getHostname());
138        }
139        return false;
140    }
141}
142// end::SystemData[]

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest;
13
14import java.util.List;
15
16import io.openliberty.deepdive.rest.model.SystemData;
17import jakarta.enterprise.context.ApplicationScoped;
18import jakarta.persistence.EntityManager;
19import jakarta.persistence.PersistenceContext;
20
21@ApplicationScoped
22// tag::Inventory[]
23public class Inventory {
24
25    // tag::PersistenceContext[]
26    @PersistenceContext(name = "jpa-unit")
27    // end::PersistenceContext[]
28    private EntityManager em;
29
30    // tag::getSystems[]
31    public List<SystemData> getSystems() {
32        return em.createNamedQuery("SystemData.findAll", SystemData.class)
33                 .getResultList();
34    }
35    // end::getSystems[]
36
37    // tag::getSystem[]
38    public SystemData getSystem(String hostname) {
39        // tag::find[]
40        List<SystemData> systems =
41            em.createNamedQuery("SystemData.findSystem", SystemData.class)
42              .setParameter("hostname", hostname)
43              .getResultList();
44        return systems == null || systems.isEmpty() ? null : systems.get(0);
45        // end::find[]
46    }
47    // end::getSystem[]
48
49    // tag::add[]
50    public void add(String hostname, String osName, String javaVersion, Long heapSize) {
51        // tag::Persist[]
52        em.persist(new SystemData(hostname, osName, javaVersion, heapSize));
53        // end::Persist[]
54    }
55    // end::add[]
56
57    // tag::update[]
58    public void update(SystemData s) {
59        // tag::Merge[]
60        em.merge(s);
61        // end::Merge[]
62    }
63    // end::update[]
64
65    // tag::removeSystem[]
66    public void removeSystem(SystemData s) {
67        // tag::Remove[]
68        em.remove(s);
69        // end::Remove[]
70    }
71    // end::removeSystem[]
72
73}
74// end::Inventory[]

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest.model;
 13
 14import java.io.Serializable;
 15
 16import org.eclipse.microprofile.openapi.annotations.media.Schema;
 17
 18import jakarta.persistence.Column;
 19import jakarta.persistence.Entity;
 20import jakarta.persistence.GeneratedValue;
 21import jakarta.persistence.GenerationType;
 22import jakarta.persistence.Id;
 23import jakarta.persistence.NamedQuery;
 24import jakarta.persistence.SequenceGenerator;
 25import jakarta.persistence.Table;
 26
 27@Schema(name = "SystemData",
 28        description = "POJO that represents a single inventory entry.")
 29// tag::Entity[]
 30@Entity
 31// end::Entity[]
 32// tag::Table[]
 33@Table(name = "SystemData")
 34// end::Table[]
 35// tag::findAll[]
 36@NamedQuery(name = "SystemData.findAll", query = "SELECT e FROM SystemData e")
 37//end::findAll[]
 38//tag::findSystem[]
 39@NamedQuery(name = "SystemData.findSystem",
 40            query = "SELECT e FROM SystemData e WHERE e.hostname = :hostname")
 41// end::findSystem[]
 42// tag::SystemData[]
 43public class SystemData implements Serializable {
 44    private static final long serialVersionUID = 1L;
 45
 46    // tag::GeneratedValue[]
 47    @SequenceGenerator(name = "SEQ",
 48                       sequenceName = "systemData_id_seq",
 49                       allocationSize = 1)
 50    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SEQ")
 51    // end::GeneratedValue[]
 52    // tag::Id[]
 53    @Id
 54    // end::Id[]
 55    // tag::columnId[]
 56    @Column(name = "id")
 57    // end::columnId[]
 58    private int id;
 59
 60    @Schema(required = true)
 61    // tag::columnHostname[]
 62    @Column(name = "hostname")
 63    // end::columnHostname[]
 64    private String hostname;
 65
 66    // tag::columnOsName[]
 67    @Column(name = "osName")
 68    // end::columnOsName[]
 69    private String osName;
 70    // tag::columnJavaVersion[]
 71    @Column(name = "javaVersion")
 72    // end::columnJavaVersion[]
 73    private String javaVersion;
 74    // tag::columnHeapSize[]
 75    @Column(name = "heapSize")
 76    // end::columnHeapSize[]
 77    private Long heapSize;
 78
 79    public SystemData() {
 80    }
 81
 82    public SystemData(String hostname, String osName, String javaVer, Long heapSize) {
 83        this.hostname = hostname;
 84        this.osName = osName;
 85        this.javaVersion = javaVer;
 86        this.heapSize = heapSize;
 87    }
 88
 89    public int getId() {
 90        return id;
 91    }
 92
 93    public void setId(int id) {
 94        this.id = id;
 95    }
 96
 97    public String getHostname() {
 98        return hostname;
 99    }
100
101    public void setHostname(String hostname) {
102        this.hostname = hostname;
103    }
104
105    public String getOsName() {
106        return osName;
107    }
108
109    public void setOsName(String osName) {
110        this.osName = osName;
111    }
112
113    public String getJavaVersion() {
114        return javaVersion;
115    }
116
117    public void setJavaVersion(String javaVersion) {
118        this.javaVersion = javaVersion;
119    }
120
121    public Long getHeapSize() {
122        return heapSize;
123    }
124
125    public void setHeapSize(Long heapSize) {
126        this.heapSize = heapSize;
127    }
128
129    @Override
130    public int hashCode() {
131        return hostname.hashCode();
132    }
133
134    @Override
135    public boolean equals(Object host) {
136        if (host instanceof SystemData) {
137            return hostname.equals(((SystemData) host).getHostname());
138        }
139        return false;
140    }
141}
142// end::SystemData[]

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.util.List;
 15
 16import org.eclipse.microprofile.openapi.annotations.Operation;
 17import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 18import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 19import org.eclipse.microprofile.openapi.annotations.media.Schema;
 20import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 22import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 25
 26import org.eclipse.microprofile.config.inject.ConfigProperty;
 27
 28import io.openliberty.deepdive.rest.model.SystemData;
 29import jakarta.enterprise.context.ApplicationScoped;
 30import jakarta.inject.Inject;
 31import jakarta.transaction.Transactional;
 32import jakarta.ws.rs.Consumes;
 33import jakarta.ws.rs.DELETE;
 34import jakarta.ws.rs.GET;
 35import jakarta.ws.rs.POST;
 36import jakarta.ws.rs.PUT;
 37import jakarta.ws.rs.Path;
 38import jakarta.ws.rs.PathParam;
 39import jakarta.ws.rs.Produces;
 40import jakarta.ws.rs.QueryParam;
 41import jakarta.ws.rs.core.MediaType;
 42import jakarta.ws.rs.core.Response;
 43
 44@ApplicationScoped
 45@Path("/systems")
 46// tag::SystemResource[]
 47public class SystemResource {
 48
 49    // tag::inventory[]
 50    @Inject
 51    Inventory inventory;
 52    // end::inventory[]
 53
 54    // tag::inject[]
 55    @Inject
 56    // end::inject[]
 57    // tag::configProperty[]
 58    @ConfigProperty(name = "client.https.port")
 59    // end::configProperty[]
 60    String CLIENT_PORT;
 61
 62
 63    @GET
 64    @Path("/")
 65    @Produces(MediaType.APPLICATION_JSON)
 66    @APIResponseSchema(value = SystemData.class,
 67        responseDescription = "A list of system data stored within the inventory.",
 68        responseCode = "200")
 69    @Operation(
 70        summary = "List contents.",
 71        description = "Returns the currently stored system data in the inventory.",
 72        operationId = "listContents")
 73    public List<SystemData> listContents() {
 74        return inventory.getSystems();
 75    }
 76
 77    @GET
 78    @Path("/{hostname}")
 79    @Produces(MediaType.APPLICATION_JSON)
 80    @APIResponseSchema(value = SystemData.class,
 81        responseDescription = "System data of a particular host.",
 82        responseCode = "200")
 83    @Operation(
 84        summary = "Get System",
 85        description = "Retrieves and returns the system data from the system "
 86                      + "service running on the particular host.",
 87        operationId = "getSystem"
 88    )
 89    public SystemData getSystem(
 90        @Parameter(
 91            name = "hostname", in = ParameterIn.PATH,
 92            description = "The hostname of the system",
 93            required = true, example = "localhost",
 94            schema = @Schema(type = SchemaType.STRING)
 95        )
 96        @PathParam("hostname") String hostname) {
 97        return inventory.getSystem(hostname);
 98    }
 99
100    // tag::postTransactional[]
101    @POST
102    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
103    @Produces(MediaType.APPLICATION_JSON)
104    @Transactional
105    // end::postTransactional[]
106    @APIResponses(value = {
107        @APIResponse(responseCode = "200",
108            description = "Successfully added system to inventory"),
109        @APIResponse(responseCode = "400",
110            description = "Unable to add system to inventory")
111    })
112    @Parameters(value = {
113        @Parameter(
114            name = "hostname", in = ParameterIn.QUERY,
115            description = "The hostname of the system",
116            required = true, example = "localhost",
117            schema = @Schema(type = SchemaType.STRING)),
118        @Parameter(
119            name = "osName", in = ParameterIn.QUERY,
120            description = "The operating system of the system",
121            required = true, example = "linux",
122            schema = @Schema(type = SchemaType.STRING)),
123        @Parameter(
124            name = "javaVersion", in = ParameterIn.QUERY,
125            description = "The Java version of the system",
126            required = true, example = "17",
127            schema = @Schema(type = SchemaType.STRING)),
128        @Parameter(
129            name = "heapSize", in = ParameterIn.QUERY,
130            description = "The heap size of the system",
131            required = true, example = "1048576",
132            schema = @Schema(type = SchemaType.NUMBER)),
133    })
134    @Operation(
135        summary = "Add system",
136        description = "Add a system and its data to the inventory.",
137        operationId = "addSystem"
138    )
139    public Response addSystem(
140        @QueryParam("hostname") String hostname,
141        @QueryParam("osName") String osName,
142        @QueryParam("javaVersion") String javaVersion,
143        @QueryParam("heapSize") Long heapSize) {
144
145        SystemData s = inventory.getSystem(hostname);
146        if (s != null) {
147            return fail(hostname + " already exists.");
148        }
149        inventory.add(hostname, osName, javaVersion, heapSize);
150        return success(hostname + " was added.");
151    }
152
153    // tag::putTransactional[]
154    @PUT
155    @Path("/{hostname}")
156    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
157    @Produces(MediaType.APPLICATION_JSON)
158    @Transactional
159    // end::putTransactional[]
160    @APIResponses(value = {
161        @APIResponse(responseCode = "200",
162            description = "Successfully updated system"),
163        @APIResponse(responseCode = "400",
164           description =
165               "Unable to update because the system does not exist in the inventory.")
166    })
167    @Parameters(value = {
168        @Parameter(
169            name = "hostname", in = ParameterIn.PATH,
170            description = "The hostname of the system",
171            required = true, example = "localhost",
172            schema = @Schema(type = SchemaType.STRING)),
173        @Parameter(
174            name = "osName", in = ParameterIn.QUERY,
175            description = "The operating system of the system",
176            required = true, example = "linux",
177            schema = @Schema(type = SchemaType.STRING)),
178        @Parameter(
179            name = "javaVersion", in = ParameterIn.QUERY,
180            description = "The Java version of the system",
181            required = true, example = "17",
182            schema = @Schema(type = SchemaType.STRING)),
183        @Parameter(
184            name = "heapSize", in = ParameterIn.QUERY,
185            description = "The heap size of the system",
186            required = true, example = "1048576",
187            schema = @Schema(type = SchemaType.NUMBER)),
188    })
189    @Operation(
190        summary = "Update system",
191        description = "Update a system and its data on the inventory.",
192        operationId = "updateSystem"
193    )
194    public Response updateSystem(
195        @PathParam("hostname") String hostname,
196        @QueryParam("osName") String osName,
197        @QueryParam("javaVersion") String javaVersion,
198        @QueryParam("heapSize") Long heapSize) {
199
200        SystemData s = inventory.getSystem(hostname);
201        if (s == null) {
202            return fail(hostname + " does not exists.");
203        }
204        s.setOsName(osName);
205        s.setJavaVersion(javaVersion);
206        s.setHeapSize(heapSize);
207        inventory.update(s);
208        return success(hostname + " was updated.");
209    }
210
211    // tag::deleteTransactional[]
212    @DELETE
213    @Path("/{hostname}")
214    @Produces(MediaType.APPLICATION_JSON)
215    @Transactional
216    // end::deleteTransactional[]
217    @APIResponses(value = {
218        @APIResponse(responseCode = "200",
219            description = "Successfully deleted the system from inventory"),
220        @APIResponse(responseCode = "400",
221            description =
222                "Unable to delete because the system does not exist in the inventory")
223    })
224    @Parameter(
225        name = "hostname", in = ParameterIn.PATH,
226        description = "The hostname of the system",
227        required = true, example = "localhost",
228        schema = @Schema(type = SchemaType.STRING)
229    )
230    @Operation(
231        summary = "Remove system",
232        description = "Removes a system from the inventory.",
233        operationId = "removeSystem"
234    )
235    public Response removeSystem(@PathParam("hostname") String hostname) {
236        SystemData s = inventory.getSystem(hostname);
237        if (s != null) {
238            inventory.removeSystem(s);
239            return success(hostname + " was removed.");
240        } else {
241            return fail(hostname + " does not exists.");
242        }
243    }
244
245    @POST
246    @Path("/client/{hostname}")
247    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
248    @Produces(MediaType.APPLICATION_JSON)
249    @Transactional
250    @APIResponses(value = {
251        @APIResponse(responseCode = "200",
252            description = "Successfully added system client"),
253        @APIResponse(responseCode = "400",
254            description = "Unable to add system client")
255    })
256    @Parameter(
257        name = "hostname", in = ParameterIn.PATH,
258        description = "The hostname of the system",
259        required = true, example = "localhost",
260        schema = @Schema(type = SchemaType.STRING)
261    )
262    @Operation(
263        summary = "Add system client",
264        description = "This adds a system client.",
265        operationId = "addSystemClient"
266    )
267    //tag::printClientPort[]
268    public Response addSystemClient(@PathParam("hostname") String hostname) {
269        System.out.println(CLIENT_PORT);
270        return success("Client Port: " + CLIENT_PORT);
271    }
272    //end::printClientPort[]
273
274    private Response success(String message) {
275        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
276    }
277
278    private Response fail(String message) {
279        return Response.status(Response.Status.BAD_REQUEST)
280                       .entity("{ \"error\" : \"" + message + "\" }")
281                       .build();
282    }
283}
284// end::SystemResource[]

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

 1<?xml version="1.0" encoding="UTF-8"?>
 2<persistence version="2.2"
 3    xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
 4    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence 
 6                        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
 7    <!-- tag::persistence-unit[] -->
 8    <!-- tag::transaction-type[] -->
 9    <persistence-unit name="jpa-unit" transaction-type="JTA">
10    <!-- end::transaction-type[] -->
11      <!-- tag::jta-data[] -->
12      <jta-data-source>jdbc/postgresql</jta-data-source>
13      <!-- end::jta-data[] -->
14      <exclude-unlisted-classes>false</exclude-unlisted-classes>
15      <properties>
16        <property name="jakarta.persistence.schema-generation.database.action"
17                  value="create"/>
18        <property name="jakarta.persistence.schema-generation.scripts.action"
19                  value="create"/>
20        <property name="jakarta.persistence.schema-generation.scripts.create-target"
21                  value="createDDL.ddl"/>
22      </properties>
23    </persistence-unit>
24    <!-- end::persistence-unit[] -->
25</persistence>

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.xml configuration file.

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

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7    </featureManager>
 8
 9    <variable name="http.port" defaultValue="9080" />
10    <variable name="https.port" defaultValue="9443" />
11    <variable name="context.root" defaultValue="/inventory" />
12    <variable name="postgres/hostname" defaultValue="localhost" />
13    <variable name="postgres/portnum" defaultValue="5432" />
14
15    <httpEndpoint id="defaultHttpEndpoint"
16                  httpPort="${http.port}" 
17                  httpsPort="${https.port}" />
18
19    <!-- Automatically expand WAR files and EAR files -->
20    <applicationManager autoExpand="true"/>
21
22    <!-- Configures the application on a specified context root -->
23    <webApplication contextRoot="${context.root}" 
24                    location="inventory.war" /> 
25
26    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
27    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
28    
29    <!-- tag::postgresqlLibrary[] -->
30    <library id="postgresql-library">
31        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
32    </library>
33    <!-- end::postgresqlLibrary[] -->
34
35    <!-- Datasource Configuration -->
36    <!-- tag::dataSource[] -->
37    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
38        <jdbcDriver libraryRef="postgresql-library" />
39        <properties.postgresql databaseName="admin"
40                               serverName="localhost"
41                               portNumber="5432"
42                               user="admin"
43                               password="adminpwd"/>
44    </dataSource>
45    <!-- end::dataSource[] -->
46</server>

The library element tells the Liberty 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 pom.xml file.

Replace the pom.xml configuration file.
pom.xml

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5    <modelVersion>4.0.0</modelVersion>
 6
 7    <groupId>io.openliberty.deepdive</groupId>
 8    <artifactId>inventory</artifactId>
 9    <packaging>war</packaging>
10    <version>1.0-SNAPSHOT</version>
11
12    <properties>
13        <maven.compiler.source>17</maven.compiler.source>
14        <maven.compiler.target>17</maven.compiler.target>
15        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16        <liberty.var.http.port>9080</liberty.var.http.port>
17        <liberty.var.https.port>9443</liberty.var.https.port>
18        <liberty.var.context.root>/inventory</liberty.var.context.root>
19    </properties>
20
21    <dependencies>
22        <dependency>
23            <groupId>jakarta.platform</groupId>
24            <artifactId>jakarta.jakartaee-api</artifactId>
25            <version>10.0.0</version>
26            <scope>provided</scope>
27        </dependency>
28        <dependency>
29            <groupId>org.eclipse.microprofile</groupId>
30            <artifactId>microprofile</artifactId>
31            <version>6.1</version>
32            <type>pom</type>
33            <scope>provided</scope>
34        </dependency>
35        <!-- tag::postgresql[] -->        
36        <dependency>
37            <groupId>org.postgresql</groupId>
38            <artifactId>postgresql</artifactId>
39            <version>42.7.2</version>
40            <scope>provided</scope>
41        </dependency>
42        <!-- end::postgresql[] -->        
43    </dependencies>
44
45    <build>
46        <finalName>inventory</finalName>
47        <pluginManagement>
48            <plugins>
49                <plugin>
50                    <groupId>org.apache.maven.plugins</groupId>
51                    <artifactId>maven-war-plugin</artifactId>
52                    <version>3.3.2</version>
53                </plugin>
54                <plugin>
55                    <groupId>io.openliberty.tools</groupId>
56                    <artifactId>liberty-maven-plugin</artifactId>
57                    <version>3.10.2</version>
58                </plugin>
59            </plugins>
60        </pluginManagement>
61        <plugins>
62            <plugin>
63                <groupId>io.openliberty.tools</groupId>
64                <artifactId>liberty-maven-plugin</artifactId>
65                <!-- tag::copyDependencies[] -->        
66                <configuration>
67                    <copyDependencies>
68                        <dependencyGroup>
69                            <location>${project.build.directory}/liberty/wlp/usr/shared/resources</location>
70                            <dependency>
71                                <groupId>org.postgresql</groupId>
72                                <artifactId>postgresql</artifactId>
73                                <version>42.7.1</version>
74                            </dependency>
75                        </dependencyGroup>
76                    </copyDependencies>
77                </configuration>
78                <!-- end::copyDependencies[] -->        
79            </plugin>
80        </plugins>
81    </build>
82</project>

The postgresql dependency ensures that Maven downloads the PostgreSQL library to local project. The copyDependencies configuration tells the Liberty Maven plug-in to copy the library to the Liberty shared resources 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
docker build -t postgres-sample .
docker 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 Liberty instance.

After you see the following message, your Liberty instance is ready in dev mode 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 Liberty server.xml configuration file.

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

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7    </featureManager>
 8
 9    <variable name="http.port" defaultValue="9080" />
10    <variable name="https.port" defaultValue="9443" />
11    <variable name="context.root" defaultValue="/inventory" />
12    <variable name="postgres/hostname" defaultValue="localhost" />
13    <variable name="postgres/portnum" defaultValue="5432" />
14
15    <httpEndpoint id="defaultHttpEndpoint"
16                  httpPort="${http.port}" 
17                  httpsPort="${https.port}" />
18
19    <!-- Automatically expand WAR files and EAR files -->
20    <applicationManager autoExpand="true"/>
21
22    <!-- tag::basicregistry[] -->
23    <basicRegistry id="basic" realm="WebRealm">
24        <user name="bob" password="{xor}PTA9Lyg7" />
25        <user name="alice" password="{xor}PjM2PDovKDs=" />
26        <!-- tag::myadmins[] -->
27        <group name="admin">
28            <member name="bob" />
29        </group>
30        <!-- end::myadmins[] -->
31        <!-- tag::myusers[] -->
32        <group name="user">
33            <member name="bob" />
34            <member name="alice" />
35        </group>
36        <!-- end::myusers[] -->
37    </basicRegistry>
38    <!-- end::basicregistry[] -->
39
40    <!-- Configures the application on a specified context root -->
41    <webApplication contextRoot="${context.root}"
42                    location="inventory.war">
43        <application-bnd>
44            <!-- tag::securityrole[] -->
45            <!-- tag::adminrole[] -->
46            <security-role name="admin">
47                <group name="admin" />
48            </security-role>
49            <!-- end::adminrole[] -->
50            <!-- tag::userrole[] -->
51            <security-role name="user">
52                <group name="user" />
53            </security-role>
54            <!-- end::userrole[] -->
55            <!-- end::securityrole[] -->
56        </application-bnd>
57     </webApplication>
58
59    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
60    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
61
62    <library id="postgresql-library">
63        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
64    </library>
65
66    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
67        <jdbcDriver libraryRef="postgresql-library" />
68        <properties.postgresql databaseName="admin"
69                               serverName="localhost"
70                               portNumber="5432"
71                               user="admin"
72                               password="adminpwd"/>
73    </dataSource>
74</server>

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.util.List;
 15
 16import org.eclipse.microprofile.openapi.annotations.Operation;
 17import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 18import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 19import org.eclipse.microprofile.openapi.annotations.media.Schema;
 20import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 22import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 25
 26import org.eclipse.microprofile.config.inject.ConfigProperty;
 27
 28import io.openliberty.deepdive.rest.model.SystemData;
 29import jakarta.enterprise.context.ApplicationScoped;
 30import jakarta.annotation.security.RolesAllowed;
 31import jakarta.inject.Inject;
 32import jakarta.transaction.Transactional;
 33import jakarta.ws.rs.Consumes;
 34import jakarta.ws.rs.DELETE;
 35import jakarta.ws.rs.GET;
 36import jakarta.ws.rs.POST;
 37import jakarta.ws.rs.PUT;
 38import jakarta.ws.rs.Path;
 39import jakarta.ws.rs.PathParam;
 40import jakarta.ws.rs.Produces;
 41import jakarta.ws.rs.QueryParam;
 42import jakarta.ws.rs.core.MediaType;
 43import jakarta.ws.rs.core.Response;
 44
 45@ApplicationScoped
 46@Path("/systems")
 47// tag::SystemResource[]
 48public class SystemResource {
 49
 50    // tag::inventory[]
 51    @Inject
 52    Inventory inventory;
 53    // end::inventory[]
 54
 55    // tag::inject[]
 56    @Inject
 57    // end::inject[]
 58    // tag::configProperty[]
 59    @ConfigProperty(name = "client.https.port")
 60    // end::configProperty[]
 61    String CLIENT_PORT;
 62
 63
 64    @GET
 65    @Path("/")
 66    @Produces(MediaType.APPLICATION_JSON)
 67    @APIResponseSchema(value = SystemData.class,
 68        responseDescription = "A list of system data stored within the inventory.",
 69        responseCode = "200")
 70    @Operation(
 71        summary = "List contents.",
 72        description = "Returns the currently stored system data in the inventory.",
 73        operationId = "listContents")
 74    public List<SystemData> listContents() {
 75        return inventory.getSystems();
 76    }
 77
 78    @GET
 79    @Path("/{hostname}")
 80    @Produces(MediaType.APPLICATION_JSON)
 81    @APIResponseSchema(value = SystemData.class,
 82        responseDescription = "System data of a particular host.",
 83        responseCode = "200")
 84    @Operation(
 85        summary = "Get System",
 86        description = "Retrieves and returns the system data from the system "
 87                      + "service running on the particular host.",
 88        operationId = "getSystem"
 89    )
 90    public SystemData getSystem(
 91        @Parameter(
 92            name = "hostname", in = ParameterIn.PATH,
 93            description = "The hostname of the system",
 94            required = true, example = "localhost",
 95            schema = @Schema(type = SchemaType.STRING)
 96        )
 97        @PathParam("hostname") String hostname) {
 98        return inventory.getSystem(hostname);
 99    }
100
101    // tag::postTransactional[]
102    @POST
103    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
104    @Produces(MediaType.APPLICATION_JSON)
105    @Transactional
106    // end::postTransactional[]
107    @APIResponses(value = {
108        @APIResponse(responseCode = "200",
109            description = "Successfully added system to inventory"),
110        @APIResponse(responseCode = "400",
111            description = "Unable to add system to inventory")
112    })
113    @Parameters(value = {
114        @Parameter(
115            name = "hostname", in = ParameterIn.QUERY,
116            description = "The hostname of the system",
117            required = true, example = "localhost",
118            schema = @Schema(type = SchemaType.STRING)),
119        @Parameter(
120            name = "osName", in = ParameterIn.QUERY,
121            description = "The operating system of the system",
122            required = true, example = "linux",
123            schema = @Schema(type = SchemaType.STRING)),
124        @Parameter(
125            name = "javaVersion", in = ParameterIn.QUERY,
126            description = "The Java version of the system",
127            required = true, example = "17",
128            schema = @Schema(type = SchemaType.STRING)),
129        @Parameter(
130            name = "heapSize", in = ParameterIn.QUERY,
131            description = "The heap size of the system",
132            required = true, example = "1048576",
133            schema = @Schema(type = SchemaType.NUMBER)),
134    })
135    @Operation(
136        summary = "Add system",
137        description = "Add a system and its data to the inventory.",
138        operationId = "addSystem"
139    )
140    public Response addSystem(
141        @QueryParam("hostname") String hostname,
142        @QueryParam("osName") String osName,
143        @QueryParam("javaVersion") String javaVersion,
144        @QueryParam("heapSize") Long heapSize) {
145
146        SystemData s = inventory.getSystem(hostname);
147        if (s != null) {
148            return fail(hostname + " already exists.");
149        }
150        inventory.add(hostname, osName, javaVersion, heapSize);
151        return success(hostname + " was added.");
152    }
153
154    // tag::putTransactional[]
155    // tag::put[]
156    @PUT
157    // end::put[]
158    // tag::putEndpoint[]
159    @Path("/{hostname}")
160    // end::putEndpoint[]
161    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
162    @Produces(MediaType.APPLICATION_JSON)
163    @Transactional
164    // end::putTransactional[]
165    // tag::putRolesAllowed[]
166    @RolesAllowed({ "admin", "user" })
167    // end::putRolesAllowed[]
168    @APIResponses(value = {
169        @APIResponse(responseCode = "200",
170            description = "Successfully updated system"),
171        @APIResponse(responseCode = "400",
172           description =
173           "Unable to update because the system does not exist in the inventory.")
174    })
175    @Parameters(value = {
176        @Parameter(
177            name = "hostname", in = ParameterIn.PATH,
178            description = "The hostname of the system",
179            required = true, example = "localhost",
180            schema = @Schema(type = SchemaType.STRING)),
181        @Parameter(
182            name = "osName", in = ParameterIn.QUERY,
183            description = "The operating system of the system",
184            required = true, example = "linux",
185            schema = @Schema(type = SchemaType.STRING)),
186        @Parameter(
187            name = "javaVersion", in = ParameterIn.QUERY,
188            description = "The Java version of the system",
189            required = true, example = "17",
190            schema = @Schema(type = SchemaType.STRING)),
191        @Parameter(
192            name = "heapSize", in = ParameterIn.QUERY,
193            description = "The heap size of the system",
194            required = true, example = "1048576",
195            schema = @Schema(type = SchemaType.NUMBER)),
196    })
197    @Operation(
198        summary = "Update system",
199        description = "Update a system and its data on the inventory.",
200        operationId = "updateSystem"
201    )
202    public Response updateSystem(
203        @PathParam("hostname") String hostname,
204        @QueryParam("osName") String osName,
205        @QueryParam("javaVersion") String javaVersion,
206        @QueryParam("heapSize") Long heapSize) {
207
208        SystemData s = inventory.getSystem(hostname);
209        if (s == null) {
210            return fail(hostname + " does not exists.");
211        }
212        s.setOsName(osName);
213        s.setJavaVersion(javaVersion);
214        s.setHeapSize(heapSize);
215        inventory.update(s);
216        return success(hostname + " was updated.");
217    }
218
219    // tag::deleteTransactional[]
220    // tag::delete[]
221    @DELETE
222    // end::delete[]
223    // tag::deleteEndpoint[]
224    @Path("/{hostname}")
225    // end::deleteEndpoint[]
226    @Produces(MediaType.APPLICATION_JSON)
227    @Transactional
228    // end::deleteTransactional[]
229    // tag::deleteRolesAllowed[]
230    @RolesAllowed({ "admin" })
231    // end::deleteRolesAllowed[]
232    @APIResponses(value = {
233        @APIResponse(responseCode = "200",
234            description = "Successfully deleted the system from inventory"),
235        @APIResponse(responseCode = "400",
236            description =
237                "Unable to delete because the system does not exist in the inventory")
238    })
239    @Parameter(
240        name = "hostname", in = ParameterIn.PATH,
241        description = "The hostname of the system",
242        required = true, example = "localhost",
243        schema = @Schema(type = SchemaType.STRING)
244    )
245    @Operation(
246        summary = "Remove system",
247        description = "Removes a system from the inventory.",
248        operationId = "removeSystem"
249    )
250    public Response removeSystem(@PathParam("hostname") String hostname) {
251        SystemData s = inventory.getSystem(hostname);
252        if (s != null) {
253            inventory.removeSystem(s);
254            return success(hostname + " was removed.");
255        } else {
256            return fail(hostname + " does not exists.");
257        }
258    }
259
260    // tag::postTransactional[]
261    // tag::addSystemClient[]
262    @POST
263    @Path("/client/{hostname}")
264    // end::addSystemClient[]
265    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
266    @Produces(MediaType.APPLICATION_JSON)
267    @Transactional
268    @RolesAllowed({ "admin" })
269    @APIResponses(value = {
270        @APIResponse(responseCode = "200",
271            description = "Successfully added system client"),
272        @APIResponse(responseCode = "400",
273            description = "Unable to add system client")
274    })
275    @Parameter(
276        name = "hostname", in = ParameterIn.PATH,
277        description = "The hostname of the system",
278        required = true, example = "localhost",
279        schema = @Schema(type = SchemaType.STRING)
280    )
281    @Operation(
282        summary = "Add system client",
283        description = "This adds a system client.",
284        operationId = "addSystemClient"
285    )
286    //tag::printClientPort[]
287    public Response addSystemClient(@PathParam("hostname") String hostname) {
288        System.out.println(CLIENT_PORT);
289        return success("Client Port: " + CLIENT_PORT);
290    }
291    //end::printClientPort[]
292
293    private Response success(String message) {
294        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
295    }
296
297    private Response fail(String message) {
298        return Response.status(Response.Status.BAD_REQUEST)
299                       .entity("{ \"error\" : \"" + message + "\" }")
300                       .build();
301    }
302}
303// end::SystemResource[]

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=17&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":"17","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=17&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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest.client;
13
14import jakarta.ws.rs.GET;
15import jakarta.ws.rs.HeaderParam;
16import jakarta.ws.rs.Path;
17import jakarta.ws.rs.PathParam;
18import jakarta.ws.rs.Produces;
19import jakarta.ws.rs.core.MediaType;
20
21@Path("/api")
22public interface SystemClient extends AutoCloseable {
23
24    @GET
25    @Path("/property/{property}")
26    @Produces(MediaType.TEXT_PLAIN)
27    String getProperty(@HeaderParam("Authorization") String authHeader,
28                       @PathParam("property") String property);
29
30    @GET
31    @Path("/heapsize")
32    @Produces(MediaType.TEXT_PLAIN)
33    Long getHeapSize(@HeaderParam("Authorization") String authHeader);
34
35}

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest.client;
13
14public class UnknownUriException extends Exception {
15
16    private static final long serialVersionUID = 1L;
17
18    public UnknownUriException() {
19        super();
20    }
21
22    public UnknownUriException(String message) {
23        super(message);
24    }
25
26}

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.deepdive.rest.client;
13
14import java.util.logging.Logger;
15
16import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
17
18import jakarta.ws.rs.core.MultivaluedMap;
19import jakarta.ws.rs.core.Response;
20
21public class UnknownUriExceptionMapper
22    implements ResponseExceptionMapper<UnknownUriException> {
23    Logger LOG = Logger.getLogger(UnknownUriExceptionMapper.class.getName());
24
25    @Override
26    public boolean handles(int status, MultivaluedMap<String, Object> headers) {
27        LOG.info("status = " + status);
28        return status == 404;
29    }
30
31    @Override
32    public UnknownUriException toThrowable(Response response) {
33        return new UnknownUriException();
34    }
35}

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.net.URI;
 15import java.util.List;
 16
 17import org.eclipse.microprofile.openapi.annotations.Operation;
 18import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 19import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 20import org.eclipse.microprofile.openapi.annotations.media.Schema;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 22import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 25import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 26import org.eclipse.microprofile.rest.client.RestClientBuilder;
 27import org.eclipse.microprofile.config.inject.ConfigProperty;
 28import org.eclipse.microprofile.jwt.JsonWebToken;
 29
 30import io.openliberty.deepdive.rest.client.SystemClient;
 31import io.openliberty.deepdive.rest.client.UnknownUriExceptionMapper;
 32import io.openliberty.deepdive.rest.model.SystemData;
 33import jakarta.annotation.security.RolesAllowed;
 34import jakarta.enterprise.context.ApplicationScoped;
 35import jakarta.inject.Inject;
 36import jakarta.transaction.Transactional;
 37import jakarta.ws.rs.Consumes;
 38import jakarta.ws.rs.DELETE;
 39import jakarta.ws.rs.GET;
 40import jakarta.ws.rs.POST;
 41import jakarta.ws.rs.PUT;
 42import jakarta.ws.rs.Path;
 43import jakarta.ws.rs.PathParam;
 44import jakarta.ws.rs.Produces;
 45import jakarta.ws.rs.QueryParam;
 46import jakarta.ws.rs.core.MediaType;
 47import jakarta.ws.rs.core.Response;
 48
 49@ApplicationScoped
 50@Path("/systems")
 51public class SystemResource {
 52
 53    @Inject
 54    Inventory inventory;
 55
 56    @Inject
 57    @ConfigProperty(name = "client.https.port")
 58    String CLIENT_PORT;
 59
 60    // tag::jwt[]
 61    @Inject
 62    JsonWebToken jwt;
 63    // end::jwt[]
 64
 65    @GET
 66    @Path("/")
 67    @Produces(MediaType.APPLICATION_JSON)
 68    @APIResponseSchema(value = SystemData.class,
 69        responseDescription = "A list of system data stored within the inventory.",
 70        responseCode = "200")
 71    @Operation(
 72        summary = "List contents.",
 73        description = "Returns the currently stored system data in the inventory.",
 74        operationId = "listContents")
 75    public List<SystemData> listContents() {
 76        return inventory.getSystems();
 77    }
 78
 79    @GET
 80    @Path("/{hostname}")
 81    @Produces(MediaType.APPLICATION_JSON)
 82    @APIResponseSchema(value = SystemData.class,
 83        responseDescription = "System data of a particular host.",
 84        responseCode = "200")
 85    @Operation(
 86        summary = "Get System",
 87        description = "Retrieves and returns the system data from the system "
 88                      + "service running on the particular host.",
 89        operationId = "getSystem"
 90    )
 91    public SystemData getSystem(
 92        @Parameter(
 93            name = "hostname", in = ParameterIn.PATH,
 94            description = "The hostname of the system",
 95            required = true, example = "localhost",
 96            schema = @Schema(type = SchemaType.STRING)
 97        )
 98        @PathParam("hostname") String hostname) {
 99        return inventory.getSystem(hostname);
100    }
101
102    @POST
103    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
104    @Produces(MediaType.APPLICATION_JSON)
105    @Transactional
106    @APIResponses(value = {
107        @APIResponse(responseCode = "200",
108            description = "Successfully added system to inventory"),
109        @APIResponse(responseCode = "400",
110            description = "Unable to add system to inventory")
111    })
112    @Parameters(value = {
113        @Parameter(
114            name = "hostname", in = ParameterIn.QUERY,
115            description = "The hostname of the system",
116            required = true, example = "localhost",
117            schema = @Schema(type = SchemaType.STRING)),
118        @Parameter(
119            name = "osName", in = ParameterIn.QUERY,
120            description = "The operating system of the system",
121            required = true, example = "linux",
122            schema = @Schema(type = SchemaType.STRING)),
123        @Parameter(
124            name = "javaVersion", in = ParameterIn.QUERY,
125            description = "The Java version of the system",
126            required = true, example = "17",
127            schema = @Schema(type = SchemaType.STRING)),
128        @Parameter(
129            name = "heapSize", in = ParameterIn.QUERY,
130            description = "The heap size of the system",
131            required = true, example = "1048576",
132            schema = @Schema(type = SchemaType.NUMBER)),
133    })
134    @Operation(
135        summary = "Add system",
136        description = "Add a system and its data to the inventory.",
137        operationId = "addSystem"
138    )
139    public Response addSystem(
140        @QueryParam("hostname") String hostname,
141        @QueryParam("osName") String osName,
142        @QueryParam("javaVersion") String javaVersion,
143        @QueryParam("heapSize") Long heapSize) {
144
145        SystemData s = inventory.getSystem(hostname);
146        if (s != null) {
147            return fail(hostname + " already exists.");
148        }
149        inventory.add(hostname, osName, javaVersion, heapSize);
150        return success(hostname + " was added.");
151    }
152
153    // tag::put[]
154    @PUT
155    // end::put[]
156    // tag::putEndpoint[]
157    @Path("/{hostname}")
158    // end::putEndpoint[]
159    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
160    @Produces(MediaType.APPLICATION_JSON)
161    @Transactional
162    // tag::putRolesAllowed[]
163    @RolesAllowed({ "admin", "user" })
164    // end::putRolesAllowed[]
165    @APIResponses(value = {
166        @APIResponse(responseCode = "200",
167            description = "Successfully updated system"),
168        @APIResponse(responseCode = "400",
169           description =
170               "Unable to update because the system does not exist in the inventory.")
171    })
172    @Parameters(value = {
173        @Parameter(
174            name = "hostname", in = ParameterIn.PATH,
175            description = "The hostname of the system",
176            required = true, example = "localhost",
177            schema = @Schema(type = SchemaType.STRING)),
178        @Parameter(
179            name = "osName", in = ParameterIn.QUERY,
180            description = "The operating system of the system",
181            required = true, example = "linux",
182            schema = @Schema(type = SchemaType.STRING)),
183        @Parameter(
184            name = "javaVersion", in = ParameterIn.QUERY,
185            description = "The Java version of the system",
186            required = true, example = "17",
187            schema = @Schema(type = SchemaType.STRING)),
188        @Parameter(
189            name = "heapSize", in = ParameterIn.QUERY,
190            description = "The heap size of the system",
191            required = true, example = "1048576",
192            schema = @Schema(type = SchemaType.NUMBER)),
193    })
194    @Operation(
195        summary = "Update system",
196        description = "Update a system and its data on the inventory.",
197        operationId = "updateSystem"
198    )
199    public Response updateSystem(
200        @PathParam("hostname") String hostname,
201        @QueryParam("osName") String osName,
202        @QueryParam("javaVersion") String javaVersion,
203        @QueryParam("heapSize") Long heapSize) {
204
205        SystemData s = inventory.getSystem(hostname);
206        if (s == null) {
207            return fail(hostname + " does not exists.");
208        }
209        s.setOsName(osName);
210        s.setJavaVersion(javaVersion);
211        s.setHeapSize(heapSize);
212        inventory.update(s);
213        return success(hostname + " was updated.");
214    }
215
216    // tag::delete[]
217    @DELETE
218    // end::delete[]
219    // tag::deleteEndpoint[]
220    @Path("/{hostname}")
221    // end::deleteEndpoint[]
222    @Produces(MediaType.APPLICATION_JSON)
223    @Transactional
224    // tag::deleteRolesAllowed[]
225    @RolesAllowed({ "admin" })
226    // end::deleteRolesAllowed[]
227    @APIResponses(value = {
228        @APIResponse(responseCode = "200",
229            description = "Successfully deleted the system from inventory"),
230        @APIResponse(responseCode = "400",
231            description =
232                "Unable to delete because the system does not exist in the inventory")
233    })
234    @Parameter(
235        name = "hostname", in = ParameterIn.PATH,
236        description = "The hostname of the system",
237        required = true, example = "localhost",
238        schema = @Schema(type = SchemaType.STRING)
239    )
240    @Operation(
241        summary = "Remove system",
242        description = "Removes a system from the inventory.",
243        operationId = "removeSystem"
244    )
245    public Response removeSystem(@PathParam("hostname") String hostname) {
246        SystemData s = inventory.getSystem(hostname);
247        if (s != null) {
248            inventory.removeSystem(s);
249            return success(hostname + " was removed.");
250        } else {
251            return fail(hostname + " does not exists.");
252        }
253    }
254
255    // tag::addSystemClient[]
256    @POST
257    @Path("/client/{hostname}")
258    // end::addSystemClient[]
259    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
260    @Produces(MediaType.APPLICATION_JSON)
261    @Transactional
262    @RolesAllowed({ "admin" })
263    @APIResponses(value = {
264        @APIResponse(responseCode = "200",
265            description = "Successfully added system client"),
266        @APIResponse(responseCode = "400",
267            description = "Unable to add system client")
268    })
269    @Parameter(
270        name = "hostname", in = ParameterIn.PATH,
271        description = "The hostname of the system",
272        required = true, example = "localhost",
273        schema = @Schema(type = SchemaType.STRING)
274    )
275    @Operation(
276        summary = "Add system client",
277        description = "This adds a system client.",
278        operationId = "addSystemClient"
279    )
280    public Response addSystemClient(@PathParam("hostname") String hostname) {
281
282        SystemData s = inventory.getSystem(hostname);
283        if (s != null) {
284            return fail(hostname + " already exists.");
285        }
286
287        // tag::getCustomRestClient[]
288        SystemClient customRestClient = null;
289        try {
290            customRestClient = getSystemClient(hostname);
291        } catch (Exception e) {
292            return fail("Failed to create the client " + hostname + ".");
293        }
294        // end::getCustomRestClient[]
295
296        // tag::authHeader[]
297        String authHeader = "Bearer " + jwt.getRawToken();
298        // end::authHeader[]
299        try {
300            // tag::customRestClient[]
301            String osName = customRestClient.getProperty(authHeader, "os.name");
302            String javaVer = customRestClient.getProperty(authHeader, "java.version");
303            Long heapSize = customRestClient.getHeapSize(authHeader);
304            // end::customRestClient[]
305            // tag::addSystem[]
306            inventory.add(hostname, osName, javaVer, heapSize);
307            // end::addSystem[]
308        } catch (Exception e) {
309            return fail("Failed to reach the client " + hostname + ".");
310        }
311        return success(hostname + " was added.");
312    }
313
314    // tag::getSystemClient[]
315    private SystemClient getSystemClient(String hostname) throws Exception {
316        String customURIString = "https://" + hostname + ":" + CLIENT_PORT + "/system";
317        URI customURI = URI.create(customURIString);
318        return RestClientBuilder.newBuilder()
319                                .baseUri(customURI)
320                                .register(UnknownUriExceptionMapper.class)
321                                .build(SystemClient.class);
322    }
323    // end::getSystemClient[]
324
325    private Response success(String message) {
326        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
327    }
328
329    private Response fail(String message) {
330        return Response.status(Response.Status.BAD_REQUEST)
331                       .entity("{ \"error\" : \"" + message + "\" }")
332                       .build();
333    }
334}

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 Liberty server.xml configuration file for the inventory service.

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

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7        <!-- tag::jwtSsoFeature[] -->
 8        <feature>jwtSso-1.0</feature>
 9        <!-- end::jwtSsoFeature[] -->
10    </featureManager>
11
12    <variable name="http.port" defaultValue="9080" />
13    <variable name="https.port" defaultValue="9443" />
14    <variable name="context.root" defaultValue="/inventory" />
15    <variable name="postgres/hostname" defaultValue="localhost" />
16    <variable name="postgres/portnum" defaultValue="5432" />
17
18    <httpEndpoint id="defaultHttpEndpoint"
19                  httpPort="${http.port}" 
20                  httpsPort="${https.port}" />
21
22    <!-- Automatically expand WAR files and EAR files -->
23    <applicationManager autoExpand="true"/>
24    
25    <basicRegistry id="basic" realm="WebRealm">
26        <user name="bob" password="{xor}PTA9Lyg7" />
27        <user name="alice" password="{xor}PjM2PDovKDs=" />
28
29        <group name="admin">
30            <member name="bob" />
31        </group>
32
33        <group name="user">
34            <member name="bob" />
35            <member name="alice" />
36        </group>
37    </basicRegistry>
38
39    <!-- Configures the application on a specified context root -->
40    <webApplication contextRoot="${context.root}"
41                    location="inventory.war">
42        <application-bnd>
43            <security-role name="admin">
44                <group name="admin" />
45            </security-role>
46            <security-role name="user">
47                <group name="user" />
48            </security-role>
49        </application-bnd>
50    </webApplication>
51
52    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
53    <!-- tag::ssl[] -->
54    <ssl id="guideSSLConfig" keyStoreRef="guideKeyStore" trustDefaultCerts="true" />
55    <!-- end::ssl[] -->
56    <!-- tag::sslDefault[] -->
57    <sslDefault sslRef="guideSSLConfig" />
58    <!-- end::sslDefault[] -->
59
60    <!-- tag::keyStore[] -->
61    <keyStore id="guideKeyStore"
62              password="secret"
63              location="${server.config.dir}/resources/security/key.p12" />
64    <!-- end::keyStore[] -->
65
66    <!-- tag::jwtSsoConfig[] -->
67    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/>
68    <!-- end::jwtSsoConfig[] -->
69    <!-- tag::jwtBuilder[] -->
70    <jwtBuilder id="jwtInventoryBuilder" 
71                issuer="http://openliberty.io" 
72                audiences="systemService"
73                expiry="24h"/>
74    <!-- end::jwtBuilder[] -->
75    <!-- tag::mpJwt[] -->
76    <mpJwt audiences="systemService" 
77           groupNameAttribute="groups" 
78           id="myMpJwt"
79           sslRef="guideSSLConfig"
80           issuer="http://openliberty.io"/>
81    <!-- end::mpJwt[] -->
82
83    <library id="postgresql-library">
84        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
85    </library>
86
87    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
88        <jdbcDriver libraryRef="postgresql-library" />
89        <properties.postgresql databaseName="admin"
90                               serverName="localhost"
91                               portNumber="5432"
92                               user="admin"
93                               password="adminpwd"/>
94    </dataSource>
95</server>

microprofile-config.properties

1Unresolved directive in README.adoc - include::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 file. 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 guideKeyStore. 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.

To avoid the conflict with the default ssl configuration, define your own ssl configuration by setting the id attribute to other value, the sslDefault element, and the sslRef attribute in the mpJwt element.

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 pom.xml configuration file.

Replace the pom.xml file.
pom.xml

pom.xml

 1<?xml version="1.0" encoding="UTF-8" ?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0"
 3               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5
 6    <modelVersion>4.0.0</modelVersion>
 7
 8    <groupId>io.openliberty.deepdive</groupId>
 9    <artifactId>inventory</artifactId>
10    <packaging>war</packaging>
11    <version>1.0-SNAPSHOT</version>
12
13    <properties>
14        <maven.compiler.source>17</maven.compiler.source>
15        <maven.compiler.target>17</maven.compiler.target>
16        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17        <liberty.var.http.port>9080</liberty.var.http.port>
18        <liberty.var.https.port>9443</liberty.var.https.port>
19        <liberty.var.context.root>/inventory</liberty.var.context.root>
20        <!-- tag::https[] -->
21        <liberty.var.client.https.port>9444</liberty.var.client.https.port>
22        <!-- end::https[] -->
23    </properties>
24
25    <dependencies>
26        <dependency>
27            <groupId>jakarta.platform</groupId>
28            <artifactId>jakarta.jakartaee-api</artifactId>
29            <version>10.0.0</version>
30            <scope>provided</scope>
31        </dependency>
32        <dependency>
33            <groupId>org.eclipse.microprofile</groupId>
34            <artifactId>microprofile</artifactId>
35            <version>6.1</version>
36            <type>pom</type>
37            <scope>provided</scope>
38        </dependency>
39        <dependency>
40            <groupId>org.postgresql</groupId>
41            <artifactId>postgresql</artifactId>
42            <version>42.7.2</version>
43            <scope>provided</scope>
44        </dependency>
45    </dependencies>
46
47    <build>
48        <finalName>inventory</finalName>
49        <pluginManagement>
50            <plugins>
51                <plugin>
52                    <groupId>org.apache.maven.plugins</groupId>
53                    <artifactId>maven-war-plugin</artifactId>
54                    <version>3.3.2</version>
55                </plugin>
56                <plugin>
57                    <groupId>io.openliberty.tools</groupId>
58                    <artifactId>liberty-maven-plugin</artifactId>
59                    <version>3.10.2</version>
60                </plugin>
61            </plugins>
62        </pluginManagement>
63        <plugins>
64            <plugin>
65                <groupId>io.openliberty.tools</groupId>
66                <artifactId>liberty-maven-plugin</artifactId>
67                <configuration>
68                    <copyDependencies>
69                        <dependencyGroup>
70                            <location>${project.build.directory}/liberty/wlp/usr/shared/resources</location>
71                            <dependency>
72                                <groupId>org.postgresql</groupId>
73                                <artifactId>postgresql</artifactId>
74                                <version>42.7.2</version>
75                            </dependency>
76                        </dependencyGroup>
77                    </copyDependencies>
78                </configuration>
79            </plugin>
80        </plugins>
81    </build>
82</project>

Configure the client https port by setting the <liberty.var.client.https.port> to 9444.

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

mvn liberty:dev

After you see the following message, your Liberty instance is ready in dev mode 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
mvn liberty:run

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": "17.0.9",
    "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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12// tag::StartupCheck[]
13package io.openliberty.deepdive.rest.health;
14
15import java.lang.management.ManagementFactory;
16import com.sun.management.OperatingSystemMXBean;
17import jakarta.enterprise.context.ApplicationScoped;
18import org.eclipse.microprofile.health.Startup;
19import org.eclipse.microprofile.health.HealthCheck;
20import org.eclipse.microprofile.health.HealthCheckResponse;
21
22// tag::Startup[]
23@Startup
24// end::Startup[]
25@ApplicationScoped
26public class StartupCheck implements HealthCheck {
27
28    @Override
29    public HealthCheckResponse call() {
30        OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean)
31        ManagementFactory.getOperatingSystemMXBean();
32        double cpuUsed = bean.getSystemCpuLoad();
33        String cpuUsage = String.valueOf(cpuUsed);
34        return HealthCheckResponse.named("Startup Check")
35                                  .status(cpuUsed < 0.95).build();
36    }
37}
38// end::StartupCheck[]

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12// tag::LivenessCheck[]
13package io.openliberty.deepdive.rest.health;
14
15import java.lang.management.ManagementFactory;
16import java.lang.management.MemoryMXBean;
17
18import jakarta.enterprise.context.ApplicationScoped;
19import org.eclipse.microprofile.health.Liveness;
20import org.eclipse.microprofile.health.HealthCheck;
21import org.eclipse.microprofile.health.HealthCheckResponse;
22
23// tag::Liveness[]
24@Liveness
25// end::Liveness[]
26@ApplicationScoped
27public class LivenessCheck implements HealthCheck {
28
29    @Override
30    public HealthCheckResponse call() {
31        MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
32        long memUsed = memBean.getHeapMemoryUsage().getUsed();
33        long memMax = memBean.getHeapMemoryUsage().getMax();
34
35        return HealthCheckResponse.named("Liveness Check")
36                                  .status(memUsed < memMax * 0.9)
37                                  .build();
38    }
39}
40// end::LivenessCheck[]

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

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12// tag::ReadinessCheck[]
13package io.openliberty.deepdive.rest.health;
14
15import jakarta.enterprise.context.ApplicationScoped;
16import jakarta.inject.Inject;
17
18import org.eclipse.microprofile.config.inject.ConfigProperty;
19import org.eclipse.microprofile.health.Readiness;
20import org.eclipse.microprofile.health.HealthCheck;
21import org.eclipse.microprofile.health.HealthCheckResponse;
22import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
23
24import java.io.IOException;
25import java.net.Socket;
26
27// tag::Readiness[]
28@Readiness
29// end::Readiness[]
30// tag::ApplicationScoped[]
31@ApplicationScoped
32// end::ApplicationScoped[]
33public class ReadinessCheck implements HealthCheck {
34
35    @Inject
36    @ConfigProperty(name = "postgres/hostname")
37    private String host;
38
39    @Inject
40    @ConfigProperty(name = "postgres/portnum")
41    private int port;
42
43    @Override
44    public HealthCheckResponse call() {
45        HealthCheckResponseBuilder responseBuilder =
46            HealthCheckResponse.named("Readiness Check");
47
48        try {
49            Socket socket = new Socket(host, port);
50            socket.close();
51            responseBuilder.up();
52        } catch (Exception e) {
53            responseBuilder.down();
54        }
55        return responseBuilder.build();
56    }
57}
58// end::ReadinessCheck[]

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 Liberty server.xml configuration file.
src/main/liberty/config/server.xml

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7        <feature>jwtSso-1.0</feature>
 8    </featureManager>
 9
10    <variable name="http.port" defaultValue="9080" />
11    <variable name="https.port" defaultValue="9443" />
12    <variable name="context.root" defaultValue="/inventory" />
13    <variable name="postgres/hostname" defaultValue="localhost" />
14    <variable name="postgres/portnum" defaultValue="5432" />
15
16    <httpEndpoint id="defaultHttpEndpoint"
17                  httpPort="${http.port}" 
18                  httpsPort="${https.port}" />
19
20    <!-- Automatically expand WAR files and EAR files -->
21    <applicationManager autoExpand="true"/>
22    
23    <basicRegistry id="basic" realm="WebRealm">
24        <user name="bob" password="{xor}PTA9Lyg7" />
25        <user name="alice" password="{xor}PjM2PDovKDs=" />
26
27        <group name="admin">
28            <member name="bob" />
29        </group>
30
31        <group name="user">
32            <member name="bob" />
33            <member name="alice" />
34        </group>
35    </basicRegistry>
36
37    <!-- tag::administrator[] -->
38    <administrator-role>
39        <user>bob</user>
40        <group>AuthorizedGroup</group>
41    </administrator-role>
42    <!-- end::administrator[] -->
43
44    <!-- Configures the application on a specified context root -->
45    <webApplication contextRoot="${context.root}"
46                    location="inventory.war">
47        <application-bnd>
48            <security-role name="admin">
49                <group name="admin" />
50            </security-role>
51            <security-role name="user">
52                <group name="user" />
53            </security-role>
54        </application-bnd>
55    </webApplication>
56
57    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
58    <ssl id="guideSSLConfig" keyStoreRef="guideKeyStore" trustDefaultCerts="true" />
59    <sslDefault sslRef="guideSSLConfig" />
60
61    <keyStore id="guideKeyStore"
62              password="secret"
63              location="${server.config.dir}/resources/security/key.p12" />
64    
65    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/>
66    <jwtBuilder id="jwtInventoryBuilder" 
67                issuer="http://openliberty.io" 
68                audiences="systemService"
69                expiry="24h"/>
70    <mpJwt audiences="systemService" 
71           groupNameAttribute="groups" 
72           id="myMpJwt" 
73           issuer="http://openliberty.io"/>
74
75    <library id="postgresql-library">
76        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
77    </library>
78
79    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
80        <jdbcDriver libraryRef="postgresql-library" />
81        <properties.postgresql databaseName="admin"
82                               serverName="localhost"
83                               portNumber="5432"
84                               user="admin"
85                               password="adminpwd"/>
86    </dataSource>
87</server>

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

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.deepdive.rest;
 13
 14import java.net.URI;
 15import java.util.List;
 16
 17import org.eclipse.microprofile.openapi.annotations.Operation;
 18import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
 19import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
 20import org.eclipse.microprofile.openapi.annotations.media.Schema;
 21import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 22import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
 23import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 24import org.eclipse.microprofile.openapi.annotations.responses.APIResponseSchema;
 25import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 26import org.eclipse.microprofile.rest.client.RestClientBuilder;
 27import org.eclipse.microprofile.config.inject.ConfigProperty;
 28import org.eclipse.microprofile.jwt.JsonWebToken;
 29// tag::metricsImport[]
 30import org.eclipse.microprofile.metrics.annotation.Counted;
 31// end::metricsImport[]
 32
 33import io.openliberty.deepdive.rest.client.SystemClient;
 34import io.openliberty.deepdive.rest.client.UnknownUriExceptionMapper;
 35import io.openliberty.deepdive.rest.model.SystemData;
 36import jakarta.annotation.security.RolesAllowed;
 37import jakarta.enterprise.context.ApplicationScoped;
 38import jakarta.inject.Inject;
 39import jakarta.transaction.Transactional;
 40import jakarta.ws.rs.Consumes;
 41import jakarta.ws.rs.DELETE;
 42import jakarta.ws.rs.GET;
 43import jakarta.ws.rs.POST;
 44import jakarta.ws.rs.PUT;
 45import jakarta.ws.rs.Path;
 46import jakarta.ws.rs.PathParam;
 47import jakarta.ws.rs.Produces;
 48import jakarta.ws.rs.QueryParam;
 49import jakarta.ws.rs.core.MediaType;
 50import jakarta.ws.rs.core.Response;
 51
 52@ApplicationScoped
 53@Path("/systems")
 54public class SystemResource {
 55
 56    @Inject
 57    Inventory inventory;
 58
 59    @Inject
 60    @ConfigProperty(name = "client.https.port")
 61    String CLIENT_PORT;
 62
 63    @Inject
 64    JsonWebToken jwt;
 65
 66    @GET
 67    @Path("/")
 68    @Produces(MediaType.APPLICATION_JSON)
 69    @APIResponseSchema(value = SystemData.class,
 70        responseDescription = "A list of system data stored within the inventory.",
 71        responseCode = "200")
 72    @Operation(
 73        summary = "List contents.",
 74        description = "Returns the currently stored system data in the inventory.",
 75        operationId = "listContents")
 76    public List<SystemData> listContents() {
 77        return inventory.getSystems();
 78    }
 79
 80    @GET
 81    @Path("/{hostname}")
 82    @Produces(MediaType.APPLICATION_JSON)
 83    @APIResponseSchema(value = SystemData.class,
 84        responseDescription = "System data of a particular host.",
 85        responseCode = "200")
 86    @Operation(
 87        summary = "Get System",
 88        description = "Retrieves and returns the system data from the system "
 89                      + "service running on the particular host.",
 90        operationId = "getSystem"
 91    )
 92    public SystemData getSystem(
 93        @Parameter(
 94            name = "hostname", in = ParameterIn.PATH,
 95            description = "The hostname of the system",
 96            required = true, example = "localhost",
 97            schema = @Schema(type = SchemaType.STRING)
 98        )
 99        @PathParam("hostname") String hostname) {
100        return inventory.getSystem(hostname);
101    }
102
103    @POST
104    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
105    @Produces(MediaType.APPLICATION_JSON)
106    @Transactional
107    // tag::metricsAddSystem[]
108    @Counted(name = "addSystem",
109             absolute = true,
110             description = "Number of times adding system endpoint is called")
111    // end::metricsAddSystem[]
112    @APIResponses(value = {
113        @APIResponse(responseCode = "200",
114            description = "Successfully added system to inventory"),
115        @APIResponse(responseCode = "400",
116            description = "Unable to add system to inventory")
117    })
118    @Parameters(value = {
119        @Parameter(
120            name = "hostname", in = ParameterIn.QUERY,
121            description = "The hostname of the system",
122            required = true, example = "localhost",
123            schema = @Schema(type = SchemaType.STRING)),
124        @Parameter(
125            name = "osName", in = ParameterIn.QUERY,
126            description = "The operating system of the system",
127            required = true, example = "linux",
128            schema = @Schema(type = SchemaType.STRING)),
129        @Parameter(
130            name = "javaVersion", in = ParameterIn.QUERY,
131            description = "The Java version of the system",
132            required = true, example = "17",
133            schema = @Schema(type = SchemaType.STRING)),
134        @Parameter(
135            name = "heapSize", in = ParameterIn.QUERY,
136            description = "The heap size of the system",
137            required = true, example = "1048576",
138            schema = @Schema(type = SchemaType.NUMBER)),
139    })
140    @Operation(
141        summary = "Add system",
142        description = "Add a system and its data to the inventory.",
143        operationId = "addSystem"
144    )
145    public Response addSystem(
146        @QueryParam("hostname") String hostname,
147        @QueryParam("osName") String osName,
148        @QueryParam("javaVersion") String javaVersion,
149        @QueryParam("heapSize") Long heapSize) {
150
151        SystemData s = inventory.getSystem(hostname);
152        if (s != null) {
153            return fail(hostname + " already exists.");
154        }
155        inventory.add(hostname, osName, javaVersion, heapSize);
156        return success(hostname + " was added.");
157    }
158
159    @PUT
160    @Path("/{hostname}")
161    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
162    @Produces(MediaType.APPLICATION_JSON)
163    @Transactional
164    @RolesAllowed({ "admin", "user" })
165    // tag::metricsUpdateSystem[]
166    @Counted(name = "updateSystem",
167             absolute = true,
168             description = "Number of times updating a system endpoint is called")
169    // end::metricsUpdateSystem[]
170    @APIResponses(value = {
171        @APIResponse(responseCode = "200",
172            description = "Successfully updated system"),
173        @APIResponse(responseCode = "400",
174           description =
175               "Unable to update because the system does not exist in the inventory.")
176    })
177    @Parameters(value = {
178        @Parameter(
179            name = "hostname", in = ParameterIn.PATH,
180            description = "The hostname of the system",
181            required = true, example = "localhost",
182            schema = @Schema(type = SchemaType.STRING)),
183        @Parameter(
184            name = "osName", in = ParameterIn.QUERY,
185            description = "The operating system of the system",
186            required = true, example = "linux",
187            schema = @Schema(type = SchemaType.STRING)),
188        @Parameter(
189            name = "javaVersion", in = ParameterIn.QUERY,
190            description = "The Java version of the system",
191            required = true, example = "17",
192            schema = @Schema(type = SchemaType.STRING)),
193        @Parameter(
194            name = "heapSize", in = ParameterIn.QUERY,
195            description = "The heap size of the system",
196            required = true, example = "1048576",
197            schema = @Schema(type = SchemaType.NUMBER)),
198    })
199    @Operation(
200        summary = "Update system",
201        description = "Update a system and its data on the inventory.",
202        operationId = "updateSystem"
203    )
204    public Response updateSystem(
205        @PathParam("hostname") String hostname,
206        @QueryParam("osName") String osName,
207        @QueryParam("javaVersion") String javaVersion,
208        @QueryParam("heapSize") Long heapSize) {
209
210        SystemData s = inventory.getSystem(hostname);
211        if (s == null) {
212            return fail(hostname + " does not exists.");
213        }
214        s.setOsName(osName);
215        s.setJavaVersion(javaVersion);
216        s.setHeapSize(heapSize);
217        inventory.update(s);
218        return success(hostname + " was updated.");
219    }
220
221    @DELETE
222    @Path("/{hostname}")
223    @Produces(MediaType.APPLICATION_JSON)
224    @Transactional
225    @RolesAllowed({ "admin" })
226    // tag::metricsRemoveSystem[]
227    @Counted(name = "removeSystem",
228             absolute = true,
229             description = "Number of times removing a system endpoint is called")
230    // end::metricsRemoveSystem[]
231    @APIResponses(value = {
232        @APIResponse(responseCode = "200",
233            description = "Successfully deleted the system from inventory"),
234        @APIResponse(responseCode = "400",
235            description =
236                "Unable to delete because the system does not exist in the inventory")
237    })
238    @Parameter(
239        name = "hostname", in = ParameterIn.PATH,
240        description = "The hostname of the system",
241        required = true, example = "localhost",
242        schema = @Schema(type = SchemaType.STRING)
243    )
244    @Operation(
245        summary = "Remove system",
246        description = "Removes a system from the inventory.",
247        operationId = "removeSystem"
248    )
249    public Response removeSystem(@PathParam("hostname") String hostname) {
250        SystemData s = inventory.getSystem(hostname);
251        if (s != null) {
252            inventory.removeSystem(s);
253            return success(hostname + " was removed.");
254        } else {
255            return fail(hostname + " does not exists.");
256        }
257    }
258
259    @POST
260    @Path("/client/{hostname}")
261    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
262    @Produces(MediaType.APPLICATION_JSON)
263    @Transactional
264    @RolesAllowed({ "admin" })
265    // tag::metricsAddSystemClient[]
266    @Counted(name = "addSystemClient",
267             absolute = true,
268             description = "Number of times adding a system by client is called")
269    // end::metricsAddSystemClient[]
270    @APIResponses(value = {
271        @APIResponse(responseCode = "200",
272            description = "Successfully added system client"),
273        @APIResponse(responseCode = "400",
274            description = "Unable to add system client")
275    })
276    @Parameter(
277        name = "hostname", in = ParameterIn.PATH,
278        description = "The hostname of the system",
279        required = true, example = "localhost",
280        schema = @Schema(type = SchemaType.STRING)
281    )
282    @Operation(
283        summary = "Add system client",
284        description = "This adds a system client.",
285        operationId = "addSystemClient"
286    )
287    public Response addSystemClient(@PathParam("hostname") String hostname) {
288
289        SystemData s = inventory.getSystem(hostname);
290        if (s != null) {
291            return fail(hostname + " already exists.");
292        }
293
294        SystemClient customRestClient = null;
295        try {
296            customRestClient = getSystemClient(hostname);
297        } catch (Exception e) {
298            return fail("Failed to create the client " + hostname + ".");
299        }
300
301        String authHeader = "Bearer " + jwt.getRawToken();
302        try {
303            String osName = customRestClient.getProperty(authHeader, "os.name");
304            String javaVer = customRestClient.getProperty(authHeader, "java.version");
305            Long heapSize = customRestClient.getHeapSize(authHeader);
306            inventory.add(hostname, osName, javaVer, heapSize);
307        } catch (Exception e) {
308            return fail("Failed to reach the client " + hostname + ".");
309        }
310        return success(hostname + " was added.");
311    }
312
313    private SystemClient getSystemClient(String hostname) throws Exception {
314        String customURIString = "https://" + hostname + ":" + CLIENT_PORT + "/system";
315        URI customURI = URI.create(customURIString);
316        return RestClientBuilder.newBuilder()
317                                .baseUri(customURI)
318                                .register(UnknownUriExceptionMapper.class)
319                                .build(SystemClient.class);
320    }
321
322    private Response success(String message) {
323        return Response.ok("{ \"ok\" : \"" + message + "\" }").build();
324    }
325
326    private Response fail(String message) {
327        return Response.status(Response.Status.BAD_REQUEST)
328                       .entity("{ \"error\" : \"" + message + "\" }")
329                       .build();
330    }
331}

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 mvn liberty:dev 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 Docker container is creating a Dockerfile. A Dockerfile is a collection of instructions for building a Docker image that can then be run as a container.

Make sure to start your Docker daemon before you proceed.

Replace the Dockerfile in the start/inventory directory.
Dockerfile

Dockerfile

 1# tag::from[]
 2FROM icr.io/appcafe/open-liberty:full-java17-openj9-ubi
 3# end::from[]
 4
 5ARG VERSION=1.0
 6ARG REVISION=SNAPSHOT
 7
 8# tag::label[]
 9LABEL \
10  org.opencontainers.image.authors="My Name" \
11  org.opencontainers.image.vendor="Open Liberty" \
12  org.opencontainers.image.url="local" \
13  org.opencontainers.image.source="https://github.com/OpenLiberty/draft-guide-liberty-deepdive" \
14  org.opencontainers.image.version="$VERSION" \
15  org.opencontainers.image.revision="$REVISION" \
16  vendor="Open Liberty" \
17  name="inventory" \
18  version="$VERSION-$REVISION" \
19  summary="" \
20  description="This image contains the inventory microservice running with the Open Liberty runtime."
21# end::label[]
22
23USER root
24
25# tag::copy[]
26# tag::copy-config[]
27# tag::config-userID[]
28COPY --chown=1001:0 \
29# end::config-userID[]
30    # tag::inventory-config[]
31    src/main/liberty/config/ \
32    # end::inventory-config[]
33    # tag::config[]
34    /config/
35    # end::config[]
36# end::copy-config[]
37
38# tag::copy-war[]
39# tag::war-userID[]
40COPY --chown=1001:0 \
41# end::war-userID[]
42    # tag::inventory-war[]
43    target/inventory.war \
44    # end::inventory-war[]
45    # tag::config-apps[]
46    /config/apps
47    # end::config-apps[]
48# end::copy-war[]
49
50# tag::copy-postgres[]
51COPY --chown=1001:0 \
52    target/liberty/wlp/usr/shared/resources/*.jar \
53    /opt/ol/wlp/usr/shared/resources/
54# end::copy-postgres[]
55# end::copy[]
56
57USER 1001
58
59RUN configure.sh

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-java17-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 Docker image. In this case, the first COPY instruction copies the Liberty 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.

Developing the application in a container

Make the PostgreSQL database configurable in the Liberty server.xml configuraton file.

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

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7        <feature>jwtSso-1.0</feature>
 8    </featureManager>
 9
10    <variable name="http.port" defaultValue="9080" />
11    <variable name="https.port" defaultValue="9443" />
12    <!-- tag::contextRoot[] -->
13    <variable name="context.root" defaultValue="/inventory" />
14    <!-- end::contextRoot[] -->
15    <!-- tag::variables[] -->
16    <variable name="postgres/hostname" defaultValue="localhost" />
17    <variable name="postgres/portnum" defaultValue="5432" />
18    <variable name="postgres/username" defaultValue="admin" />
19    <variable name="postgres/password" defaultValue="adminpwd" />
20    <!-- end::variables[] -->
21
22    <httpEndpoint id="defaultHttpEndpoint"
23                  httpPort="${http.port}" 
24                  httpsPort="${https.port}" />
25
26    <!-- Automatically expand WAR files and EAR files -->
27    <applicationManager autoExpand="true"/>
28
29    <basicRegistry id="basic" realm="WebRealm">
30        <user name="bob" password="{xor}PTA9Lyg7" />
31        <user name="alice" password="{xor}PjM2PDovKDs=" />
32
33        <group name="admin">
34            <member name="bob" />
35        </group>
36
37        <group name="user">
38            <member name="bob" />
39            <member name="alice" />
40        </group>
41    </basicRegistry>
42
43    <!-- Configures the application on a specified context root -->
44    <webApplication contextRoot="${context.root}"
45                    location="inventory.war">
46        <application-bnd>
47            <security-role name="admin">
48                <group name="admin" />
49            </security-role>
50            <security-role name="user">
51                <group name="user" />
52            </security-role>
53        </application-bnd>
54    </webApplication>
55
56    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
57    <ssl id="guideSSLConfig" keyStoreRef="guideKeyStore" trustDefaultCerts="true" />
58    <sslDefault sslRef="guideSSLConfig" />
59
60    <keyStore id="guideKeyStore"
61              password="secret"
62              location="${server.config.dir}/resources/security/key.p12" />
63
64    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/>
65    <jwtBuilder id="jwtInventoryBuilder" 
66                issuer="http://openliberty.io" 
67                audiences="systemService"
68                expiry="24h"/>
69    <mpJwt audiences="systemService" 
70           groupNameAttribute="groups" 
71           id="myMpJwt"
72           sslRef="guideSSLConfig"
73           issuer="http://openliberty.io"/>
74
75    <library id="postgresql-library">
76        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
77    </library>
78
79    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
80        <jdbcDriver libraryRef="postgresql-library" />
81        <!-- tag::postgresProperties[] -->
82        <properties.postgresql databaseName="admin"
83                               serverName="${postgres/hostname}"
84                               portNumber="${postgres/portnum}"
85                               user="${postgres/username}"
86                               password="${postgres/password}"/>
87        <!-- end::postgresProperties[] -->
88    </dataSource>
89</server>

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.

You can use the Dockerfile to try out your application with the PostGreSQL database by running the devc goal.

The Open Liberty Maven plug-in includes a devc goal that simplifies developing your application in a container by starting dev mode with container support. This goal builds a Docker image, mounts the required directories, binds the required ports, and then runs the application inside of a container. Dev mode also listens for any changes in the application source code or configuration and rebuilds the image and restarts the container as necessary.

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

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

The command returns the PostgreSQL container IP address:

172.17.0.2

Build and run the container by running the devc goal with the PostgreSQL container IP address from the start/inventory directory. If your PostgreSQL container IP address is not 172.17.0.2, replace the command with the right IP address.

mvn liberty:devc -DdockerRunOpts="-e POSTGRES_HOSTNAME=172.17.0.2" -DserverStartTimeout=240

You need to wait a while to let dev mode start. After you see the following message, your Liberty instance is ready in dev mode:

**************************************************************
*    Liberty is running in dev mode.
*    ...
*    Docker network information:
*        Container name: [ liberty-dev ]
*        IP address [ 172.17.0.2 ] on Docker network [ bridge ]
*    ...

Open another command-line session and run the following command to make sure that your container is running and didn’t crash:

docker ps

You can see something similar to the following output:

CONTAINER ID  IMAGE               COMMAND                 CREATED        STATUS        PORTS                                                                   NAMES
ee2daf0b33e1  inventory-dev-mode  "/opt/ol/helpers/run…"  2 minutes ago  Up 2 minutes  0.0.0.0:7777->7777/tcp, 0.0.0.0:9080->9080/tcp, 0.0.0.0:9443->9443/tcp  liberty-dev

Point your browser to the http://localhost:9080/openapi/ui URL to try out your application.

When you’re finished trying out the microservice, press CTRL+C in the command-line session where you started dev mode to stop and remove the container.

Also, run the following commands to stop the PostgreSQL container that was started in the previous section.

docker stop postgres-container
docker rm postgres-container

Building the container image

Run the mvn package command from the start/inventory directory so that the .war file resides in the target directory.

mvn package

Build your Docker image with the following commands:

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

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

docker images

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

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

Testing the microservice with Testcontainers

Although you can test your microservice manually, you should rely on automated tests. In this section, you can learn how to use Testcontainers to verify your microservice in the same Docker container that you’ll use in production.

First, create the test directory at the src directory of your Maven project.

mkdir src\test\java\it\io\openliberty\deepdive\rest
mkdir src\test\resources
mkdir -p src/test/java/it/io/openliberty/deepdive/rest
mkdir src/test/resources

Create a RESTful client interface for the inventory microservice.

Create the SystemResourceClient.java file.
src/test/java/it/io/openliberty/deepdive/rest/SystemResourceClient.java

SystemResourceClient.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package it.io.openliberty.deepdive.rest;
13
14import java.util.List;
15
16import jakarta.annotation.security.RolesAllowed;
17import jakarta.enterprise.context.ApplicationScoped;
18import jakarta.ws.rs.Consumes;
19import jakarta.ws.rs.DELETE;
20import jakarta.ws.rs.GET;
21import jakarta.ws.rs.HeaderParam;
22import jakarta.ws.rs.POST;
23import jakarta.ws.rs.PUT;
24import jakarta.ws.rs.Path;
25import jakarta.ws.rs.PathParam;
26import jakarta.ws.rs.Produces;
27import jakarta.ws.rs.QueryParam;
28import jakarta.ws.rs.core.MediaType;
29import jakarta.ws.rs.core.Response;
30
31
32@ApplicationScoped
33@Path("/systems")
34public interface SystemResourceClient {
35
36    // tag::listContents[]
37    @GET
38    @Path("/")
39    @Produces(MediaType.APPLICATION_JSON)
40    List<SystemData> listContents();
41    // end::listContents[]
42
43    // tag::getSystem[]
44    @GET
45    @Path("/{hostname}")
46    @Produces(MediaType.APPLICATION_JSON)
47    SystemData getSystem(
48        @PathParam("hostname") String hostname);
49    // end::getSystem[]
50
51    // tag::addSystem[]
52    @POST
53    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
54    @Produces(MediaType.APPLICATION_JSON)
55    Response addSystem(
56        @QueryParam("hostname") String hostname,
57        @QueryParam("osName") String osName,
58        @QueryParam("javaVersion") String javaVersion,
59        @QueryParam("heapSize") Long heapSize);
60    // end::addSystem[]
61
62    // tag::updateSystem[]
63    @PUT
64    @Path("/{hostname}")
65    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
66    @Produces(MediaType.APPLICATION_JSON)
67    @RolesAllowed({ "admin", "user" })
68    Response updateSystem(
69        @HeaderParam("Authorization") String authHeader,
70        @PathParam("hostname") String hostname,
71        @QueryParam("osName") String osName,
72        @QueryParam("javaVersion") String javaVersion,
73        @QueryParam("heapSize") Long heapSize);
74    // end::updateSystem[]
75
76    // tag::removeSystem[]
77    @DELETE
78    @Path("/{hostname}")
79    @Produces(MediaType.APPLICATION_JSON)
80    @RolesAllowed({ "admin" })
81    Response removeSystem(
82        @HeaderParam("Authorization") String authHeader,
83        @PathParam("hostname") String hostname);
84    // end::removeSystem[]
85}

This interface declares listContents(), getSystem(), addSystem(), updateSystem(), and removeSystem() methods for accessing each of the endpoints that are set up to access the inventory microservice.

Create the SystemData data model for each system in the inventory.

Create the SystemData.java file.
src/test/java/it/io/openliberty/deepdive/rest/SystemData.java

SystemData.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022, 2023 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package it.io.openliberty.deepdive.rest;
13
14public class SystemData {
15
16    // tag::fields[]
17    private int id;
18    private String hostname;
19    private String osName;
20    private String javaVersion;
21    private Long heapSize;
22    // end::fields[]
23
24    public SystemData() {
25    }
26
27    // tag::getMethods[]
28    public int getId() {
29        return id;
30    }
31
32    public String getHostname() {
33        return hostname;
34    }
35
36    public String getOsName() {
37        return osName;
38    }
39
40    public String getJavaVersion() {
41        return javaVersion;
42    }
43
44    public Long getHeapSize() {
45        return heapSize;
46    }
47    // end::getMethods[]
48
49    // tag::setMethods[]
50    public void setId(int id) {
51        this.id = id;
52    }
53
54    public void setHostname(String hostname) {
55        this.hostname = hostname;
56    }
57
58    public void setOsName(String osName) {
59        this.osName = osName;
60    }
61
62    public void setJavaVersion(String javaVersion) {
63        this.javaVersion = javaVersion;
64    }
65
66    public void setHeapSize(Long heapSize) {
67        this.heapSize = heapSize;
68    }
69    // end::setMethods[]
70}

The SystemData class contains the ID, hostname, operating system name, Java version, and heap size properties. The various get and set methods within this class enable you to view and edit the properties of each system in the inventory.

Create the test container class that access the inventory docker image that you built in previous section.

Create the LibertyContainer.java file.
src/test/java/it/io/openliberty/deepdive/rest/LibertyContainer.java

LibertyContainer.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.deepdive.rest;
 13
 14import java.io.FileInputStream;
 15import java.security.KeyStore;
 16import java.security.SecureRandom;
 17import java.security.cert.CertificateException;
 18import java.security.cert.X509Certificate;
 19
 20import javax.net.ssl.HostnameVerifier;
 21import javax.net.ssl.KeyManagerFactory;
 22import javax.net.ssl.SSLContext;
 23import javax.net.ssl.SSLSession;
 24import javax.net.ssl.TrustManager;
 25import javax.net.ssl.X509TrustManager;
 26
 27// imports for a JAXRS client to simplify the code
 28import org.jboss.resteasy.client.jaxrs.ResteasyClient;
 29import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
 30import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
 31// logger imports
 32import org.slf4j.Logger;
 33import org.slf4j.LoggerFactory;
 34// testcontainers imports
 35import org.testcontainers.containers.GenericContainer;
 36import org.testcontainers.containers.wait.strategy.Wait;
 37
 38import jakarta.ws.rs.client.ClientBuilder;
 39// simple import to build a URI/URL
 40import jakarta.ws.rs.core.UriBuilder;
 41
 42public class LibertyContainer extends GenericContainer<LibertyContainer> {
 43
 44    static final Logger LOGGER = LoggerFactory.getLogger(LibertyContainer.class);
 45
 46    private String baseURL;
 47
 48    private KeyStore keystore;
 49    private SSLContext sslContext;
 50
 51    public static String getProtocol() {
 52        return System.getProperty("test.protocol", "https");
 53    }
 54
 55    public static boolean testHttps() {
 56        return getProtocol().equalsIgnoreCase("https");
 57    }
 58
 59    public LibertyContainer(final String dockerImageName) {
 60        super(dockerImageName);
 61        // wait for smarter planet message by default
 62        waitingFor(Wait.forLogMessage("^.*CWWKF0011I.*$", 1));
 63        init();
 64    }
 65
 66    // tag::createRestClient[]
 67    public <T> T createRestClient(Class<T> clazz, String applicationPath) {
 68        String urlPath = getBaseURL();
 69        if (applicationPath != null) {
 70            urlPath += applicationPath;
 71        }
 72        ClientBuilder builder = ResteasyClientBuilder.newBuilder();
 73        if (testHttps()) {
 74            builder.sslContext(sslContext);
 75            builder.trustStore(keystore);
 76            builder.hostnameVerifier(new HostnameVerifier() {
 77                @Override
 78                public boolean verify(String hostname, SSLSession session) {
 79                    return true;
 80                }
 81            });
 82        }
 83        ResteasyClient client = (ResteasyClient) builder.build();
 84        ResteasyWebTarget target = client.target(UriBuilder.fromPath(urlPath));
 85        return target.proxy(clazz);
 86    }
 87    // end::createRestClient[]
 88
 89    // tag::getBaseURL[]
 90    public String getBaseURL() throws IllegalStateException {
 91        if (baseURL != null) {
 92            return baseURL;
 93        }
 94        if (!this.isRunning()) {
 95            throw new IllegalStateException(
 96                "Container must be running to determine hostname and port");
 97        }
 98        baseURL =  getProtocol() + "://" + this.getHost()
 99            + ":" + this.getFirstMappedPort();
100        System.out.println("TEST: " + baseURL);
101        return baseURL;
102    }
103    // end::getBaseURL[]
104
105    private void init() {
106
107        if (!testHttps()) {
108            this.addExposedPorts(9080);
109            return;
110        }
111
112        this.addExposedPorts(9443, 9080);
113        try {
114            String keystoreFile = System.getProperty("user.dir")
115                    + "/../../finish/system/src/main"
116                    + "/liberty/config/resources/security/key.p12";
117            keystore = KeyStore.getInstance("PKCS12");
118            keystore.load(new FileInputStream(keystoreFile), "secret".toCharArray());
119            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
120                                        KeyManagerFactory.getDefaultAlgorithm());
121            kmf.init(keystore, "secret".toCharArray());
122            X509TrustManager xtm = new X509TrustManager() {
123                @Override
124                public void checkClientTrusted(X509Certificate[] chain, String authType)
125                    throws CertificateException { }
126
127                @Override
128                public void checkServerTrusted(X509Certificate[] chain, String authType)
129                    throws CertificateException { }
130
131                @Override
132                public X509Certificate[] getAcceptedIssuers() {
133                    return null;
134                }
135            };
136            TrustManager[] tm = new TrustManager[] {
137                                    xtm
138                                };
139            sslContext = SSLContext.getInstance("TLS");
140            sslContext.init(kmf.getKeyManagers(), tm, new SecureRandom());
141        } catch (Exception e) {
142            e.printStackTrace();
143        }
144    }
145}

The createRestClient() method creates a REST client instance with the SystemResourceClient interface. The getBaseURL() method constructs the URL that can access the inventory docker image.

Now, you can create your integration test cases.

Create the SystemResourceIT.java file.
src/test/java/it/io/openliberty/deepdive/rest/SystemResourceIT.java

SystemResourceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2022, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.deepdive.rest;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import java.util.Base64;
 17import java.util.List;
 18
 19import org.junit.jupiter.api.BeforeAll;
 20import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 21import org.junit.jupiter.api.Order;
 22import org.junit.jupiter.api.Test;
 23import org.junit.jupiter.api.TestMethodOrder;
 24import org.slf4j.Logger;
 25import org.slf4j.LoggerFactory;
 26import org.testcontainers.containers.GenericContainer;
 27import org.testcontainers.containers.Network;
 28import org.testcontainers.containers.output.Slf4jLogConsumer;
 29import org.testcontainers.containers.wait.strategy.Wait;
 30import org.testcontainers.junit.jupiter.Container;
 31import org.testcontainers.junit.jupiter.Testcontainers;
 32
 33@Testcontainers
 34@TestMethodOrder(OrderAnnotation.class)
 35public class SystemResourceIT {
 36
 37    private static Logger logger = LoggerFactory.getLogger(SystemResourceIT.class);
 38    private static String appPath = "/inventory/api";
 39    private static String postgresHost = "postgres";
 40    private static String postgresImageName = "postgres-sample:latest";
 41    private static String appImageName = "liberty-deepdive-inventory:1.0-SNAPSHOT";
 42
 43    public static SystemResourceClient client;
 44    // tag::network[]
 45    public static Network network = Network.newNetwork();
 46    // end::network[]
 47    private static String authHeader;
 48
 49    // tag::postgresSetup[]
 50    @Container
 51    public static GenericContainer<?> postgresContainer
 52        = new GenericContainer<>(postgresImageName)
 53              // tag::pNetwork[]
 54              .withNetwork(network)
 55              // end::pNetwork[]
 56              .withExposedPorts(5432)
 57              .withNetworkAliases(postgresHost)
 58              .withLogConsumer(new Slf4jLogConsumer(logger));
 59    // end::postgresSetup[]
 60
 61    // tag::libertySetup[]
 62    @Container
 63    public static LibertyContainer libertyContainer
 64        = new LibertyContainer(appImageName)
 65              .withEnv("POSTGRES_HOSTNAME", postgresHost)
 66              // tag::lNetwork[]
 67              .withNetwork(network)
 68              // end::lNetwork[]
 69              // tag::health[]
 70              .waitingFor(Wait.forHttp("/health/ready").forPort(9080))
 71              // end::health[]
 72              .withLogConsumer(new Slf4jLogConsumer(logger));
 73    // end::libertySetup[]
 74
 75    @BeforeAll
 76    public static void setupTestClass() throws Exception {
 77        System.out.println("TEST: Starting Liberty Container setup");
 78        client = libertyContainer.createRestClient(
 79            SystemResourceClient.class, appPath);
 80        String userPassword = "bob" + ":" + "bobpwd";
 81        authHeader = "Basic "
 82            + Base64.getEncoder().encodeToString(userPassword.getBytes());
 83    }
 84
 85    private void showSystemData(SystemData system) {
 86        System.out.println("TEST: SystemData > "
 87            + system.getId() + ", "
 88            + system.getHostname() + ", "
 89            + system.getOsName() + ", "
 90            + system.getJavaVersion() + ", "
 91            + system.getHeapSize());
 92    }
 93
 94    // tag::testAddSystem[]
 95    @Test
 96    @Order(1)
 97    public void testAddSystem() {
 98        System.out.println("TEST: Testing add a system");
 99        // tag::addSystem[]
100        client.addSystem("localhost", "linux", "17", Long.valueOf(2048));
101        // end::addSystem[]
102        // tag::listContents[]
103        List<SystemData> systems = client.listContents();
104        // end::listContents[]
105        assertEquals(1, systems.size());
106        showSystemData(systems.get(0));
107        assertEquals("17", systems.get(0).getJavaVersion());
108        assertEquals(Long.valueOf(2048), systems.get(0).getHeapSize());
109    }
110    // end::testAddSystem[]
111
112    // tag::testUpdateSystem[]
113    @Test
114    @Order(2)
115    public void testUpdateSystem() {
116        System.out.println("TEST: Testing update a system");
117        // tag::updateSystem[]
118        client.updateSystem(authHeader, "localhost", "linux", "8", Long.valueOf(1024));
119        // end::updateSystem[]
120        // tag::getSystem[]
121        SystemData system = client.getSystem("localhost");
122        // end::getSystem[]
123        showSystemData(system);
124        assertEquals("8", system.getJavaVersion());
125        assertEquals(Long.valueOf(1024), system.getHeapSize());
126    }
127    // end::testUpdateSystem[]
128
129    // tag::testRemoveSystem[]
130    @Test
131    @Order(3)
132    public void testRemoveSystem() {
133        System.out.println("TEST: Testing remove a system");
134        // tag::removeSystem[]
135        client.removeSystem(authHeader, "localhost");
136        // end::removeSystem[]
137        List<SystemData> systems = client.listContents();
138        assertEquals(0, systems.size());
139    }
140    // end::testRemoveSystem[]
141}

Define the postgresContainer test container to start up the PostgreSQL docker image, and define the libertyContainer test container to start up the inventory docker image. Make sure that both containers use the same network. The /health/ready endpoint can tell you whether the container is ready to start testing.

The testAddSystem() verifies the addSystem and listContents endpoints.

The testUpdateSystem() verifies the updateSystem and getSystem endpoints.

The testRemoveSystem() verifies the removeSystem endpoint.

Create the log4j properites that are required by the Testcontainers framework.

Create the log4j.properties file.
src/test/resources/log4j.properties

log4j.properties

 1log4j.rootLogger=INFO, stdout
 2
 3log4j.appender=org.apache.log4j.ConsoleAppender
 4log4j.appender.layout=org.apache.log4j.PatternLayout
 5
 6log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 7log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 8log4j.appender.stdout.layout.ConversionPattern=%r %p %c %x - %m%n
 9
10log4j.logger.io.openliberty.guides.testing=DEBUG

Update the Maven configuration file with the required dependencies.

Replace the pom.xml file.
pom.xml

pom.xml

  1<?xml version="1.0" encoding="UTF-8" ?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0"
  3               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5
  6    <modelVersion>4.0.0</modelVersion>
  7
  8    <groupId>io.openliberty.deepdive</groupId>
  9    <artifactId>inventory</artifactId>
 10    <packaging>war</packaging>
 11    <version>1.0-SNAPSHOT</version>
 12
 13    <properties>
 14        <maven.compiler.source>17</maven.compiler.source>
 15        <maven.compiler.target>17</maven.compiler.target>
 16        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 17        <liberty.var.http.port>9080</liberty.var.http.port>
 18        <liberty.var.https.port>9443</liberty.var.https.port>
 19        <liberty.var.context.root>/inventory</liberty.var.context.root>
 20        <liberty.var.client.https.port>9444</liberty.var.client.https.port>
 21    </properties>
 22
 23    <dependencies>
 24        <dependency>
 25            <groupId>jakarta.platform</groupId>
 26            <artifactId>jakarta.jakartaee-api</artifactId>
 27            <version>10.0.0</version>
 28            <scope>provided</scope>
 29        </dependency>
 30        <dependency>
 31            <groupId>org.eclipse.microprofile</groupId>
 32            <artifactId>microprofile</artifactId>
 33            <version>6.1</version>
 34            <type>pom</type>
 35            <scope>provided</scope>
 36        </dependency>
 37        <dependency>
 38            <groupId>org.postgresql</groupId>
 39            <artifactId>postgresql</artifactId>
 40            <version>42.7.2</version>
 41            <scope>provided</scope>
 42        </dependency>
 43        
 44        <!-- tag::testDependenies[] -->
 45        <!-- Test dependencies -->
 46        <dependency>
 47            <groupId>org.junit.jupiter</groupId>
 48            <artifactId>junit-jupiter</artifactId>
 49            <version>5.10.1</version>
 50            <scope>test</scope>
 51        </dependency>
 52        <dependency>
 53            <groupId>org.testcontainers</groupId>
 54            <artifactId>testcontainers</artifactId>
 55            <version>1.19.3</version>
 56            <scope>test</scope>
 57        </dependency>
 58        <dependency>
 59            <groupId>org.testcontainers</groupId>
 60            <artifactId>junit-jupiter</artifactId>
 61            <version>1.19.3</version>
 62            <scope>test</scope>
 63        </dependency>
 64        <dependency>
 65            <groupId>org.slf4j</groupId>
 66            <artifactId>slf4j-reload4j</artifactId>
 67            <version>2.0.9</version>
 68            <scope>test</scope>
 69        </dependency>
 70        <dependency>
 71            <groupId>org.slf4j</groupId>
 72            <artifactId>slf4j-api</artifactId>
 73            <version>2.0.9</version>
 74        </dependency>
 75        <dependency>
 76            <groupId>org.jboss.resteasy</groupId>
 77            <artifactId>resteasy-client</artifactId>
 78            <version>6.2.6.Final</version>
 79            <scope>test</scope>
 80        </dependency>
 81        <dependency>
 82            <groupId>org.jboss.resteasy</groupId>
 83            <artifactId>resteasy-json-binding-provider</artifactId>
 84            <version>6.2.6.Final</version>
 85            <scope>test</scope>
 86        </dependency>
 87        <dependency>
 88            <groupId>org.glassfish</groupId>
 89            <artifactId>jakarta.json</artifactId>
 90            <version>2.0.1</version>
 91            <scope>test</scope>
 92        </dependency>
 93        <dependency>
 94            <groupId>org.eclipse</groupId>
 95            <artifactId>yasson</artifactId>
 96            <version>3.0.3</version>
 97            <scope>test</scope>
 98        </dependency>
 99        <dependency>
100            <groupId>cglib</groupId>
101            <artifactId>cglib-nodep</artifactId>
102            <version>3.3.0</version>
103            <scope>test</scope>
104        </dependency>
105        <dependency>
106            <groupId>io.vertx</groupId>
107            <artifactId>vertx-auth-jwt</artifactId>
108            <version>4.5.0</version>
109            <scope>test</scope>
110        </dependency>
111        <!-- end::testDependenies[] -->
112    </dependencies>
113
114    <build>
115        <finalName>inventory</finalName>
116        <pluginManagement>
117            <plugins>
118                <plugin>
119                    <groupId>org.apache.maven.plugins</groupId>
120                    <artifactId>maven-war-plugin</artifactId>
121                    <version>3.3.2</version>
122                </plugin>
123                <plugin>
124                    <groupId>io.openliberty.tools</groupId>
125                    <artifactId>liberty-maven-plugin</artifactId>
126                    <version>3.10.2</version>
127                </plugin>
128            </plugins>
129        </pluginManagement>
130        <plugins>
131            <plugin>
132                <groupId>io.openliberty.tools</groupId>
133                <artifactId>liberty-maven-plugin</artifactId>
134                <configuration>
135                    <copyDependencies>
136                        <dependencyGroup>
137                            <location>${project.build.directory}/liberty/wlp/usr/shared/resources</location>
138                            <dependency>
139                                <groupId>org.postgresql</groupId>
140                                <artifactId>postgresql</artifactId>
141                                <version>42.7.2</version>
142                            </dependency>
143                        </dependencyGroup>
144                    </copyDependencies>
145                </configuration>
146            </plugin>
147            <!-- tag::failsafe[] -->
148            <plugin>
149                <groupId>org.apache.maven.plugins</groupId>
150                <artifactId>maven-failsafe-plugin</artifactId>
151                <version>3.2.2</version>
152                <executions>
153                    <execution>
154                        <goals>
155                            <goal>integration-test</goal>
156                            <goal>verify</goal>
157                        </goals>
158                    </execution>
159                </executions>
160            </plugin>
161            <!-- end::failsafe[] -->
162        </plugins>
163    </build>
164</project>

Add each required dependency with test scope, including JUnit5, Testcontainers, Log4J, JBoss RESTEasy client, Glassfish JSON, and Vert.x libraries. Also, add the maven-failsafe-plugin plugin, so that the integration test can be run by the Maven verify goal.

Running the tests

You can run the Maven verify goal, which compiles the java files, starts the containers, runs the tests, and then stops the containers.

mvn verify
export TESTCONTAINERS_RYUK_DISABLED=true
mvn verify

You will see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.deepdive.rest.SystemResourceIT
...
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.413 s - in it.io.openliberty.deepdive.rest.SystemResourceIT

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

Starting and preparing your cluster for deployment

If you are using Linux, you can continue this section.

Start your Kubernetes cluster.

Run the following command from a command-line session:

minikube start

Next, validate that you have a healthy Kubernetes environment by running the following command from the active command-line session.

kubectl get nodes

This command should return a Ready status for the minikube node.

Run the following command to configure the Docker CLI to use Minikube’s Docker daemon. After you run this command, you will be able to interact with Minikube’s Docker daemon and build new images directly to it from your host machine:

eval $(minikube docker-env)

Rebuild your Docker image under Minikube with the following commands:

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

Deploying the microservice to Kubernetes

If you are using Linux, you can continue this section.

Now that the containerized application is built and tested, deploy it to a local Kubernetes cluster.

Installing the Open Liberty Operator

Install the Open Liberty Operator to deploy the microservice to Kubernetes.

First, install the cert-manager to your Kubernetes cluster by running the following command:

kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.12.3/cert-manager.yaml

Next, install Custom Resource Definitions (CRDs) for the Open Liberty Operator by running the following command:

kubectl apply --server-side -f https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-crd.yaml

Custom Resources extend the Kubernetes API and enhance its functionality.

Set environment variables for namespaces for the Open Liberty Operator by running the following commands:

OPERATOR_NAMESPACE=default
WATCH_NAMESPACE='""'

Next, run the following commands to install cluster-level role-based access:

curl -L https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-rbac-watch-all.yaml \
  | sed -e "s/OPEN_LIBERTY_OPERATOR_NAMESPACE/${OPERATOR_NAMESPACE}/" \
  | kubectl apply -f -

Finally, run the following commands to install the Operator:

curl -L https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-operator.yaml \
  | sed -e "s/OPEN_LIBERTY_WATCH_NAMESPACE/${WATCH_NAMESPACE}/" \
  | kubectl apply -n ${OPERATOR_NAMESPACE} -f -

To check that the Open Liberty Operator is installed successfully, run the following command to view all the supported API resources that are available through the Open Liberty Operator:

kubectl api-resources --api-group=apps.openliberty.io

Look for the following output, which shows the custom resource definitions (CRDs) that can be used by the Open Liberty Operator:

NAME                      SHORTNAMES         APIGROUP              NAMESPACED   KIND
openlibertyapplications   olapp,olapps       apps.openliberty.io   true         OpenLibertyApplication
openlibertydumps          oldump,oldumps     apps.openliberty.io   true         OpenLibertyDump
openlibertytraces         oltrace,oltraces   apps.openliberty.io   true         OpenLibertyTrace

Each CRD defines a kind of object that can be used, which is specified in the previous example by the KIND value. The SHORTNAME value specifies alternative names that you can substitute in the configuration to refer to an object kind. For example, you can refer to the OpenLibertyApplication object kind by one of its specified shortnames, such as olapps.

The openlibertyapplications CRD defines a set of configurations for deploying an Open Liberty-based application, including the application image, number of instances, and storage settings. The Open Liberty Operator watches for changes to instances of the OpenLibertyApplication object kind and creates Kubernetes resources that are based on the configuration that is defined in the CRD.

Deploying the container image

Create the inventory.yaml in the start/inventory directory.
inventory.yaml

inventory.yaml

 1apiVersion: apps.openliberty.io/v1
 2# tag::kind[]
 3kind: OpenLibertyApplication
 4# end::kind[]
 5metadata:
 6  name: inventory-deployment
 7  labels:
 8    name: inventory-deployment
 9spec:
10  # tag::applicationImage[]
11  applicationImage: liberty-deepdive-inventory:1.0-SNAPSHOT
12  # end::applicationImage[]
13  service:
14    port: 9443
15  env:
16    - name: POSTGRES_HOSTNAME
17      value: "postgres"

In the inventory.yaml file, the custom resource (CR) is specified to be OpenLibertyApplication. The CR triggers the Open Liberty Operator to create, update, or delete Kubernetes resources that are needed by the application to run on your cluster. Additionally, the applicationImage field must be specified and set to the image that was created in the previous module.

postgres.yaml

 1kind: ConfigMap
 2apiVersion: v1
 3metadata:
 4  namespace: default
 5  name: poststarthook
 6data:
 7  schema.sql: |
 8    CREATE TABLE SystemData (
 9        id SERIAL,
10        hostname varchar(50),
11        osName varchar(50),
12        javaVersion varchar(50),
13        heapSize bigint,
14        primary key(id)
15    );
16
17    CREATE SEQUENCE systemData_id
18    START 1
19    INCREMENT 1
20    OWNED BY SystemData.id;
21---
22# tag::deployment[]
23apiVersion: apps/v1
24kind: Deployment
25metadata:
26  name: postgres
27  labels:
28    app: postgres
29    group: db
30spec:
31  replicas: 1
32  selector:
33    matchLabels:
34      app: postgres
35  template:
36    metadata:
37      labels:
38        app: postgres
39        type: db
40    spec:
41      volumes:                             
42        - name: hookvolume
43          configMap:
44            name: poststarthook
45            defaultMode: 0755
46      containers:
47        - name: postgres
48          image: postgres:16.1
49          ports:
50            - containerPort: 5432
51          volumeMounts:
52            - name: hookvolume
53              mountPath: /docker-entrypoint-initdb.d
54          # tag::env[]
55          env:
56            - name: POSTGRES_USER
57              valueFrom:
58                secretKeyRef:
59                  name: post-app-credentials
60                  key: username
61            - name: POSTGRES_PASSWORD
62              valueFrom:
63                secretKeyRef:
64                  name: post-app-credentials
65                  key: password
66          # end::env[]
67# end::deployment[]
68---
69# tag::service[]
70apiVersion: v1
71kind: Service
72metadata:
73  name: postgres
74  labels: 
75    group: db
76spec:
77  type: ClusterIP
78  selector:             
79    app: postgres
80  ports:
81  - protocol: TCP
82    port: 5432
83# tag::service[]

Similarly, a Kubernetes resource definition is provided in the postgres.yaml file at the finish/postgres directory. In the postgres.yaml file, the deployment for the PostgreSQL database is defined.

Create a Kubernetes Secret to configure the credentials for the admin user to access the database.

kubectl create secret generic post-app-credentials --from-literal username=admin --from-literal password=adminpwd

The credentials are passed to the PostgreSQL database service as environment variables in the env field.

Run the following command to deploy the application and database:

kubectl apply -f ../../finish/postgres/postgres.yaml
kubectl apply -f inventory.yaml

When your pods are deployed, run the following command to check their status:

kubectl get pods

If all the pods are working correctly, you see an output similar to the following example:

NAME                                    READY   STATUS    RESTARTS   AGE
inventory-deployment-75f9dc56d9-g9lzl   1/1     Running   0          35s
postgres-58bd9b55c7-6vzz8               1/1     Running   0          13s
olo-controller-manager-6fc6b456dc-s29wl 1/1     Running   0          10m

Pause briefly to give the inventory service time to initialize. After it has started, use the following command to configure port forwarding to access the inventory microservice:

kubectl port-forward svc/inventory-deployment 9443

The port-forward command pauses the command-line session until you press Ctrl+C after you try out the microservice.

The application might take some time to get ready. See the https://localhost:9443/health URL to confirm that the inventory microservice is up and running.

Once your application is up and running, you can check out the service at the https://localhost:9443/openapi/ui/ URL. The servers dropdown list shows the https://localhost:9443/inventory URL. Or, you can run the following command to access the inventory microservice:

curl -k https://localhost:9443/inventory/api/systems

When you’re done trying out the microservice, press CTRL+C in the command line session where you ran the kubectl port-forward command to stop the port forwarding. Then, run the kubectl delete command to stop the inventory microservice.

kubectl delete -f inventory.yaml

Customizing deployments

server.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<server description="inventory">
 3
 4    <featureManager>
 5        <feature>jakartaee-10.0</feature>
 6        <feature>microProfile-6.1</feature>
 7        <feature>jwtSso-1.0</feature>
 8    </featureManager>
 9
10    <variable name="http.port" defaultValue="9080" />
11    <variable name="https.port" defaultValue="9443" />
12    <!-- tag::contextRoot[] -->
13    <variable name="context.root" defaultValue="/inventory" />
14    <!-- end::contextRoot[] -->
15    <!-- tag::variables[] -->
16    <variable name="postgres/hostname" defaultValue="localhost" />
17    <variable name="postgres/portnum" defaultValue="5432" />
18    <variable name="postgres/username" defaultValue="admin" />
19    <variable name="postgres/password" defaultValue="adminpwd" />
20    <!-- end::variables[] -->
21
22    <httpEndpoint id="defaultHttpEndpoint"
23                  httpPort="${http.port}" 
24                  httpsPort="${https.port}" />
25
26    <!-- Automatically expand WAR files and EAR files -->
27    <applicationManager autoExpand="true"/>
28
29    <basicRegistry id="basic" realm="WebRealm">
30        <user name="bob" password="{xor}PTA9Lyg7" />
31        <user name="alice" password="{xor}PjM2PDovKDs=" />
32
33        <group name="admin">
34            <member name="bob" />
35        </group>
36
37        <group name="user">
38            <member name="bob" />
39            <member name="alice" />
40        </group>
41    </basicRegistry>
42
43    <!-- Configures the application on a specified context root -->
44    <webApplication contextRoot="${context.root}"
45                    location="inventory.war">
46        <application-bnd>
47            <security-role name="admin">
48                <group name="admin" />
49            </security-role>
50            <security-role name="user">
51                <group name="user" />
52            </security-role>
53        </application-bnd>
54    </webApplication>
55
56    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
57    <ssl id="guideSSLConfig" keyStoreRef="guideKeyStore" trustDefaultCerts="true" />
58    <sslDefault sslRef="guideSSLConfig" />
59
60    <keyStore id="guideKeyStore"
61              password="secret"
62              location="${server.config.dir}/resources/security/key.p12" />
63
64    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/>
65    <jwtBuilder id="jwtInventoryBuilder" 
66                issuer="http://openliberty.io" 
67                audiences="systemService"
68                expiry="24h"/>
69    <mpJwt audiences="systemService" 
70           groupNameAttribute="groups" 
71           id="myMpJwt"
72           sslRef="guideSSLConfig"
73           issuer="http://openliberty.io"/>
74
75    <library id="postgresql-library">
76        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
77    </library>
78
79    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
80        <jdbcDriver libraryRef="postgresql-library" />
81        <!-- tag::postgresProperties[] -->
82        <properties.postgresql databaseName="admin"
83                               serverName="${postgres/hostname}"
84                               portNumber="${postgres/portnum}"
85                               user="${postgres/username}"
86                               password="${postgres/password}"/>
87        <!-- end::postgresProperties[] -->
88    </dataSource>
89</server>

You can modify the inventory deployment to customize the service. Customizations for a service include changing the port number, changing the context root, and passing confidential information by using Secrets.

The context.root variable is defined in the server.xml configuration file. The context root for the inventory service can be changed by using this variable. The value for the context.root variable can be defined in a ConfigMap and accessed as an environment variable.

Create a ConfigMap to configure the app name with the following kubectl command.

kubectl create configmap inv-app-root --from-literal contextRoot=/dev

This command deploys a ConfigMap named inv-app-root to your cluster. It has a key called contextRoot with a value of /dev. The --from-literal flag specifies individual key-value pairs to store in this ConfigMap.

Replace the inventory.yaml file.
inventory.yaml

inventory.yaml

 1apiVersion: apps.openliberty.io/v1
 2# tag::kind[]
 3kind: OpenLibertyApplication
 4# end::kind[]
 5metadata:
 6  name: inventory-deployment
 7  labels:
 8    name: inventory-deployment
 9spec:
10  # tag::applicationImage[]
11  applicationImage: liberty-deepdive-inventory:1.0-SNAPSHOT
12  # end::applicationImage[]
13  service:
14    port: 9443
15  volumeMounts:
16  - name: postgres
17   # tag::mountPath[]
18    mountPath: "/config/variables/postgres"
19    # end::mountPath[]
20    readOnly: true
21  volumes:
22  - name: postgres
23    secret:
24      secretName: post-app-credentials 
25  env:
26    - name: POSTGRES_HOSTNAME
27      value: "postgres"
28    - name: CONTEXT_ROOT
29      valueFrom:
30        configMapKeyRef:
31          name: inv-app-root
32          key: contextRoot

During deployment, the post-app-credentials secret can be mounted to the /config/variables/postgres in the pod to create Liberty config variables. Liberty creates variables from the files in the /config/variables/postgres directory. Instead of including confidential information in the server.xml configuration file, users can access it using normal Liberty variable syntax, ${postgres/username} and ${postgres/password}.

Run the following command to deploy your changes.

kubectl apply -f inventory.yaml

Run the following command to check your pods status:

kubectl get pods

If all the pods are working correctly, you see an output similar to the following example:

NAME                                    READY   STATUS    RESTARTS   AGE
inventory-deployment-75f9dc56d9-g9lzl   1/1     Running   0          35s
postgres-58bd9b55c7-6vzz8               1/1     Running   0          13s

Run the following command to set up port forwarding to access the inventory microservice:

kubectl port-forward svc/inventory-deployment 9443

The application might take some time to get ready. See the https://localhost:9443/health URL to confirm that the inventory microservice is up and running. You can now check out the service at the https://localhost:9443/openapi/ui/ URL. The servers dropdown list shows the https://localhost:9443/dev URL. Or, you can run the following command to access the inventory microservice:

curl -k https://localhost:9443/dev/api/systems

Tearing down the environment

When you’re finished trying out the microservice, press CTRL+C in the command-line session where you ran the kubectl port-forward command to stop the port forwarding. You can delete all Kubernetes resources by running the kubectl delete commands:

kubectl delete -f inventory.yaml
kubectl delete -f ../../finish/postgres/postgres.yaml
kubectl delete configmap inv-app-root
kubectl delete secret post-app-credentials

To uninstall the Open Liberty Operator, run the following commands:

OPERATOR_NAMESPACE=default
WATCH_NAMESPACE='""'

curl -L https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-operator.yaml \
  | sed -e "s/OPEN_LIBERTY_WATCH_NAMESPACE/${WATCH_NAMESPACE}/" \
  | kubectl delete -n ${OPERATOR_NAMESPACE} -f -

curl -L https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-rbac-watch-all.yaml \
  | sed -e "s/OPEN_LIBERTY_OPERATOR_NAMESPACE/${OPERATOR_NAMESPACE}/" \
  | kubectl delete -f -

kubectl delete -f https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-crd.yaml

kubectl delete -f https://github.com/cert-manager/cert-manager/releases/download/v1.12.3/cert-manager.yaml

Perform the following steps to stop your Kubernetes cluster and return your environment to a clean state.

  1. Point the Docker daemon back to your local machine:

    eval $(minikube docker-env -u)
  2. Stop your Minikube cluster:

    minikube stop
  3. Delete your cluster:

    minikube delete

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 pom.xml, add the <configuration> element as the following:

  <plugin>
      <groupId>io.openliberty.tools</groupId>
      <artifactId>liberty-maven-plugin</artifactId>
      <version>3.10.2</version>
      <configuration>
          <runtimeArtifact>
              <groupId>com.ibm.websphere.appserver.runtime</groupId>
              <artifactId>wlp-kernel</artifactId>
               <version>[24.0.0.2,)</version>
               <type>zip</type>
          </runtimeArtifact>
      </configuration>
  </plugin>

Rebuild and restart the inventory service by dev mode:

mvn clean
mvn liberty:dev

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

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

ARG VERSION=1.0
ARG REVISION=SNAPSHOT
...

Great work! You’re done!

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

Guide Attribution

A Technical Deep Dive on Liberty by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star