Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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

An end-to-end tutorial on cloud-native Java application development and deployment using Jakarta EE, MicroProfile & Open Liberty
https://github.com/openliberty/guide-liberty-deep-dive

Last synced: 3 months ago
JSON representation

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

Awesome Lists containing this project

README

        

// Copyright (c) 2022, 2024 IBM Corporation and others.
// Licensed under Creative Commons Attribution-NoDerivatives
// 4.0 International (CC BY-ND 4.0)
// https://creativecommons.org/licenses/by-nd/4.0/
//
// Contributors:
// IBM Corporation
//
:projectid: liberty-deep-dive
:page-layout: guide-multipane
:page-duration: 120 minutes
:page-releasedate: 2022-04-27
:page-essential: false
:page-description: Learn how to use Liberty to develop and run Java microservices.
:page-tags: ['jakarta-ee', 'microprofile']
:page-related-guides: ['microprofile-openapi', 'cdi-intro', 'microprofile-config', 'jpa-intro', 'microprofile-jwt', 'microprofile-health', 'microprofile-metrics', 'containerize', 'openliberty-operator-intro', 'kubernetes-microprofile-config']
:page-permalink: /guides/{projectid}
:common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/prod
:imagesdir: /img/guide/{projectid}
:source-highlighter: prettify
:page-seo-title: A hands-on technical deep dive on Liberty
:page-seo-description: An in-depth and end-to-end tutorial with examples (akin to a "masterclass") on how to easily develop cloud-native Java applications and microservices using Jakarta EE and MicroProfile APIs using Open Liberty and WebSphere Liberty as the runtime or framework, and how to build, run and deploy the applications in containers to Kubernetes.
:guide-author: Open Liberty
= A Technical Deep Dive on Liberty

[.hidden]
NOTE: This repository contains the documentation source. To view this exercise in published form, view it on the https://openliberty.io/guides/{projectid}.html[Open Liberty website].

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

== What you'll learn

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

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

image::inventory.png[Inventory microservice,align="center",height=85%,width=85%]

== Additional prerequisites

Docker must be installed before you start the **Persisting Data** module. For installation instructions, refer to the https://docs.docker.com/get-docker/[official Docker documentation^]. You'll build and run the application in Docker containers.

Make sure to start your Docker daemon before you proceed.

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

You will use `Minikube` as a single-node Kubernetes cluster that runs locally in a virtual machine. Make sure that you have `kubectl` installed. If you need to install `kubectl`, see the https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl-on-linux[kubectl installation instructions^].
For Minikube installation instructions, see the https://github.com/kubernetes/minikube#installation[Minikube documentation^].

== Getting started

ifdef::cloud-hosted[]
To open a new command-line session,
select **Terminal** > **New Terminal** from the menu of the IDE.

Run the following command to navigate to the **/home/project** directory:

```bash
cd /home/project
```
endif::[]

Clone the https://github.com/OpenLiberty/guide-liberty-deep-dive.git[Git repository^]:

[role='command']
```
git clone https://github.com/openliberty/guide-liberty-deep-dive.git
cd guide-liberty-deep-dive
```

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

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

ifndef::cloud-hosted[]
Before you begin, make sure you have all the necessary prerequisites.
endif::[]

ifdef::cloud-hosted[]
In this IBM Cloud environment, you need to change the user home to ***/home/project*** by running the following command:
```bash
sudo usermod -d /home/project theia
```
endif::[]

== Getting started with Liberty and REST

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

In this workshop, the Open Liberty Starter is used to create the starting point of the application. Maven is used as the selected build tool and the application uses of Jakarta EE 10 and MicroProfile 6.

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

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

* Under Group specify: `io.openliberty.deepdive`
* Under Artifact specify: `inventory`
* Under Build Tool select: `Maven`
* Under Java SE Version select: `17`
* Under Java EE/Jakarta EE Version select: `10.0`
* Under MicroProfile Version select: `6.1`

ifndef::cloud-hosted[]
Then, click `Generate Project`, which downloads the starter project as `inventory.zip` file.

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

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

