A Technical Deep Dive on Liberty

duration 80 minutes
New

Prerequisites:

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

What you’ll learn

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

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

Inventory microservice

Additional prerequisites

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

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

Getting started

Clone the Git repository:

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

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

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

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

Getting started with Liberty and REST

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

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

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

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

  • Under Group specify: io.openliberty.deepdive

  • Under Artifact specify: inventory

  • Under Build Tool select: Gradle

  • Under Java SE Version select: your version

  • Under Java EE/Jakarta EE Version select: 10

  • Under MicroProfile Version select: 6.0

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

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

Use Powershell for the following commands:

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

Building the application

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

settings.gradle

1rootProject.name = 'inventory'

build.gradle

 1plugins {
 2    id 'war'
 3    // tag::libertyGradlePlugin[]
 4    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 5    // end::libertyGradlePlugin[]
 6}
 7
 8version '1.0-SNAPSHOT'
 9group 'io.openliberty.deepdive'
10
11sourceCompatibility = 11
12targetCompatibility = 11
13tasks.withType(JavaCompile) {
14    options.encoding = 'UTF-8'
15}
16
17repositories {
18    mavenCentral()
19}
20
21dependencies {
22    // provided dependencies
23    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0' 
24    providedCompile 'org.eclipse.microprofile:microprofile:6.0' 
25
26}
27
28clean.dependsOn 'libertyStop'

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

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

cd inventory

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

gradlew libertyRun
./gradlew libertyRun

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

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

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

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

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

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

gradlew libertyStop
./gradlew libertyStop

Starting and stopping the Liberty server in the background

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

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

Updating the server configuration without restarting the server

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

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

gradlew libertyDev
./gradlew libertyDev

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

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

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

Developing a RESTful microservice

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

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

Inventory.java

 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 server in dev mode at the beginning of this exercise, all the changes were automatically picked up.

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

Documenting APIs

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

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

build.gradle

 1plugins {
 2    id 'war'
 3    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 4}
 5
 6version '1.0-SNAPSHOT'
 7group 'io.openliberty.deepdive'
 8
 9sourceCompatibility = 11
10targetCompatibility = 11
11tasks.withType(JavaCompile) {
12    options.encoding = 'UTF-8'
13}
14
15repositories {
16    mavenCentral()
17}
18
19dependencies {
20    // provided dependencies
21    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0' 
22    // tag::mp5[]
23    providedCompile 'org.eclipse.microprofile:microprofile:6.0' 
24    // end::mp5[]
25
26}
27
28clean.dependsOn 'libertyStop'

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.0</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    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
21    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
22</server>

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

Generating the OpenAPI document

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

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

Augmenting the existing Jakarta RESTful Web Services annotations with OpenAPI annotations

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

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

SystemResource.java

  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 = "11",
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 = "11",
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 server was started in dev mode at the beginning of this exercise, your changes were automatically picked up. Go to the http://localhost:9080/openapi URL to see the updated endpoint descriptions. The endpoints at which your REST methods are served now more meaningful:

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

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

Augmenting POJOs with OpenAPI annotations

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

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

SystemData.java

 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 server configuration and inject configuration for your microservice by using MicroProfile Config.

Enabling configurable ports and context root

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

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

server.xml

 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.0</feature>
 8    </featureManager>
 9