[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
curl -o inventory.zip 'https://start.openliberty.io/api/start?a=inventory&b=maven&e=10.0&g=io.openliberty.deepdive&j=17&m=6.1'
Expand-Archive -Path .\inventory.zip
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
curl -o inventory.zip 'https://start.openliberty.io/api/start?a=inventory&b=maven&e=10.0&g=io.openliberty.deepdive&j=17&m=6.1'
unzip inventory.zip -d inventory
```
--
endif::[]

ifdef::cloud-hosted[]
In this Skills Network environment, instead of manually downloading and extracting the project, run the following commands:
```bash
cd /home/project/guide-liberty-deep-dive/start
curl -o inventory.zip 'https://start.openliberty.io/api/start?a=inventory&b=maven&e=10.0&g=io.openliberty.deepdive&j=17&m=6.1'
unzip inventory.zip -d inventory
```

After getting the ***inventory*** project, switch the workspace to the ***/home/project/guide-liberty-deep-dive/start/inventory*** directory.
> - Select **File** > **Close Workspace** from the menu of the IDE.
> - Click the OK button to confirm to close.
> - Wait for the IDE to refresh.
> - Select **File** > **Open...** from the menu of the IDE.
> - In the **Open** window, select the ***home*** directory from the top dropdown list, and then select the ***/home/project/guide-liberty-deep-dive/start/inventory*** directory and click the **Open** button.
> - Wait for the IDE to refresh.
> - Click **Yes** to trust the workspace.
endif::[]

=== Building the application

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

pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-getting-started/pom.xml[]
----

Your [hotspot]`pom.xml` file is located in the `start/inventory` directory and is configured to include the [hotspot=libertyMavenPlugin]`liberty-maven-plugin`. Using the plug-in, you can install applications into Liberty and manage the associated Liberty instances.

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

ifndef::cloud-hosted[]
[role='command']
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

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

[role='command']
```
mvn liberty:run
```

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

The `liberty:run` argument specifies the Liberty `run` goal, which starts a Liberty instance in the foreground. As part of this phase, a Liberty runtime is downloaded and installed into the `target/liberty/wlp` directory. Additionally, a Liberty instance is created and configured in the `target/liberty/wlp/usr/servers/defaultServer` directory, and the application is installed into that Liberty instance by using https://www.ibm.com/support/knowledgecenter/en/SSEQTP_liberty/com.ibm.websphere.wlp.doc/ae/rwlp_loose_applications.html[loose config^].

For more information about the Liberty Maven plug-in, see its https://github.com/WASdev/ci.maven[GitHub repository^].

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

[source, role="no_copy"]
----
[INFO] [AUDIT] CWWKF0011I: The server defaultServer is ready to run a smarter planet.
----

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

=== Starting and stopping the Liberty in the background

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

[role='command']
----
mvn liberty:start
mvn liberty:stop
----

=== Updating the Liberty configuration without restarting the instance

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

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

[role='command']
```
mvn liberty:dev
```

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

[role="no_copy"]
----
**************************************************************
* Liberty is running in dev mode.
----

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

=== Developing a RESTful microservice

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

ifdef::cloud-hosted[]
Open another command-line session by selecting **Terminal** > **New Terminal** from the menu of the IDE. Go to the ***start/inventory*** directory.
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `Inventory` class.#
`src/main/java/io/openliberty/deepdive/rest/Inventory.java`
----

Inventory.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/Inventory.java[]
----

This `Inventory` class stores a record of all systems and their system properties. The [hotspot=getSystem file=0]`getSystem()` method within this class retrieves and returns the system data from the system. The [hotspot=add file=0]`add()` method enables the addition of a system and its data to the inventory. The [hotspot=update file=0]`update()` method enables a system and its data on the inventory to be updated. The [hotspot=removeSystem file=0]`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.

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
mkdir src\main\java\io\openliberty\deepdive\rest\model
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
mkdir src/main/java/io/openliberty/deepdive/rest/model
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir /home/project/guide-liberty-deep-dive/start/inventory/src/main/java/io/openliberty/deepdive/rest/model
```
endif::[]

[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `SystemData` class.#
`src/main/java/io/openliberty/deepdive/rest/model/SystemData.java`
----

SystemData.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]
----

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

[role="code_command hotspot file=2", subs="quotes"]
----
#Create the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

SystemResource.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

RestApplication.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-getting-started/src/main/java/io/openliberty/deepdive/rest/RestApplication.java[]
----

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

The [hotspot=path file=2]`@Path` annotation on this class indicates that this resource responds to the `/systems` path in the RESTful application. The [hotspot=applicationPath file=3]`@ApplicationPath` annotation in the `RestApplication` class, together with the [hotspot=path file=2]`@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 [hotspot=getListContents file=2]`@GET` annotation on the `listContents` method indicates that the method is to be called for the HTTP `GET` method. The [hotspot=producesListContents file=2]`@Produces` annotation indicates the format of the content that is returned. The value of the [hotspot=producesListContents file=2]`@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 [hotspot=getSystems file=2]`inventory.getSystems()`. Because the method is annotated with [hotspot=producesListContents file=2]`@Produces(MediaType.APPLICATION_JSON)`, the Jakarta RESTful Web Services API uses JSON-B to automatically convert the returned object to JSON data in the HTTP response.

=== Running the application

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

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

ifdef::cloud-hosted[]
Open another command-line session by selecting **Terminal** > **New Terminal** from the menu of the IDE, and run the following curl command:
```bash
curl 'http://localhost:9080/inventory/api/systems'
```

You can expect to see the following output:

```
[]
```
endif::[]

== Documenting APIs

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

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

pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-openapi/pom.xml[]
----

server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-openapi/src/main/liberty/config/server.xml[]
----

The MicroProfile OpenAPI API is included in the [hotspot=mp5 file=0]`microProfile` dependency that is specified in your `pom.xml` file. The [hotspot=mp5 file=1]`microProfile` feature that includes the `mpOpenAPI` feature is also enabled in the `server.xml` configuration file.

=== Generating the OpenAPI document

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

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

=== Augmenting the existing Jakarta RESTful Web Services annotations with OpenAPI annotations

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

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the `SystemResources` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

SystemResource.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-openapi/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

Add OpenAPI [hotspot=listContentsAPIResponseSchema hotspot=getSystemAPIResponseSchema file=0]`@APIResponseSchema`, [hotspot=addSystemAPIResponses file=0]`@APIResponses`, [hotspot=addSystemAPIResponse file=0]`@APIResponse`, [hotspot=addSystemParameters file=0]`@Parameters`, [hotspot=addSystemParameter file=0]`@Parameter`, and [hotspot=addSystemOperation file=0]`@Operation` annotations to the REST methods, [hotspot=listContents file=0]`listContents()`, [hotspot=getSystem file=0]`getSystem()`, [hotspot=addSystem file=0]`addSystem()`, [hotspot=updateSystem file=0]`updateSystem()`, [hotspot=removeSystem file=0]`removeSystem()`, and [hotspot=addSystemClient file=0]`addSystemClient()`.

Note, the `@Parameter` annotation can be placed either [hotspot=getSystemParameter file=0]`inline` or [hotspot=removeSystemParameter file=0]`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 https://download.eclipse.org/microprofile/microprofile-open-api-3.1/microprofile-openapi-spec-3.1.html#_annotations[MicroProfile OpenAPI specification^].

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

ifdef::cloud-hosted[]
```bash
curl http://localhost:9080/openapi
```
endif::[]

[source, YAML, role="no_copy"]
----
---
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.
ifdef::cloud-hosted[]
In this Skills Network environment, simply click the following button:

::startApplication{port="9080" display="external" name="Visit OpenAPI UI" route="/openapi/ui"}
endif::[]

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

[role='code_command hotspot', subs="quotes"]
----
#Replace the `SystemData` class.#
`src/main/java/io/openliberty/deepdive/rest/model/SystemData.java`
----

SystemData.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-openapi/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]
----

Add OpenAPI `@Schema` annotations to the [hotspot=SystemDataSchema]`SystemData` class and the [hotspot=hostnameSchema]`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:

ifdef::cloud-hosted[]
```bash
curl http://localhost:9080/openapi
```
endif::[]

[source, YAML, role="no_copy"]
----
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.

ifdef::cloud-hosted[]
::startApplication{port="9080" display="external" name="Visit OpenAPI UI" route="/openapi/ui"}
endif::[]

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 https://openliberty.io/guides/microprofile-openapi.html[Documenting RESTful APIs guide^].

== Configuring the microservice

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

=== Enabling configurable ports and context root

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

[role='code_command hotspot file=0', subs="quotes"]
----
#Replace the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----

server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-config/src/main/liberty/config/server.xml[]
----

Add variables for the [hotspot=httpPortVariable file=0]`HTTP` port, [hotspot=httpsPortVariable file=0]`HTTPS` port, and the [hotspot=contextRootVariable file=0]`context root` to the `server.xml` configuration file. Change the [hotspot=editedHttpEndpoint file=0]`httpEndpoint` element to reflect the new `http.port` and `https.port` variables and change the [hotspot=editedContextRoot file=0]`contextRoot` to use the new `context.root` variable too.

[role='code_command hotspot file=1', subs="quotes"]
----
#Replace the `pom.xml` file.#
`pom.xml`
----

pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::staging/module-config/pom.xml[]
----

Add properties for the [hotspot=httpPort file=1]`HTTP` port, [hotspot=httpsPort file=1]`HTTPS` port, and the [hotspot=contextRoot file=1]`context root` to the `pom.xml` file.

* [hotspot=httpPort file=1]`liberty.var.http.port` to `9081`
* [hotspot=httpsPort file=1]`liberty.var.https.port` to `9445`
* [hotspot=contextRoot file=1]`liberty.var.context.root` to `/trial`.

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

ifndef::cloud-hosted[]
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/.
endif::[]

ifdef::cloud-hosted[]
Now, you can access the application by running the following command:
```bash
curl http://localhost:9081/trial/api/systems
```

Alternatively, for the updated OpenAPI UI, click the following button to visit ***/openapi/ui*** endpoint:

::startApplication{port="9081" display="external" name="Visit OpenAPI UI" route="/openapi/ui"}
endif::[]

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

* update [hotspot=httpPort file=2]`liberty.var.http.port` to `9080`
* update [hotspot=httpsPort file=2]`liberty.var.https.port` to `9443`
* update [hotspot=contextRoot file=2]`liberty.var.context.root` to `/inventory`.

[role='code_command hotspot file=2', subs="quotes"]
----
#Replace the `pom.xml` file.#
`pom.xml`
----

pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-config/pom.xml[]
----

=== Injecting static configuration

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

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

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

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

SystemResource.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-config/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

The [hotspot=inject file=0]`@Inject` annotation injects the value from other configuration sources to the `CLIENT_PORT` variable. The [hotspot=configProperty file=0]`@ConfigProperty` defines the external property name as `client.https.port`.

Update the [hotspot=printClientPort file=0]`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.

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
mkdir src\main\resources\META-INF
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
mkdir -p src/main/resources/META-INF
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir -p /home/project/guide-liberty-deep-dive/start/inventory/src/main/resources/META-INF
```
endif::[]

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `microprofile-config.properties` file.#
`src/main/resources/META-INF/microprofile-config.properties`
----

microprofile-config.properties
[source, text, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-config/src/main/resources/META-INF/microprofile-config.properties[]
----

Using the [hotspot=ordinal file=0]`config_ordinal` variable in this properties file, you can set the ordinal of this file and thus other configuration sources.

The [hotspot=configPort file=0]`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.

ifdef::cloud-hosted[]
::startApplication{port="9080" display="external" name="Visit OpenAPI UI" route="/openapi/ui"}
endif::[]

You can learn more about MicroProfile Config from the https://openliberty.io/guides/microprofile-config.html[Configuring microservices guide^].

== Persisting data

Next, you’ll persist the system data into the PostgreSQL database by using the https://jakarta.ee/specifications/persistence[Jakarta Persistence API^] (JPA).

Navigate to your application directory.

ifndef::cloud-hosted[]
[role='command']
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

=== 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 [hotspot=SystemData]`SystemData` class is a data model that represents systems in the `inventory` microservice. Annotate it with JPA annotations.

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the `SystemData` class.#
`src/main/java/io/openliberty/deepdive/rest/model/SystemData.java`
----
SystemData.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]
----

The following table breaks down the new annotations:

[cols="35, 200", options="header"]
|===
| *Annotation* | *Description*
| [hotspot=Entity]`@Entity` | Declares the class as an entity.
| [hotspot=Table]`@Table` | Specifies details of the table such as name.
| [hotspot=findAll hotspot=findSystem]`@NamedQuery` | Specifies a predefined database query that is run by an `EntityManager` instance.
| [hotspot=Id]`@Id` | Declares the primary key of the entity.
| [hotspot=GeneratedValue]`@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.
| [hotspot=columnId hotspot=columnHostname hotspot=columnOsName hotspot=columnJavaVersion hotspot=columnHeapSize]`@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.

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the `Inventory` class.#
`src/main/java/io/openliberty/deepdive/rest/Inventory.java`
----

// File 0
Inventory.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/Inventory.java[]
----

To use the entity manager at run time, inject it into your CDI bean through the [hotspot=PersistenceContext file=0]`@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.

// File 1
SystemData.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/model/SystemData.java[]
----

The [hotspot=Inventory file=0]`Inventory` class has a method for each CRUD operation, so let's break them down:

* The [hotspot=add file=0]`add()` method persists an instance of the `SystemData` entity class to the data store by calling the [hotspot=Persist file=0]`persist()` method on an `EntityManager` instance. The entity instance becomes managed and changes to it are tracked by the entity manager.

* The [hotspot=getSystems file=0]`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 [hotspot=findAll file=1]`SystemData.findAll` query that is specified in the [hotspot=findAll hotspot=findSystem file=1]`@NamedQuery` annotation on the `SystemData` class. Similarly, the [hotspot=getSystem file=0]`getSystem()` method uses the [hotspot=findSystem file=1]`SystemData.findSystem` named query to find a system with the given hostname.

* The [hotspot=update file=0]`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 [hotspot=Merge file=0]`merge()` method so that changes to loaded fields of the detached entity are tracked.

* The [hotspot=removeSystem file=0]`removeSystem()` method removes an instance of the `SystemData` entity class from the database by calling the [hotspot=Remove file=0]`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.

[role="code_command hotspot file=2", subs="quotes"]
----
#Replace the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