10    <!-- tag::httpPortVariable[] -->
11    <variable name="default.http.port" defaultValue="9080" />
12    <!-- end::httpPortVariable[] -->
13    <!-- tag::httpsPortVariable[] -->
14    <variable name="default.https.port" defaultValue="9443" />
15    <!-- end::httpsPortVariable[] -->
16    <!-- tag::contextRootVariable[] -->
17    <variable name="default.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="${default.http.port}" 
25                  httpsPort="${default.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="${default.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 file. Change the httpEndpoint element to reflect the new default.http.port and default.http.port variables and change the contextRoot to use the new default.context.root variable too.

Replace the build.gradle file.
build.gradle

build.gradle

 1plugins {
 2    id 'war'
 3    // tag::libertyGradlePlugin[]
 4    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 5    // end::libertyGradlePlugin[]
 6}
 7
 8version '1.0-SNAPSHOT'
 9group 'io.openliberty.deepdive'
10
11sourceCompatibility = 11
12targetCompatibility = 11
13tasks.withType(JavaCompile) {
14    options.encoding = 'UTF-8'
15}
16
17repositories {
18    mavenCentral()
19}
20
21dependencies {
22    // provided dependencies
23    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0'
24    providedCompile 'org.eclipse.microprofile:microprofile:6.0'
25}
26
27// tag::war[]
28war {
29    archiveVersion = ''
30}
31// end::war[]
32
33// tag::ext[]
34ext  {
35    // tag::httpPort[]
36    liberty.server.var.'default.http.port' = '9081'
37    // end::httpPort[]
38    // tag::httpsPort[]
39    liberty.server.var.'default.https.port' = '9445'
40    // end::httpsPort[]
41    // tag::contextRoot[]
42    liberty.server.var.'default.context.root' = '/trial'
43    // end::contextRoot[]
44}
45// end::ext[]
46
47clean.dependsOn 'libertyStop'

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

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

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

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

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

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

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

build.gradle

 1plugins {
 2    id 'war'
 3    // tag::libertyGradlePlugin[]
 4    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 5    // end::libertyGradlePlugin[]
 6}
 7
 8version '1.0-SNAPSHOT'
 9group 'io.openliberty.deepdive'
10
11sourceCompatibility = 11
12targetCompatibility = 11
13tasks.withType(JavaCompile) {
14    options.encoding = 'UTF-8'
15}
16
17repositories {
18    mavenCentral()
19}
20
21dependencies {
22    // provided dependencies
23    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0'
24    providedCompile 'org.eclipse.microprofile:microprofile:6.0'
25}
26
27// tag::war[]
28war {
29    archiveVersion = ''
30}
31// end::war[]
32
33// tag::ext[]
34ext  {
35    // tag::httpPort[]
36    liberty.server.var.'default.http.port' = '9080'
37    // end::httpPort[]
38    // tag::httpsPort[]
39    liberty.server.var.'default.https.port' = '9443'
40    // end::httpsPort[]
41    // tag::contextRoot[]
42    liberty.server.var.'default.context.root' = '/inventory'
43    // end::contextRoot[]
44}
45// end::ext[]
46
47clean.dependsOn 'libertyStop'

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

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

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

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

Wait until you see the following message:

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

Injecting static configuration

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

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

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

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

SystemResource.java

  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 = "11",
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 = "11",
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 = "11",
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 = "11",
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      <class>io.openliberty.deepdive.rest.model.SystemData</class>
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 configuration file.

Replace the 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.0</feature>
 7    </featureManager>
 8
 9    <variable name="default.http.port" defaultValue="9080" />
10    <variable name="default.https.port" defaultValue="9443" />
11    <variable name="default.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="${default.http.port}" 
17                  httpsPort="${default.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="${default.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 server where to find the PostgreSQL library. The dataSource element points to where the Java Database Connectivity (JDBC) driver connects, along with some database vendor-specific properties. For more information, see the Data source configuration and dataSource element documentation.

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

Replace the build.gradle file.
build.gradle

build.gradle

 1plugins {
 2    id 'war'
 3    // tag::libertyGradlePlugin[]
 4    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 5    // end::libertyGradlePlugin[]
 6}
 7
 8version '1.0-SNAPSHOT'
 9group 'io.openliberty.deepdive'
10
11sourceCompatibility = 11
12targetCompatibility = 11
13tasks.withType(JavaCompile) {
14    options.encoding = 'UTF-8'
15}
16
17repositories {
18    mavenCentral()
19}
20
21// tag::configurations[]
22configurations {
23    jdbcLib
24}
25// end::configurations[]
26
27dependencies {
28    // provided dependencies
29    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0'
30    providedCompile 'org.eclipse.microprofile:microprofile:6.0'
31    // tag::postgresql[]
32    jdbcLib 'org.postgresql:postgresql:42.3.8'
33    // end::postgresql[]
34}
35
36war {
37    archiveVersion = ''
38}
39
40ext  {
41    // tag::httpPort[]
42    liberty.server.var.'default.http.port' = '9080'
43    // end::httpPort[]
44    // tag::httpsPort[]
45    liberty.server.var.'default.https.port' = '9443'
46    // end::httpsPort[]
47    // tag::contextRoot[]
48    liberty.server.var.'default.context.root' = '/inventory'
49    // end::contextRoot[]
50    // tag::setResourcesDir[]
51    sourceSets.main.output.resourcesDir = sourceSets.main.java.destinationDirectory
52    // end::setResourcesDir[]
53}
54
55// tag::copyJDBC[]
56task copyJdbcLibs(type: Copy) {
57    from configurations.jdbcLib
58    into "${buildDir}/wlp/usr/shared/resources"
59}
60
61deploy.dependsOn 'copyJdbcLibs'
62// end::copyJDBC[]
63
64clean.dependsOn 'libertyStop'

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

Starting PostgreSQL database

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

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

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

Running the application

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

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

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

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

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

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

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

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

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

Securing RESTful APIs

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

cd start/inventory

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

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

server.xml

 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.0</feature>
 7    </featureManager>
 8
 9    <variable name="default.http.port" defaultValue="9080" />
10    <variable name="default.https.port" defaultValue="9443" />
11    <variable name="default.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="${default.http.port}" 
17                  httpsPort="${default.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="${default.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 = "11",
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 = "11",
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=11&heapSize=1"

You can expect the following response:

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

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

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

You can now expect the following response:

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

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

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

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

You should see the following response:

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

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

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

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

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

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

jakarta.ws.rs.ForbiddenException: Unauthorized

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

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

You can expect to see the following response:

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

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

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

You can expect to see the following output:

[]

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

Consuming the secured RESTful APIs by JWT

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

The system microservice is provided for you.

Writing the RESTful client interface

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

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

SystemClient.java

 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 = "11",
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 = "11",
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 server configuration file for the inventory service.

Replace the server.xml 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.0</feature>
 7        <!-- tag::jwtSsoFeature[] -->
 8        <feature>jwtSso-1.0</feature>
 9        <!-- end::jwtSsoFeature[] -->
10    </featureManager>
11
12    <variable name="default.http.port" defaultValue="9080" />
13    <variable name="default.https.port" defaultValue="9443" />
14    <variable name="default.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="${default.http.port}" 
20                  httpsPort="${default.https.port}" />
21
22    <!-- Automatically expand WAR files and EAR files -->
23    <applicationManager autoExpand="true"/>
24    
25    <!-- tag::keyStore[] -->
26    <keyStore id="defaultKeyStore" password="secret" />
27    <!-- end::keyStore[] -->
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="${default.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    <!-- tag::jwtSsoConfig[] -->
57    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/> 
58    <!-- end::jwtSsoConfig[] -->
59    <!-- tag::jwtBuilder[] -->
60    <jwtBuilder id="jwtInventoryBuilder" 
61                issuer="http://openliberty.io" 
62                audiences="systemService"
63                expiry="24h"/>
64    <!-- end::jwtBuilder[] -->
65    <!-- tag::mpJwt[] -->
66    <mpJwt audiences="systemService" 
67           groupNameAttribute="groups" 
68           id="myMpJwt" 
69           issuer="http://openliberty.io"/>
70    <!-- end::mpJwt[] -->
71
72    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
73    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
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>

microprofile-config.properties

1mp.jwt.verify.issuer=http://openliberty.io
2mp.jwt.token.header=Authorization
3mp.jwt.token.cookie=Bearer
4mp.jwt.verify.audiences=systemService, adminServices
5# mp.jwt.decrypt.key.location=privatekey.pem
6mp.jwt.verify.publickey.algorithm=RS256

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

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

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

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

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

Replace the build.gradle file.
build.gradle

build.gradle

 1plugins {
 2    id 'war'
 3    id 'io.openliberty.tools.gradle.Liberty' version '3.6.2'
 4}
 5
 6version '1.0-SNAPSHOT'
 7group 'io.openliberty.deepdive'
 8
 9sourceCompatibility = 11
10targetCompatibility = 11
11tasks.withType(JavaCompile) {
12    options.encoding = 'UTF-8'
13}
14
15repositories {
16    mavenCentral()
17}
18
19configurations {
20    jdbcLib
21}
22
23dependencies {
24    // provided dependencies
25    providedCompile 'jakarta.platform:jakarta.jakartaee-api:10.0.0'
26    providedCompile 'org.eclipse.microprofile:microprofile:6.0'
27    jdbcLib 'org.postgresql:postgresql:42.3.8'
28}
29
30war {
31    archiveVersion = ''
32}
33
34ext  {
35    liberty.server.var.'default.http.port' = '9080'
36    liberty.server.var.'default.https.port' = '9443'
37    liberty.server.var.'default.context.root' = '/inventory'
38    // tag::https[]
39    liberty.server.var.'client.https.port' = '9444'
40    // end::https[]
41    sourceSets.main.output.resourcesDir = sourceSets.main.java.destinationDirectory
42}
43
44task copyJdbcLibs(type: Copy) {
45    from configurations.jdbcLib
46    into "${buildDir}/wlp/usr/shared/resources"
47}
48
49deploy.dependsOn 'copyJdbcLibs'
50
51clean.dependsOn 'libertyStop'

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

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

gradlew libertyDev
./gradlew libertyDev

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

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

Running the /client/{hostname} endpoint

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

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

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

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

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

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

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

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

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

You can expect the following output:

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

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

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

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

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

Adding health checks

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

Navigate to your application directory

cd start/inventory

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

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

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

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

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

Create the health subdirectory before creating the health check classes.

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

StartupCheck.java

 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 java.time.LocalDateTime;
16import jakarta.enterprise.context.ApplicationScoped;
17import org.eclipse.microprofile.config.inject.ConfigProperty;
18import org.eclipse.microprofile.health.Readiness;
19import org.eclipse.microprofile.health.HealthCheck;
20import org.eclipse.microprofile.health.HealthCheckResponse;
21
22// tag::Readiness[]
23@Readiness
24// end::Readiness[]
25// tag::ApplicationScoped[]
26@ApplicationScoped
27// end::ApplicationScoped[]
28public class ReadinessCheck implements HealthCheck {
29
30    private static final int ALIVE_DELAY_SECONDS = 10;
31    private static final String READINESS_CHECK = "Readiness Check";
32    private static LocalDateTime aliveAfter = LocalDateTime.now();
33
34    @Override
35    public HealthCheckResponse call() {
36        if (isAlive()) {
37            return HealthCheckResponse.up(READINESS_CHECK);
38        }
39
40        return HealthCheckResponse.down(READINESS_CHECK);
41    }
42
43    public static void setUnhealthy() {
44        aliveAfter = LocalDateTime.now().plusSeconds(ALIVE_DELAY_SECONDS);
45    }
46
47    private static boolean isAlive() {
48        return LocalDateTime.now().isAfter(aliveAfter);
49    }
50}
51// 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 server.xml 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.0</feature>
 7        <feature>jwtSso-1.0</feature>
 8    </featureManager>
 9
10    <variable name="default.http.port" defaultValue="9080" />
11    <variable name="default.https.port" defaultValue="9443" />
12    <variable name="default.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="${default.http.port}" 
18                  httpsPort="${default.https.port}" />
19
20    <!-- Automatically expand WAR files and EAR files -->
21    <applicationManager autoExpand="true"/>
22    
23    <keyStore id="defaultKeyStore" password="secret" />
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    <!-- tag::administrator[] -->
40    <administrator-role>
41        <user>bob</user>
42        <group>AuthorizedGroup</group>
43    </administrator-role>
44    <!-- end::administrator[] -->
45
46    <!-- Configures the application on a specified context root -->
47    <webApplication contextRoot="${default.context.root}"
48                    location="inventory.war">
49        <application-bnd>
50            <security-role name="admin">
51                <group name="admin" />
52            </security-role>
53            <security-role name="user">
54                <group name="user" />
55            </security-role>
56        </application-bnd>
57    </webApplication>
58
59    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/> 
60    <jwtBuilder id="jwtInventoryBuilder" 
61                issuer="http://openliberty.io" 
62                audiences="systemService"
63                expiry="24h"/>
64    <mpJwt audiences="systemService" 
65           groupNameAttribute="groups" 
66           id="myMpJwt" 
67           issuer="http://openliberty.io"/>
68
69    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
70    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
71
72    <library id="postgresql-library">
73        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
74    </library>
75
76    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
77        <jdbcDriver libraryRef="postgresql-library" />
78        <properties.postgresql databaseName="admin"
79                               serverName="localhost"
80                               portNumber="5432"
81                               user="admin"
82                               password="adminpwd"/>
83    </dataSource>
84</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 = "11",
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 = "11",
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 gradlew libertyDev dev mode that you started in the previous section.

Navigate to your application directory:

cd start/inventory

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

Make sure to start your podman daemon before you proceed.

Create the Containerfile in the start/inventory directory.
Containerfile

Containerfile

 1# tag::from[]
 2FROM icr.io/appcafe/open-liberty:full-java11-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/guide-liberty-deepdive-gradle" \
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    build/libs/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-jar[]
51# tag::jar-userID[]
52COPY --chown=1001:0 \
53# end::jar-userID[]
54    # tag::inventory-jar[]
55    build/wlp/usr/shared/resources/*.jar \
56    # end::inventory-jar[]
57    # tag::shared-resources[]
58    /opt/ol/wlp/usr/shared/resources/
59    # end::shared-resources[]
60# end::copy-jar[]
61# end::copy[]
62
63USER 1001
64
65RUN 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-java11-openj9-ubi image that comes with the latest Open Liberty runtime as your parent image.

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

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

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

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

server.xml

 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.0</feature>
 7        <feature>jwtSso-1.0</feature>
 8    </featureManager>
 9
10    <variable name="default.http.port" defaultValue="9080" />
11    <variable name="default.https.port" defaultValue="9443" />
12    <!-- tag::contextRoot[] -->
13    <variable name="default.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="${default.http.port}" 
24                  httpsPort="${default.https.port}" />
25
26    <!-- Automatically expand WAR files and EAR files -->
27    <applicationManager autoExpand="true"/>
28
29    <keyStore id="defaultKeyStore" password="secret" />
30    
31    <basicRegistry id="basic" realm="WebRealm">
32        <user name="bob" password="{xor}PTA9Lyg7" />
33        <user name="alice" password="{xor}PjM2PDovKDs=" />
34
35        <group name="admin">
36            <member name="bob" />
37        </group>
38
39        <group name="user">
40            <member name="bob" />
41            <member name="alice" />
42        </group>
43    </basicRegistry>
44
45    <!-- Configures the application on a specified context root -->
46    <webApplication contextRoot="${default.context.root}"
47                    location="inventory.war">
48        <application-bnd>
49            <security-role name="admin">
50                <group name="admin" />
51            </security-role>
52            <security-role name="user">
53                <group name="user" />
54            </security-role>
55        </application-bnd>
56    </webApplication>
57
58    <jwtSso jwtBuilderRef="jwtInventoryBuilder"/> 
59    <jwtBuilder id="jwtInventoryBuilder" 
60                issuer="http://openliberty.io" 
61                audiences="systemService"
62                expiry="24h"/>
63    <mpJwt audiences="systemService" 
64           groupNameAttribute="groups" 
65           id="myMpJwt" 
66           issuer="http://openliberty.io"/>
67
68    <!-- Default SSL configuration enables trust for default certificates from the Java runtime -->
69    <ssl id="defaultSSLConfig" trustDefaultCerts="true" />
70
71    <library id="postgresql-library">
72        <fileset dir="${shared.resource.dir}/" includes="*.jar" />
73    </library>
74
75    <dataSource id="DefaultDataSource" jndiName="jdbc/postgresql">
76        <jdbcDriver libraryRef="postgresql-library" />
77        <!-- tag::postgresProperties[] -->
78        <properties.postgresql databaseName="admin"
79                               serverName="${postgres/hostname}"
80                               portNumber="${postgres/portnum}"
81                               user="${postgres/username}"
82                               password="${postgres/password}"/>
83        <!-- end::postgresProperties[] -->
84    </dataSource>
85</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.

Building the container image

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

gradlew war
./gradlew war

Build your container image with the following commands:

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

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

podman images

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

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

Running the application in container

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

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

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

The command returns the PostgreSQL container IP address:

10.88.0.10

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

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

The following table describes the flags in this command:

Flag Description

-d

Runs the container in the background.

--name

Specifies a name for the container.

-p

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

-e

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

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

podman ps

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

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

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

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

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

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

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

Support Licensing

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

WebSphere Liberty is also available in Maven Central.

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

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

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

Rebuild and restart the inventory service by dev mode:

./gradlew clean
./gradlew libertyDev

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

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

ARG VERSION=1.0
ARG REVISION=SNAPSHOT
...

Great work! You’re done!

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

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