// File 2
SystemResource.java
[source, Java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-persisting-data/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

The `@Transactional` annotation is used in the [hotspot=postTransactional file=2]`POST`, [hotspot=putTransactional file=2]`PUT`, and [hotspot=deleteTransactional file=2]`DELETE` endpoints of the `SystemResource` class to declaratively control the transaction boundaries on the [hotspot=inventory file=2]`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 [hotspot file=0]`persistence.xml` file is a configuration file that defines a persistence unit. The
persistence unit specifies configuration information for the entity manager.

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the configuration file.#
`src/main/resources/META-INF/persistence.xml`
----

// File 0
persistence.xml
[source, Xml, linenums, role='code_column']
----
include::finish/module-persisting-data/src/main/resources/META-INF/persistence.xml[]
----

The persistence unit is defined by the [hotspot=persistence-unit file=0]`persistence-unit` XML element. The [hotspot=transaction-type file=0]`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 [hotspot=transaction-type file=0]`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 [hotspot=jta-data file=0]`jta-data-source` element specifies the Java Naming and Directory Interface (JNDI) name of the data source that is used.

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

[role="code_command hotspot file=1", subs="quotes"]
----
#Replace the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----

// File 1
server.xml
[source, Xml, linenums, role='code_column']
----
include::finish/module-persisting-data/src/main/liberty/config/server.xml[]
----

The [hotspot=postgresqlLibrary file=1]`library` element tells the Liberty where to find the PostgreSQL library. The [hotspot=dataSource file=1]`dataSource` element points to where the Java Database Connectivity (JDBC) driver connects, along with some database vendor-specific properties. For more information, see the https://www.openliberty.io/docs/latest/relational-database-connections-JDBC.html#_data_source_configuration[Data source configuration^] and https://www.openliberty.io/docs/latest/reference/config/dataSource.html[dataSource element^] documentation.

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

[role='code_command hotspot file=2', subs="quotes"]
----
#Replace the `pom.xml` configuration file.#
`pom.xml`
----

// File 2
pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-persisting-data/pom.xml[]
----

The [hotspot=postgresql file=2]`postgresql` dependency ensures that Maven downloads the PostgreSQL library to local project. The [hotspot=copyDependencies file=2]`copyDependencies` configuration tells the Liberty Maven plug-in to copy the library to the Liberty shared resources directory.

=== Starting PostgreSQL database ===

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

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

ifndef::cloud-hosted[]
[role='command']
```
cd ../../finish/postgres
docker build -t postgres-sample .
docker run --name postgres-container -p 5432:5432 -d postgres-sample
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/finish/postgres
docker build -t postgres-sample .
docker run --name postgres-container -p 5432:5432 -d postgres-sample
```
endif::[]

=== Running the application ===

ifndef::cloud-hosted[]
In your dev mode console for the `inventory` microservice, type `r` and press `enter/return` key to restart the Liberty instance.

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

[role="no_copy"]
----
**************************************************************
* 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.

endif::[]

ifdef::cloud-hosted[]
In your dev mode console for the ***inventory*** microservice, type `r` and press ***enter/return*** key to restart the Liberty instance.

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

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

First, make a POST request to the ***/api/systems/*** endpoint by the following command. The POST request adds a system with the specified values to the database.

```bash
curl -X POST 'http://localhost:9080/inventory/api/systems?heapSize=1048576&hostname=localhost&javaVersion=9&osName=linux'
```

Next, make a GET request to the ***/api/systems*** endpoint by the following command. The GET request returns all systems from the database.

```bash
curl -s 'http://localhost:9080/inventory/api/systems' | jq
```

Next, make a PUT request to the ***/api/systems/{hostname}*** endpoint with the same value for the ***hostname*** path as in the previous step, and different values to the ***heapSize***, ***javaVersion***, and ***osName*** parameters. The PUT request updates the system with the specified values.

```bash
curl -X PUT 'http://localhost:9080/inventory/api/systems/localhost?heapSize=2097152&javaVersion=17&osName=linux'
```

To see the updated system, make a GET request to the ***/api/systems/{hostname}*** endpoint with the same value for the ***hostname*** path as in the previous step. The GET request returns the system from the database.

```bash
curl -s 'http://localhost:9080/inventory/api/systems/localhost' | jq
```

Next, make a DELETE request to the ***/api/systems/{hostname}*** endpoint. The DELETE request removes the system from the database.

```bash
curl -X DELETE 'http://localhost:9080/inventory/api/systems/localhost'
```

Run the GET request again to see that the system no longer exists in the database.
```bash
curl 'http://localhost:9080/inventory/api/systems'
```
endif::[]

== Securing RESTful APIs

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

ifndef::cloud-hosted[]
[role='command']
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

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

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----

// File 0
server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-securing/src/main/liberty/config/server.xml[]
----

The [hotspot=basicregistry file=0]`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 [hotspot=basicregistry file=0]`basicRegistry` element is a very simple case for learning purposes. For more information about the different user registries, see the https://openliberty.io/docs/latest/user-registries-application-security.html[User registries documentation^]. The [hotspot=myadmins file=0]`admin` group tells the application which of the users are in the administrator group. The [hotspot=myusers file=0]`user` group tells the application that users are in the user group.

The `security-role` maps the [hotspot=adminrole file=0]`admin` role to the [hotspot=myadmins file=0]`admin` group, meaning that all users in the `admin` group have the administrator role. Similarly, the [hotspot=userrole file=0]`user` role is mapped to the [hotspot=myusers file=0]`user` group, meaning all users in the `user` group have the user role.

Your application has the following users and passwords:

[cols="<35, ^200, ^200"]
|===
| *Username* | *Password* | *Role*
| bob | bobpwd | admin, user
| alice | alicepwd | user
|===

Now you can secure the `inventory` service.

[role="code_command hotspot file=1", subs="quotes"]
----
#Replace the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

// File 1
SystemResource.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-securing/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

This class now has role-based access control. The role names that are used in the [hotspot=putRolesAllowed hotspot=deleteRolesAllowed file=1]`@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 [hotspot=putEndpoint file=1]`/{hostname}` endpoint that is annotated with the [hotspot=put file=1]`@PUT` annotation updates a system in the inventory. This PUT endpoint is annotated with the [hotspot=putRolesAllowed file=1]`@RolesAllowed({ "admin", "user" })` annotation. Only authenticated users with the role of `admin` or `user` can access this endpoint.

The [hotspot=deleteEndpoint file=1]`/{hostname}` endpoint that is annotated with the [hotspot=delete file=1]`@DELETE` annotation removes a system from the inventory. This DELETE endpoint is annotated with the [hotspot=deleteRolesAllowed file=1]`@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:

[role='command']
----
curl -X POST 'http://localhost:9080/inventory/api/systems?hostname=localhost&osName=mac&javaVersion=17&heapSize=1'
----

You can expect the following response:

[source, role="no_copy"]
----
{ "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:

ifndef::cloud-hosted[]
[role='command']
----
curl -s 'http://localhost:9080/inventory/api/systems'
----
endif::[]

ifdef::cloud-hosted[]
```bash
curl -s 'http://localhost:9080/inventory/api/systems' | jq
```
endif::[]

You can now expect the following response:

[source, role=no_copy]
----
[{"heapSize":1,"hostname":"localhost","javaVersion":"17","osName":"mac","id":23}]
----

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

[role='command']
----
curl -k --user alice:alicepwd -X PUT 'http://localhost:9080/inventory/api/systems/localhost?heapSize=2097152&javaVersion=17&osName=linux'
----

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

You should see the following response:

[source, role=no_copy]
----
{ "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:

[role='command']
----
curl -kf --user alice:alicepwd -X DELETE 'https://localhost:9443/inventory/api/systems/localhost'
----

You should see the following response:

[source, role=no_copy]
----
curl: (22) The requested URL returned error: 403
----

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

[source, role=no_copy]
----
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:

[role='command']
----
curl -k --user bob:bobpwd -X DELETE 'https://localhost:9443/inventory/api/systems/localhost'
----

You can expect to see the following response:

[source, role=no_copy]
----
{ "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:

[role='command']
----
curl 'http://localhost:9080/inventory/api/systems'
----

You can expect to see the following output:

[source, role=no_copy]
----
[]
----

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.

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
mkdir src\main\java\io\openliberty\deepdive\rest\client
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
mkdir src/main/java/io/openliberty/deepdive/rest/client
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir /home/project/guide-liberty-deep-dive/start/inventory/src/main/java/io/openliberty/deepdive/rest/client
```
endif::[]

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `SystemClient` interface.#
`src/main/java/io/openliberty/deepdive/rest/client/SystemClient.java`
----

// File 0
SystemClient.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/SystemClient.java[]
----

This interface declares methods for accessing each of the endpoints that are set up for you in the `system` service. The MicroProfile Rest Client feature automatically builds and generates a client implementation based on what is defined in the [hotspot file=0]`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.

[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `UnknownUriException` class.#
`src/main/java/io/openliberty/deepdive/rest/client/UnknownUriException.java`
----

// File 1
UnknownUriException.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/UnknownUriException.java[]
----

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

[role="code_command hotspot file=2", subs="quotes"]
----
#Create the `UnknownUriExceptionMapper` class.#
`src/main/java/io/openliberty/deepdive/rest/client/UnknownUriExceptionMapper.java`
----

// File 2
UnknownUriExceptionMapper.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/client/UnknownUriExceptionMapper.java[]
----

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

=== Implementing the `/client/{hostname}` endpoint

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

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

// File 0
SystemResource.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

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

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

=== Configuring the JSON Web Token

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

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----

// File 0
server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/src/main/liberty/config/server.xml[]
----

// File 1
microprofile-config.properties
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/system/src/main/webapp/META-INF/microprofile-config.properties[]
----

The [hotspot=jwtSsoFeature file=0]`jwtSso` feature adds the libraries that are required for JWT SSO implementation. Configure the [hotspot=jwtSsoConfig file=0]`jwtSso` feature by adding the [hotspot=jwtBuilder file=0]`jwtBuilder` configuration to your `server.xml` file. Also, configure the MicroProfile [hotspot=mpJwt file=0]`JWT` with the `audiences` and `issuer` properties that match the [hotspot file=1]`microprofile-config.properties` defined at the `system/src/main/webapp/META-INF` directory under the `system` project. For more information, see the https://www.openliberty.io/docs/latest/reference/feature/jwtSso-1.0.html[JSON Web Token Single Sign-On feature^], https://www.openliberty.io/docs/latest/reference/config/jwtSso.html[jwtSso element^], and https://www.openliberty.io/docs/latest/reference/config/jwtBuilder.html[jwtBuilder element^] documentation.

The [hotspot=keyStore file=0]`keyStore` element is used to define the repository of security certificates used for SSL encryption. The `id` attribute is a unique configuration ID that is set to `guideKeyStore`. The `password` attribute is used to load the keystore file, and its value can be stored in clear text or encoded form. To learn more about other attributes, see the https://openliberty.io/docs/latest/reference/config/keyStore.html#keyStore.html[keyStore attribute documentation^].

To avoid the conflict with the default ssl configuration, define your own ssl configuration by setting the [hotspot=ssl file=0]`id` attribute to other value, the [hotspot=sslDefault file=0]`sslDefault` element, and the [hotspot=mpJwt file=0]`sslRef` attribute in the `mpJwt` element.

Because the keystore file is not provided at the `src` directory, Liberty creates a Public Key Cryptography Standards #12 (PKCS12) keystore file for you by default. This file needs to be replaced, as the [hotspot=keyStore file=0]`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.

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
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
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
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
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir -p /home/project/guide-liberty-deep-dive/start/inventory/src/main/liberty/config/resources/security
cp /home/project/guide-liberty-deep-dive/finish/system/src/main/liberty/config/resources/security/key.p12 \
/home/project/guide-liberty-deep-dive/start/inventory/src/main/liberty/config/resources/security/key.p12
```
endif::[]

Now configure the client https port in the `pom.xml` configuration file.

[role="code_command hotspot file=2", subs="quotes"]
----
#Replace the `pom.xml` file.#
`pom.xml`
----

// File 2
pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-jwt/pom.xml[]
----

Configure the client https port by setting the [hotspot=https file=2]`` to `9444`.

In your dev mode console for the `inventory` microservice, press `CTRL+C` to stop the Liberty instance. Then, restart the dev mode of the `inventory` microservice.
[role='command']
```
mvn liberty:dev
```

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

[role="no_copy"]
----
**************************************************************
* 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.

ifndef::cloud-hosted[]
[role='command']
----
cd finish/system
mvn liberty:run
----
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/finish/system
mvn liberty:run
```
endif::[]

Wait until the following message displays on the `system` microservice console.
[source]
----
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. Open another command-line session and run the following command:

[role='command']
----
curl -kf 'https://localhost:9444/system/api/heapsize'
----

You should see the following response:

[source, role=no_copy]
----
curl: (22) The requested URL returned error: 401
----

You can expect to see the following error in the console of the `system` microservice:

[source]
----
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.

[role='command']
----
curl -k --user bob:bobpwd -X POST 'https://localhost:9443/inventory/api/systems/client/localhost'
----

You can expect the following output:

[source, role='no_copy']
----
{ "ok" : "localhost was added." }
----

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

ifndef::cloud-hosted[]
[role='command']
----
curl 'http://localhost:9080/inventory/api/systems'
----
endif::[]

ifdef::cloud-hosted[]
```bash
curl -s 'http://localhost:9080/inventory/api/systems' | jq
```
endif::[]

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

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

== Adding health checks
Next, you'll use https://download.eclipse.org/microprofile/microprofile-health-4.0/microprofile-health-spec-4.0.html[MicroProfile Health^] to report the health status of the microservice and PostgreSQL database connection.

Navigate to your application directory

ifndef::cloud-hosted[]
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

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.

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
mkdir src\main\java\io\openliberty\deepdive\rest\health
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
mkdir src/main/java/io/openliberty/deepdive/rest/health
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir /home/project/guide-liberty-deep-dive/start/inventory/src/main/java/io/openliberty/deepdive/rest/health
```
endif::[]

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `StartupCheck` class.#
`src/main/java/io/openliberty/deepdive/rest/health/StartupCheck.java`
----

StartupCheck.java
[source, java, linenums, role='code_column tags=StartupCheck hide_tags=copyright']
----
include::finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/StartupCheck.java[]
----

The [hotspot=Startup file=0]`@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.
ifdef::cloud-hosted[]
```bash
curl -s http://localhost:9080/health/started | jq
```
endif::[]

[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `LivenessCheck` class.#
`src/main/java/io/openliberty/deepdive/rest/health/LivenessCheck.java`
----

LivenessCheck.java
[source, java, linenums, role='code_column tags=LivenessCheck hide_tags=copyright']
----
include::finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/LivenessCheck.java[]
----

The [hotspot=Liveness file=1]`@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.

ifdef::cloud-hosted[]
```bash
curl -s http://localhost:9080/health/live | jq
```
endif::[]

[role="code_command hotspot file=2", subs="quotes"]
----
#Create the `ReadinessCheck` class.#
`src/main/java/io/openliberty/deepdive/rest/health/ReadinessCheck.java`
----

ReadinessCheck.java
[source, java, linenums, role='code_column tags=ReadinessCheck hide_tags=copyright']
----
include::finish/module-health-checks/src/main/java/io/openliberty/deepdive/rest/health/ReadinessCheck.java[]
----
The [hotspot=Readiness file=2]`@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.

ifdef::cloud-hosted[]
```bash
curl -s http://localhost:9080/health/ready | jq
```
endif::[]

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

ifdef::cloud-hosted[]
```bash
curl -s http://localhost:9080/health | jq
```
endif::[]

== Providing metrics

Next, you can learn how to use https://download.eclipse.org/microprofile/microprofile-metrics-4.0/microprofile-metrics-spec-4.0.html[MicroProfile Metrics^] to provide metrics from the `inventory` microservice.

Go to your application directory.

ifndef::cloud-hosted[]
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

Enable the `bob` user to access the `/metrics` endpoints.

[role="code_command hotspot file=0", subs="quotes"]
----
#Replace the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----

// File 0
server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-metrics/src/main/liberty/config/server.xml[]
----

The [hotspot=administrator file=0]`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.

[role="code_command hotspot file=1", subs="quotes"]
----
#Replace the `SystemResource` class.#
`src/main/java/io/openliberty/deepdive/rest/SystemResource.java`
----

// File 1
SystemResource.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-metrics/src/main/java/io/openliberty/deepdive/rest/SystemResource.java[]
----

Import the [hotspot=metricsImport file=1]`Counted` annotation and apply it to the [hotspot=metricsAddSystem file=1]`POST /api/systems`, [hotspot=metricsUpdateSystem file=1]`PUT /api/systems/{hostname}`, [hotspot=metricsRemoveSystem file=1]`DELETE /api/systems/{hostname}`, and [hotspot=metricsAddSystemClient file=1]`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 https://openliberty.io/docs/latest/reference/javadoc/microprofile-6.1-javadoc.html?package=org/eclipse/microprofile/metrics/annotation/package-frame.html&class=overview-summary.html[MicroProfile Metrics Annotation Javadoc^].

ifndef::cloud-hosted[]
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.
endif::[]

ifdef::cloud-hosted[]
Run the following commands to call some of the endpoints that you annotated:

```bash
curl -k --user bob:bobpwd -X DELETE \
'https://localhost:9443/inventory/api/systems/localhost'
```

```bash
curl -X POST 'http://localhost:9080/inventory/api/systems?heapSize=1048576&hostname=localhost&javaVersion=9&osName=linux'
```

```bash
curl -k --user alice:alicepwd -X PUT \
'http://localhost:9080/inventory/api/systems/localhost?heapSize=2097152&javaVersion=17&osName=linux'
```

```bash
curl -s 'http://localhost:9080/inventory/api/systems' | jq
```
endif::[]

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.

ifndef::cloud-hosted[]
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.

[source, role="no_copy"]
----
# 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.
endif::[]

// cloud-hosted guide instructions:
ifdef::cloud-hosted[]
Run the following curl command to see the application metrics that are enabled through MicroProfile Metrics:
```bash
curl -k --user bob:bobpwd https://localhost:9443/metrics?scope=application
```

You can expect to see your application metrics in text format as the following 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
```

To see the system metrics, run the following curl command:
```bash
curl -k --user bob:bobpwd https://localhost:9443/metrics\?scope=base
```

To see the vendor metrics, run the following curl command:
```bash
curl -k --user bob:bobpwd https://localhost:9443/metrics\?scope=vendor
```

To review all the metrics, run the following curl command:
```bash
curl -k --user bob:bobpwd https://localhost:9443/metrics
```
endif::[]

== Building the container 

Press `CTRL+C` in the command-line session to stop the `mvn liberty:dev` dev mode that you started in the previous section.

Navigate to your application directory:

ifndef::cloud-hosted[]
```
cd start/inventory
```
endif::[]

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

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

Make sure to start your Docker daemon before you proceed.

[role="code_command hotspot file=0",subs="quotes"]
----
#Replace the `Dockerfile` in the `start/inventory` directory.#
`Dockerfile`
----

Dockerfile
[source, text, linenums, role="code_column"]
----
include::finish/module-kubernetes/Dockerfile[]
----

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

To help you manage your images, you can label your container images with the [hotspot=label file=0]`LABEL` command.

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

=== Developing the application in a container

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

[role='code_command hotspot file=0', subs="quotes"]
----
#Replace the Liberty `server.xml` configuraton file.#
`src/main/liberty/config/server.xml`
----

server.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-kubernetes/src/main/liberty/config/server.xml[]
----

Instead of the hard-coded `serverName`, `portNumber`, `user`, and `password` values in the [hotspot=postgresProperties file=0]`properties.postgresql` properties, use `${postgres/hostname}`, `${postgres/portnum}`, `${postgres/username}`, and `${postgres/password}`, which are defined by the [hotspot=variables file=0]`variable` elements.

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

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

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

[role='command']
```
docker inspect -f "{{.NetworkSettings.IPAddress }}" postgres-container
```

The command returns the PostgreSQL container IP address:

[role="no_copy"]
----
172.17.0.2
----

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

ifndef::cloud-hosted[]
[role='command']
```
mvn liberty:devc -DdockerRunOpts="-e POSTGRES_HOSTNAME=172.17.0.2" -DserverStartTimeout=240
```
endif::[]

ifdef::cloud-hosted[]
```bash
chmod 777 /home/project/guide-liberty-deep-dive/start/inventory/target/liberty/wlp/usr/servers/defaultServer/logs
POSTGRES_IP=`docker inspect -f "{{.NetworkSettings.IPAddress }}" postgres-container`
mvn liberty:devc \
-DdockerRunOpts="-e POSTGRES_HOSTNAME=$POSTGRES_IP" \
-DserverStartTimeout=240
```
endif::[]

You need to wait a while to let dev mode start. After you see the following message, your Liberty instance is ready in dev mode:
[role="no_copy"]
----
**************************************************************
* Liberty is running in dev mode.
* ...
* Docker network information:
* Container name: [ liberty-dev ]
* IP address [ 172.17.0.2 ] on Docker network [ bridge ]
* ...
----

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

[role='command']
```
docker ps
```

You can see something similar to the following output:

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

ifndef::cloud-hosted[]
Point your browser to the http://localhost:9080/openapi/ui URL to try out your application.
endif::[]

ifdef::cloud-hosted[]
Try out your application by the following commands:

```bash
curl -s http://localhost:9080/health | jq
```

```bash
curl 'http://localhost:9080/inventory/api/systems'
```
endif::[]

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

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

[role='command']
```
docker stop postgres-container
docker rm postgres-container
```

=== Building the container image

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

ifdef::cloud-hosted[]
```bash
cd /home/project/guide-liberty-deep-dive/start/inventory
```
endif::[]

[role='command']
```
mvn package
```

Build your Docker image with the following commands:

[role='command']
```
docker build -t liberty-deepdive-inventory:1.0-SNAPSHOT .
```

ifdef::cloud-hosted[]
In this Skills Network environment, you need to push the image to your container registry on IBM Cloud by running the following commands:
```bash
docker tag liberty-deepdive-inventory:1.0-SNAPSHOT us.icr.io/$SN_ICR_NAMESPACE/liberty-deepdive-inventory:1.0-SNAPSHOT
docker push us.icr.io/$SN_ICR_NAMESPACE/liberty-deepdive-inventory:1.0-SNAPSHOT
```
endif::[]

When the build finishes, run the following command to list all local Docker images:
[role='command']
```
docker images
```

Verify that the `liberty-deepdive-inventory:1.0-SNAPSHOT` image is listed among the Docker images, for example:
[source, role="no_copy"]
----
REPOSITORY TAG
liberty-deepdive-inventory 1.0-SNAPSHOT
icr.io/appcafe/open-liberty full-java17-openj9-ubi
----

== Testing the microservice with Testcontainers

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

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

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section]
--
[role='command']
```
mkdir src\test\java\it\io\openliberty\deepdive\rest
mkdir src\test\resources
```
--

[.tab_content.mac_section.linux_section]
--
[role='command']
```
mkdir -p src/test/java/it/io/openliberty/deepdive/rest
mkdir src/test/resources
```
--
endif::[]

ifdef::cloud-hosted[]
```bash
mkdir -p /home/project/guide-liberty-deep-dive/start/inventory/src/test/java/it/io/openliberty/deepdive/rest
mkdir /home/project/guide-liberty-deep-dive/start/inventory/src/test/resources
```
endif::[]

Create a RESTful client interface for the `inventory` microservice.

[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `SystemResourceClient.java` file.#
`src/test/java/it/io/openliberty/deepdive/rest/SystemResourceClient.java`
----

// File 0
SystemResourceClient.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/src/test/java/it/io/openliberty/deepdive/rest/SystemResourceClient.java[]
----

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

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

[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `SystemData.java` file.#
`src/test/java/it/io/openliberty/deepdive/rest/SystemData.java`
----

// File 1
SystemData.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/src/test/java/it/io/openliberty/deepdive/rest/SystemData.java[]
----

The [hotspot=fields file=1]`SystemData` class contains the ID, hostname, operating system name, Java version, and heap size properties. The various [hotspot=getMethods file=1]`get` and [hotspot=setMethods file=1]`set` methods within this class enable you to view and edit the properties of each system in the inventory.

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

[role="code_command hotspot file=2", subs="quotes"]
----
#Create the `LibertyContainer.java` file.#
`src/test/java/it/io/openliberty/deepdive/rest/LibertyContainer.java`
----

// File 2
LibertyContainer.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/src/test/java/it/io/openliberty/deepdive/rest/LibertyContainer.java[]
----

The [hotspot=createRestClient file=2]`createRestClient()` method creates a REST client instance with the `SystemResourceClient` interface. The [hotspot=getBaseURL file=2]`getBaseURL()` method constructs the URL that can access the `inventory` docker image.

Now, you can create your integration test cases.

[role="code_command hotspot file=3", subs="quotes"]
----
#Create the `SystemResourceIT.java` file.#
`src/test/java/it/io/openliberty/deepdive/rest/SystemResourceIT.java`
----

// File 3
SystemResourceIT.java
[source, java, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/src/test/java/it/io/openliberty/deepdive/rest/SystemResourceIT.java[]
----

Define the [hotspot=postgresSetup file=3]`postgresContainer` test container to start up the PostgreSQL docker image, and define the [hotspot=libertySetup file=3]`libertyContainer` test container to start up the `inventory` docker image. Make sure that both containers use the same [hotspot=network hotspot=pNetwork hotspot=lNetwork file=3]`network`. The [hotspot=health file=3]`/health/ready` endpoint can tell you whether the container is ready to start testing.

The [hotspot=testAddSystem file=3]`testAddSystem()` verifies the [hotspot=addSystem file=3]`addSystem` and [hotspot=listContents file=3]`listContents` endpoints.

The [hotspot=testUpdateSystem file=3]`testUpdateSystem()` verifies the [hotspot=updateSystem file=3]`updateSystem` and [hotspot=getSystem file=3]`getSystem` endpoints.

The [hotspot=testRemoveSystem file=3]`testRemoveSystem()` verifies the [hotspot=removeSystem file=3]`removeSystem` endpoint.

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

[role="code_command hotspot file=4", subs="quotes"]
----
#Create the `log4j.properties` file.#
`src/test/resources/log4j.properties`
----

// File 4
log4j.properties
[source, text, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/src/test/resources/log4j.properties[]
----

Update the Maven configuration file with the required dependencies.

[role="code_command hotspot file=5", subs="quotes"]
----
#Replace the `pom.xml` file.#
`pom.xml`
----

// File 5
pom.xml
[source, xml, linenums, role='code_column hide_tags=copyright']
----
include::finish/module-testcontainers/pom.xml[]
----

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

=== Running the tests

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

ifndef::cloud-hosted[]
[.tab_link.windows_link]
`*WINDOWS*`
[.tab_link.mac_link]
`*MAC*`
[.tab_link.linux_link]
`*LINUX*`

[.tab_content.windows_section.mac_section]
--
[role='command']
```
mvn verify
```
--

[.tab_content.linux_section]
--
[role='command']
```
export TESTCONTAINERS_RYUK_DISABLED=true
mvn verify
```
--
endif::[]

ifdef::cloud-hosted[]
In this Skills Network environment, you can test the HTTP protcol only.
```bash
export TESTCONTAINERS_RYUK_DISABLED=true
mvn verify
```
endif::[]

You will see the following output:

[source,role="no_copy"]
----
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running it.io.openliberty.deepdive.rest.SystemResourceIT
...
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.413 s - in it.io.openliberty.deepdive.rest.SystemResourceIT

Results :

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

// Starting and preparing your cluster for deployment
ifndef::cloud-hosted[]
== Starting and preparing your cluster for deployment

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

Start your Kubernetes cluster.

Run the following command from a command-line session:

[role=command]
```
minikube start
```

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

[role=command]
```
kubectl get nodes
```

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

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

[role=command]
```
eval $(minikube docker-env)
```

Rebuild your Docker image under Minikube with the following commands:

[role='command']
```
docker build -t liberty-deepdive-inventory:1.0-SNAPSHOT .
```
endif::[]

== Deploying the microservice to Kubernetes

ifndef::cloud-hosted[]
If you are using Linux, you can continue this section.
endif::[]

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

=== Installing the Open Liberty Operator

ifndef::cloud-hosted[]
Install the Open Liberty Operator to deploy the microservice to Kubernetes.

First, install the `cert-manager` to your Kubernetes cluster by running the following command:
[role='command']
```
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.12.3/cert-manager.yaml
```

Next, install Custom Resource Definitions (CRDs) for the Open Liberty Operator by running the following command:
[role='command']
```
kubectl apply --server-side -f https://raw.githubusercontent.com/OpenLiberty/open-liberty-operator/main/deploy/releases/1.2.1/kubectl/openliberty-app-crd.yaml
```
Custom Resources extend the Kubernetes API and enhance its functionality.

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

[role='command']
```
OPERATOR_NAMESPACE=default
WATCH_NAMESPACE='""'
```

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

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

Finally, run the following commands to install the Operator:

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

ifdef::cloud-hosted[]
In this Skills Network environment, the Open Liberty Operator is already installed by the administrator. If you would like to learn how to install the Open Liberty Operator, see the [Deploying a microservice to Kubernetes by using Open Liberty Operator](https://openliberty.io/guides/openliberty-operator-intro.html) guide or the Open Liberty Operator [documentation](https://github.com/OpenLiberty/open-liberty-operator/tree/main/deploy/releases/1.2.1#readme).
endif::[]

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

[role='command']
```
kubectl api-resources --api-group=apps.openliberty.io
```

Look for the following output, which shows the https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/[custom resource definitions^] (CRDs) that can be used by the Open Liberty Operator:

[role='no_copy']
```
NAME SHORTNAMES APIGROUP NAMESPACED KIND
openlibertyapplications olapp,olapps apps.openliberty.io true OpenLibertyApplication
openlibertydumps oldump,oldumps apps.openliberty.io true OpenLibertyDump
openlibertytraces oltrace,oltraces apps.openliberty.io true OpenLibertyTrace
```

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

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

=== Deploying the container image

[role="code_command hotspot file=0",subs="quotes"]
----
#Create the `inventory.yaml` in the `start/inventory` directory.#
`inventory.yaml`
----

// File 0
inventory.yaml
[source, yaml, linenums, role='code_column']
----
include::finish/module-kubernetes/inventory.init.yaml[]
----

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

// File 1
postgres.yaml
[source, yaml, linenums, role='code_column']
----
include::finish/postgres/postgres.yaml[]
----

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

// The [hotspot=deployment file=1]`Deployment` definition acts to deploy the necessary Kubernetes resources to serve the database. Finally, the [hotspot=service file=1]`Service` definition exposes the PostgreSQL service on a cluster-internal IP, so that the inventory service can make requests to it.

Create a Kubernetes Secret to configure the credentials for the `admin` user to access the database.
[role='command']
```
kubectl create secret generic post-app-credentials --from-literal username=admin --from-literal password=adminpwd
```

The credentials are passed to the PostgreSQL database service as environment variables in the [hotspot=env file=1]`env` field.

ifndef::cloud-hosted[]
Run the following command to deploy the application and database:
[role='command']
```
kubectl apply -f ../../finish/postgres/postgres.yaml
kubectl apply -f inventory.yaml
```
endif::[]

ifdef::cloud-hosted[]
To deploy the **inventory** microservice and ***Postgres*** database in this Skills Network environment, you need to update the image name so that the image in your IBM Cloud container registry is used, and add the **pullSecret** and ***pullPolicy*** settings. Run the following commands:

```bash
sed -i 's=namespace: default=namespace: '"$SN_ICR_NAMESPACE"'=g' /home/project/guide-liberty-deep-dive/finish/postgres/postgres.yaml
kubectl apply -f /home/project/guide-liberty-deep-dive/finish/postgres/postgres.yaml
sed -i 's=liberty-deepdive-inventory:1.0-SNAPSHOT=us.icr.io/'"$SN_ICR_NAMESPACE"'/liberty-deepdive-inventory:1.0-SNAPSHOT\n pullPolicy: Always\n pullSecret: icr=g' /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
kubectl apply -f /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
```
endif::[]

When your pods are deployed, run the following command to check their status:
[role='command']
```
kubectl get pods
```

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

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

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

[role='command']
```
kubectl port-forward svc/inventory-deployment 9443
```

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

ifndef::cloud-hosted[]
The application might take some time to get ready. See the https://localhost:9443/health URL to confirm that the `inventory` microservice is up and running.

Once your application is up and running, you can check out the service at the https://localhost:9443/openapi/ui/[https://localhost:9443/openapi/ui/^] URL. The servers dropdown list shows the `\https://localhost:9443/inventory` URL. Or, you can run the following command to access the inventory microservice:
[role='command']
```
curl -k https://localhost:9443/inventory/api/systems
```
endif::[]

ifdef::cloud-hosted[]
The application might take some time to get ready. To confirm that the ***inventory*** microservice is up and running, run the following curl command:

```bash
curl -k https://localhost:9443/health | jq
```

If the application is up and running, you are ready to access the microservice.
In another command-line session, access the microservice by running the following commands:

```bash
curl -k --user bob:bobpwd -X DELETE \
'https://localhost:9443/inventory/api/systems/localhost'
```

```bash
curl -k -X POST 'https://localhost:9443/inventory/api/systems?heapSize=1048576&hostname=localhost&javaVersion=9&osName=linux'
```

```bash
curl -k --user alice:alicepwd -X PUT \
'https://localhost:9443/inventory/api/systems/localhost?heapSize=2097152&javaVersion=17&osName=linux'
```

```bash
curl -k -s 'https://localhost:9443/inventory/api/systems' | jq
```
endif::[]

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

ifndef::cloud-hosted[]
[role='command']
```
kubectl delete -f inventory.yaml
```
endif::[]

ifdef::cloud-hosted[]
```bash
kubectl delete -f /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
```
endif::[]

=== Customizing deployments

// File 0
server.xml
[source, xml, linenums, role='code_column']
----
include::finish/module-kubernetes/src/main/liberty/config/server.xml[]
----

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

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

Create a ConfigMap to configure the app name with the following `kubectl` command.
[role='command']
```
kubectl create configmap inv-app-root --from-literal contextRoot=/dev
```
This command deploys a ConfigMap named `inv-app-root` to your cluster. It has a key called `contextRoot` with a value of `/dev`. The `--from-literal` flag specifies individual key-value pairs to store in this ConfigMap.

[role="code_command hotspot file=1", subs="quotes"]
----
#Replace the `inventory.yaml` file.#
`inventory.yaml`
----

// File 1
inventory.yaml
[source, yaml, linenums, role='code_column']
----
include::finish/module-kubernetes/inventory.yaml[]
----

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

Run the following command to deploy your changes.
ifndef::cloud-hosted[]
[role='command']
```
kubectl apply -f inventory.yaml
```
endif::[]

ifdef::cloud-hosted[]
```bash
sed -i 's=liberty-deepdive-inventory:1.0-SNAPSHOT=us.icr.io/'"$SN_ICR_NAMESPACE"'/liberty-deepdive-inventory:1.0-SNAPSHOT\n pullPolicy: Always\n pullSecret: icr=g' /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
kubectl apply -f /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
```
endif::[]

Run the following command to check your pods status:
[role='command']
```
kubectl get pods
```

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

[role="no_copy"]
----
NAME READY STATUS RESTARTS AGE
inventory-deployment-75f9dc56d9-g9lzl 1/1 Running 0 35s
postgres-58bd9b55c7-6vzz8 1/1 Running 0 13s
----

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

[role='command']
```
kubectl port-forward svc/inventory-deployment 9443
```

ifndef::cloud-hosted[]
The application might take some time to get ready. See the https://localhost:9443/health URL to confirm that the `inventory` microservice is up and running. You can now check out the service at the https://localhost:9443/openapi/ui/[https://localhost:9443/openapi/ui/^] URL. The servers dropdown list shows the `\https://localhost:9443/dev` URL. Or, you can run the following command to access the inventory microservice:
[role='command']
```
curl -k https://localhost:9443/dev/api/systems
```
endif::[]

ifdef::cloud-hosted[]
The application might take some time to get ready. To confirm that the `inventory` microservice is up and running, run the following curl command in another command-line session:

```bash
curl -k https://localhost:9443/health | jq
```

If the application is up and running, you are ready to access the microservice.

Access the microservice with the context root ***/dev*** by running the following commands:

```bash
curl -k --user bob:bobpwd -X DELETE \
'https://localhost:9443/dev/api/systems/localhost'
```

```bash
curl -k -X POST 'https://localhost:9443/dev/api/systems?heapSize=1048576&hostname=localhost&javaVersion=9&osName=linux'
```

```bash
curl -k --user alice:alicepwd -X PUT \
'https://localhost:9443/dev/api/systems/localhost?heapSize=2097152&javaVersion=17&osName=linux'
```

```bash
curl -k -s 'https://localhost:9443/dev/api/systems' | jq
```
endif::[]

=== Tearing down the environment

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

ifndef::cloud-hosted[]
[role='command']
```
kubectl delete -f inventory.yaml
kubectl delete -f ../../finish/postgres/postgres.yaml
kubectl delete configmap inv-app-root
kubectl delete secret post-app-credentials
```

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

[role='command']
```
OPERATOR_NAMESPACE=default
WATCH_NAMESPACE='""'

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

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

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

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

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

. Point the Docker daemon back to your local machine:
+
[role=command]
```
eval $(minikube docker-env -u)
```
. Stop your Minikube cluster:
+
[role=command]
```
minikube stop
```

. Delete your cluster:
+
[role=command]
```
minikube delete
```

endif::[]

ifdef::cloud-hosted[]
```bash
kubectl delete -f /home/project/guide-liberty-deep-dive/start/inventory/inventory.yaml
kubectl delete -f /home/project/guide-liberty-deep-dive/finish/postgres/postgres.yaml
kubectl delete configmap inv-app-root
kubectl delete secret post-app-credentials
```
endif::[]

== 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 https://github.com/openliberty/open-liberty[GitHub^]. Commercial support is available for Open Liberty from IBM. For more information, see the https://www.ibm.com/uk-en/marketplace/elite-support-for-open-liberty[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 https://search.maven.org/search?q=g:com.ibm.websphere.appserver.runtime[Maven Central^].

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

In the `pom.xml`, add the `` element as the following:

```XML

io.openliberty.tools
liberty-maven-plugin
3.10.2


com.ibm.websphere.appserver.runtime
wlp-kernel
[24.0.0.2,)
zip



```

Rebuild and restart the `inventory` service by dev mode:

[role="no_copy"]
----
mvn clean
mvn liberty:dev
----

In the `Dockerfile`, replace the Liberty image at the `FROM` statement with `websphere-liberty` as shown in the following example:
[role="no_copy"]
----
FROM icr.io/appcafe/websphere-liberty:full-java17-openj9-ubi

ARG VERSION=1.0
ARG REVISION=SNAPSHOT
...
----

== Great work! You're done!

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

include::{common-includes}/attribution.adoc[]