Consuming RESTful services with template interfaces

duration 20 minutes

Prerequisites:

Learn how to use MicroProfile Rest Client to invoke RESTful microservices over HTTP in a type-safe way.

What you’ll learn

You will learn how to build a MicroProfile Rest Client to access remote RESTful services. You will create a template interface that maps to the remote service that you want to call. MicroProfile Rest Client automatically generates a client instance based on what is defined and annotated in the template interface. Thus, you don’t have to worry about all of the boilerplate code, such as setting up a client class, connecting to the remote server, or invoking the correct URI with the correct parameters.

The application that you will be working with is an inventory service, which fetches and stores the system property information for different hosts. Whenever a request is made to retrieve the system properties of a particular host, the inventory service will create a client to invoke the system service on that host. The system service simulates a remote service in the application.

You will instantiate the client and use it in the inventory service. You can choose from two different approaches, Context and Dependency Injection (CDI) with the help of MicroProfile Config or the RestClientBuilder method. In this guide, you will explore both methods to handle scenarios for providing a valid base URL.

  • When the base URL of the remote service is static and known, define the default base URL in the configuration file. Inject the client with CDI method.

  • When the base URL is not yet known and needs to be determined during the run time, set the base URL as a variable. Build the client with the more verbose RestClientBuilder method.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-rest-client.git
cd guide-microprofile-rest-client

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

cd finish
mvn liberty:run

After you see the following message, your application server is ready.

The defaultServer server is ready to run a smarter planet.

You can access the following microservices:

  • The http://localhost:9080/system/properties microservice simulates the remote system service that retrieves the system property information for a specific host. In this case, localhost is a specific host name.

  • The http://localhost:9080/inventory/systems/localhost microservice is the inventory service that invokes the http://localhost:9080/system/properties microservice to retrieves the system property information.

  • The http://localhost:9080/inventory/systems/{your_hostname} microservice is the inventory service that invokes the http://{your_hostname}:9080/system/properties microservice. In Windows, Mac OS, and Linux, get your fully qualified domain name (FQDN) by entering hostname from your terminal. Visit the URL by replacing {your_hostname} with your FQDN. You will see the same system property information, but the process of getting the information is different.

After you are finished checking out the application, stop the Open Liberty server by pressing CTRL+C in the command-line session where you ran the server. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Writing the RESTful client interface

Now, navigate to the start directory to begin.

When you run Open Liberty in development mode, known as dev mode, the server listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

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

Press the Enter key to run tests on demand.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

The MicroProfile Rest Client API is included in the MicroProfile dependency specified by your pom.xml file. Look for the dependency with the microprofile artifact ID.

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<project xmlns="http://maven.apache.org/POM/4.0.0"
  3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6    <modelVersion>4.0.0</modelVersion>
  7
  8    <groupId>io.openliberty.guides</groupId>
  9    <artifactId>guide-microprofile-rest-client</artifactId>
 10    <version>1.0-SNAPSHOT</version>
 11    <packaging>war</packaging>
 12
 13    <properties>
 14        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 16        <maven.compiler.source>1.8</maven.compiler.source>
 17        <maven.compiler.target>1.8</maven.compiler.target>
 18        <!-- Liberty configuration -->
 19        <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 20        <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 21    </properties>
 22
 23    <dependencies>
 24        <!-- Provided dependencies -->
 25        <dependency>
 26            <groupId>jakarta.platform</groupId>
 27            <artifactId>jakarta.jakartaee-api</artifactId>
 28            <version>8.0.0</version>
 29            <scope>provided</scope>
 30        </dependency>
 31        <dependency>
 32            <groupId>org.eclipse.microprofile</groupId>
 33            <!-- tag::microprofile[] -->
 34            <artifactId>microprofile</artifactId>
 35            <!-- end::microprofile[] -->
 36            <version>3.3</version>
 37            <type>pom</type>
 38            <scope>provided</scope>
 39        </dependency>
 40        <!-- Java utility classes -->
 41        <dependency>
 42            <groupId>org.apache.commons</groupId>
 43            <artifactId>commons-lang3</artifactId>
 44            <version>3.10</version>
 45        </dependency>
 46        <!-- For tests-->
 47        <dependency>
 48            <groupId>org.junit.jupiter</groupId>
 49            <artifactId>junit-jupiter</artifactId>
 50            <version>5.6.2</version>
 51            <scope>test</scope>
 52        </dependency>
 53        <dependency>
 54            <groupId>org.apache.cxf</groupId>
 55            <artifactId>cxf-rt-rs-client</artifactId>
 56            <version>3.3.6</version>
 57            <scope>test</scope>
 58        </dependency>
 59        <dependency>
 60            <groupId>org.apache.cxf</groupId>
 61            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 62            <version>3.3.6</version>
 63            <scope>test</scope>
 64        </dependency>
 65        <dependency>
 66            <groupId>org.glassfish</groupId>
 67            <artifactId>javax.json</artifactId>
 68            <version>1.1.4</version>
 69            <scope>test</scope>
 70        </dependency>
 71    </dependencies>
 72
 73    <build>
 74        <finalName>${project.artifactId}</finalName>
 75        <plugins>
 76            <plugin>
 77                <groupId>org.apache.maven.plugins</groupId>
 78                <artifactId>maven-war-plugin</artifactId>
 79                <version>3.2.3</version>
 80            </plugin>
 81            <!-- Plugin to run unit tests -->
 82            <plugin>
 83                <groupId>org.apache.maven.plugins</groupId>
 84                <artifactId>maven-surefire-plugin</artifactId>
 85                <version>2.22.2</version>
 86            </plugin>
 87            <!-- Enable liberty-maven plugin -->
 88            <plugin>
 89                <groupId>io.openliberty.tools</groupId>
 90                <artifactId>liberty-maven-plugin</artifactId>
 91                <version>3.2</version>
 92            </plugin>
 93            <!-- Plugin to run functional tests -->
 94            <plugin>
 95                <groupId>org.apache.maven.plugins</groupId>
 96                <artifactId>maven-failsafe-plugin</artifactId>
 97                <version>2.22.2</version>
 98                <configuration>
 99                    <systemPropertyVariables>
100                        <http.port>${liberty.var.default.http.port}</http.port>
101                    </systemPropertyVariables>
102                </configuration>
103            </plugin>
104        </plugins>
105    </build>
106</project>

This dependency provides a library that is required to implement the MicroProfile Rest Client interface.

The mpRestClient feature is also enabled in the src/main/liberty/config/server.xml file. This feature enables your Open Liberty server to use MicroProfile Rest Client to invoke RESTful microservices.

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <!-- tag::mpConfig[] -->
 8    <feature>mpConfig-1.4</feature>
 9    <!-- end::mpConfig[] -->
10    <!-- tag::mpRestClient[] -->
11    <feature>mpRestClient-1.4</feature>
12    <!-- end::mpRestClient[] -->
13  </featureManager>
14
15  <variable name="default.http.port" defaultValue="9080"/>
16  <variable name="default.https.port" defaultValue="9443"/>
17
18  <httpEndpoint host="*" httpPort="${default.http.port}" httpsPort="${default.https.port}"
19                id="defaultHttpEndpoint"/>
20
21  <webApplication location="guide-microprofile-rest-client.war" contextRoot="/"/>
22</server>

The code for the system service in the src/main/java/io/openliberty/guides/system directory is provided for you. It simulates a remote RESTful service that the inventory service invokes.

Create a RESTful client interface for the system service. Write a template interface that maps the API of the remote system service. The template interface describes the remote service that you want to access. The interface defines the resource to access as a method by mapping its annotations, return type, list of arguments, and exception declarations.

Create the SystemClient class.
src/main/java/io/openliberty/guides/inventory/client/SystemClient.java

SystemClient.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::client[]
14package io.openliberty.guides.inventory.client;
15
16import java.util.Properties;
17
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.ProcessingException;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23
24import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
25import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
26
27// tag::RegisterRestClient[]
28@RegisterRestClient(configKey = "systemClient", baseUri = "http://localhost:9080/system")
29// end::RegisterRestClient[]
30// tag::RegisterProvider[]
31@RegisterProvider(UnknownUriExceptionMapper.class)
32// end::RegisterProvider[]
33@Path("/properties")
34// tag::SystemClient[]
35// tag::AutoCloseable[]
36public interface SystemClient extends AutoCloseable {
37// end::AutoCloseable[]
38
39  @GET
40  // tag::Produces[]
41  @Produces(MediaType.APPLICATION_JSON)
42  // end::Produces[]
43  // tag::getProperties[]
44  public Properties getProperties() throws UnknownUriException, ProcessingException;
45  // end::getProperties[]
46}
47// end::SystemClient[]
48// end::client[]

The MicroProfile Rest Client feature automatically builds and generates a client implementation based on what is defined in the SystemClient interface. There is no need to set up the client and connect with the remote service.

Notice the SystemClient interface inherits the AutoCloseable interface. This allows the user to explicitly close the client instance by invoking the close() method or to implicitly close the client instance using a try-with-resources block. When the client instance is closed, all underlying resources associated with the client instance are cleaned up. Refer to the MicroProfile Rest Client specification for more details.

When the getProperties() method is invoked, the SystemClient instance sends a GET request to the <baseUrl>/properties endpoint, where <baseUrl> is the default base URL of the system service. You will see how to configure the base URL in the next section.

The @Produces annotation specifies the media (MIME) type of the expected response. The default value is MediaType.APPLICATION_JSON.

The @RegisterProvider annotation tells the framework to register the provider classes to be used when the framework invokes the interface. You can add as many providers as necessary. In the SystemClient interface, add a response exception mapper as a provider to map the 404 response code with the UnknownUriException exception.

Handling exceptions through ResponseExceptionMappers

Error handling is an important step to ensure that the application can fail safely. If there is an error response such as 404 NOT FOUND when invoking the remote service, you need to handle it. First, define an exception, and map the exception with the error response code. Then, register the exception mapper in the client interface.

Look at the client interface again, the @RegisterProvider annotation registers the UnknownUriExceptionMapper response exception mapper. An exception mapper maps various response codes from the remote service to throwable exceptions.

SystemClient.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::client[]
14package io.openliberty.guides.inventory.client;
15
16import java.util.Properties;
17
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.ProcessingException;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23
24import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
25import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
26
27// tag::RegisterRestClient[]
28@RegisterRestClient(configKey = "systemClient", baseUri = "http://localhost:9080/system")
29// end::RegisterRestClient[]
30// tag::RegisterProvider[]
31@RegisterProvider(UnknownUriExceptionMapper.class)
32// end::RegisterProvider[]
33@Path("/properties")
34// tag::SystemClient[]
35// tag::AutoCloseable[]
36public interface SystemClient extends AutoCloseable {
37// end::AutoCloseable[]
38
39  @GET
40  // tag::Produces[]
41  @Produces(MediaType.APPLICATION_JSON)
42  // end::Produces[]
43  // tag::getProperties[]
44  public Properties getProperties() throws UnknownUriException, ProcessingException;
45  // end::getProperties[]
46}
47// end::SystemClient[]
48// end::client[]

Implement the actual exception class and the mapper class to see how this mechanism works.

Create the UnknownUriException class.
src/main/java/io/openliberty/guides/inventory/client/UnknownUriException.java

UnknownUriException.java

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

Now, link the UnknownUriException class with the corresponding response code through a ResponseExceptionMapper mapper class.

Create the UnknownUriExceptionMapper class.
src/main/java/io/openliberty/guides/inventory/client/UnknownUriExceptionMapper.java

UnknownUriExceptionMapper.java

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

The handles() method inspects the HTTP response code to determine whether an exception is thrown for the specific response, and the toThrowable() method returns the mapped exception.

Injecting the client with dependency injection

Now, instantiate the SystemClient interface and use it in the inventory service. If you want to connect only with the default host name, you can easily instantiate the SystemClient with CDI annotations. CDI injection simplifies the process of bootstrapping the client.

First, you need to define the base URL of the SystemClient instance. Configure the default base URL with the MicroProfile Config feature. This feature is enabled for you in the server.xml file.

Create the configuration file.
src/main/webapp/META-INF/microprofile-config.properties

microprofile-config.properties

1# tag::config[]
2# tag::baseUri[]
3systemClient/mp-rest/uri=http://localhost:9080/system
4# end::baseUri[]
5# end::config[]

The mp-rest/uri base URL config property is configured to the default http://localhost:9080/system URL.

This configuration is automatically picked up by the MicroProfile Config API.

Look at the annotations in the SystemClient interface again.

SystemClient.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::client[]
14package io.openliberty.guides.inventory.client;
15
16import java.util.Properties;
17
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.ProcessingException;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23
24import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
25import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
26
27// tag::RegisterRestClient[]
28@RegisterRestClient(configKey = "systemClient", baseUri = "http://localhost:9080/system")
29// end::RegisterRestClient[]
30// tag::RegisterProvider[]
31@RegisterProvider(UnknownUriExceptionMapper.class)
32// end::RegisterProvider[]
33@Path("/properties")
34// tag::SystemClient[]
35// tag::AutoCloseable[]
36public interface SystemClient extends AutoCloseable {
37// end::AutoCloseable[]
38
39  @GET
40  // tag::Produces[]
41  @Produces(MediaType.APPLICATION_JSON)
42  // end::Produces[]
43  // tag::getProperties[]
44  public Properties getProperties() throws UnknownUriException, ProcessingException;
45  // end::getProperties[]
46}
47// end::SystemClient[]
48// end::client[]

The @RegisterRestClient annotation registers the interface as a RESTful client. The runtime creates a CDI managed bean for every interface that is annotated with the @RegisterRestClient annotation.

The configKey value in the @RegisterRestClient annotation replaces the fully-qualified classname of the properties in the microprofile-config.properties configuration file. For example, the <fully-qualified classname>/mp-rest/uri property becomes systemClient/mp-rest/uri. The benefit of using Config Keys is when multiple client interfaces have the same configKey value, the interfaces can be configured with a single MP config property.

The baseUri value can also be set in the @RegisterRestClient annotation. However, this value will be overridden by the base URI property defined in the microprofile-config.properties configuration file, which takes precedence. In a production environment, you can use the baseUri variable to specify a different URI for development and testing purposes.

The @RegisterRestClient annotation, which is a bean defining annotation implies that the interface is manageable through CDI. You must have this annotation in order to inject the client.

Inject the SystemClient interface into the InventoryManager class, which is another CDI managed bean.

Replace the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2020 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::manager[]
 14package io.openliberty.guides.inventory;
 15
 16import java.net.ConnectException;
 17import java.net.URI;
 18import java.net.UnknownHostException;
 19import java.util.ArrayList;
 20import java.util.Collections;
 21import java.util.List;
 22import java.util.Properties;
 23
 24import javax.enterprise.context.ApplicationScoped;
 25import javax.inject.Inject;
 26import javax.ws.rs.ProcessingException;
 27
 28import org.apache.commons.lang3.exception.ExceptionUtils;
 29import org.eclipse.microprofile.rest.client.RestClientBuilder;
 30import org.eclipse.microprofile.rest.client.inject.RestClient;
 31import org.eclipse.microprofile.config.inject.ConfigProperty;
 32
 33import io.openliberty.guides.inventory.client.SystemClient;
 34import io.openliberty.guides.inventory.client.UnknownUriException;
 35import io.openliberty.guides.inventory.client.UnknownUriExceptionMapper;
 36import io.openliberty.guides.inventory.model.InventoryList;
 37import io.openliberty.guides.inventory.model.SystemData;
 38
 39// tag::ApplicationScoped[]
 40@ApplicationScoped
 41// end::ApplicationScoped[]
 42public class InventoryManager {
 43
 44  private List<SystemData> systems = Collections.synchronizedList(
 45                                       new ArrayList<SystemData>());
 46
 47  @Inject
 48  @ConfigProperty(name = "default.http.port")
 49  String DEFAULT_PORT;
 50
 51  // tag::Inject[]
 52  @Inject
 53  // end::Inject[]
 54  // tag::RestClient[]
 55  @RestClient
 56  // end::RestClient[]
 57  // tag::SystemClient[]
 58  private SystemClient defaultRestClient;
 59  // end::SystemClient[]
 60
 61  public Properties get(String hostname) {
 62    Properties properties = null;
 63    if (hostname.equals("localhost")) {
 64      properties = getPropertiesWithDefaultHostName();
 65    } else {
 66      properties = getPropertiesWithGivenHostName(hostname);
 67    }
 68
 69    return properties;
 70  }
 71
 72  public void add(String hostname, Properties systemProps) {
 73    Properties props = new Properties();
 74    props.setProperty("os.name", systemProps.getProperty("os.name"));
 75    props.setProperty("user.name", systemProps.getProperty("user.name"));
 76
 77    SystemData host = new SystemData(hostname, props);
 78    if (!systems.contains(host))
 79      systems.add(host);
 80  }
 81
 82  public InventoryList list() {
 83    return new InventoryList(systems);
 84  }
 85
 86  // tag::getPropertiesWithDefaultHostName[]
 87  private Properties getPropertiesWithDefaultHostName() {
 88    try {
 89      // tag::defaultRCGetProperties[]
 90      return defaultRestClient.getProperties();
 91      // end::defaultRCGetProperties[]
 92    } catch (UnknownUriException e) {
 93      System.err.println("The given URI is not formatted correctly.");
 94    } catch (ProcessingException ex) {
 95      handleProcessingException(ex);
 96    }
 97    return null;
 98  }
 99  // end::getPropertiesWithDefaultHostName[]
100
101  // tag::getPropertiesWithGivenHostName[]
102  private Properties getPropertiesWithGivenHostName(String hostname) {
103    String customURIString = "http://" + hostname + ":" + DEFAULT_PORT + "/system";
104    URI customURI = null;
105    try {
106      customURI = URI.create(customURIString);
107      // tag::customRestClientBuilder[]
108      SystemClient customRestClient = RestClientBuilder.newBuilder()
109                                        .baseUri(customURI)
110                                        .register(UnknownUriExceptionMapper.class)
111                                        .build(SystemClient.class);
112      // end::customRestClientBuilder[]
113      // tag::customRCGetProperties[]
114      return customRestClient.getProperties();
115      // end::customRCGetProperties[]
116    } catch (ProcessingException ex) {
117      handleProcessingException(ex);
118    } catch (UnknownUriException e) {
119      System.err.println("The given URI is unreachable.");
120    }
121    return null;
122  }
123  // end::getPropertiesWithGivenHostName[]
124
125  private void handleProcessingException(ProcessingException ex) {
126    Throwable rootEx = ExceptionUtils.getRootCause(ex);
127    if (rootEx != null && (rootEx instanceof UnknownHostException
128        || rootEx instanceof ConnectException)) {
129      System.err.println("The specified host is unknown.");
130    } else {
131      throw ex;
132    }
133  }
134
135}
136// end::manager[]

@Inject and @RestClient annotations inject an instance of the SystemClient called defaultRestClient to the InventoryManager class.

Because the InventoryManager class is @ApplicationScoped, and the SystemClient CDI bean maintains the same scope through the default dependent scope, the client is initialized once per application.

If the hostname parameter is localhost, the service runs the getPropertiesWithDefaultHostName() helper function to fetch system properties. The helper function invokes the system service by calling the defaultRestClient.getProperties() method.

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <!-- tag::mpConfig[] -->
 8    <feature>mpConfig-1.4</feature>
 9    <!-- end::mpConfig[] -->
10    <!-- tag::mpRestClient[] -->
11    <feature>mpRestClient-1.4</feature>
12    <!-- end::mpRestClient[] -->
13  </featureManager>
14
15  <variable name="default.http.port" defaultValue="9080"/>
16  <variable name="default.https.port" defaultValue="9443"/>
17
18  <httpEndpoint host="*" httpPort="${default.http.port}" httpsPort="${default.https.port}"
19                id="defaultHttpEndpoint"/>
20
21  <webApplication location="guide-microprofile-rest-client.war" contextRoot="/"/>
22</server>

Building the client with RestClientBuilder

The inventory service can also connect with a host other than the default localhost host, but you cannot configure a base URL that is not yet known. In this case, set the host name as a variable and build the client by using the RestClientBuilder method. You can customize the base URL from the host name attribute.

Look at the getPropertiesWithGivenHostName() method in the src/main/java/io/openliberty/guides/inventory/InventoryManager.java file.

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2020 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::manager[]
 14package io.openliberty.guides.inventory;
 15
 16import java.net.ConnectException;
 17import java.net.URI;
 18import java.net.UnknownHostException;
 19import java.util.ArrayList;
 20import java.util.Collections;
 21import java.util.List;
 22import java.util.Properties;
 23
 24import javax.enterprise.context.ApplicationScoped;
 25import javax.inject.Inject;
 26import javax.ws.rs.ProcessingException;
 27
 28import org.apache.commons.lang3.exception.ExceptionUtils;
 29import org.eclipse.microprofile.rest.client.RestClientBuilder;
 30import org.eclipse.microprofile.rest.client.inject.RestClient;
 31import org.eclipse.microprofile.config.inject.ConfigProperty;
 32
 33import io.openliberty.guides.inventory.client.SystemClient;
 34import io.openliberty.guides.inventory.client.UnknownUriException;
 35import io.openliberty.guides.inventory.client.UnknownUriExceptionMapper;
 36import io.openliberty.guides.inventory.model.InventoryList;
 37import io.openliberty.guides.inventory.model.SystemData;
 38
 39// tag::ApplicationScoped[]
 40@ApplicationScoped
 41// end::ApplicationScoped[]
 42public class InventoryManager {
 43
 44  private List<SystemData> systems = Collections.synchronizedList(
 45                                       new ArrayList<SystemData>());
 46
 47  @Inject
 48  @ConfigProperty(name = "default.http.port")
 49  String DEFAULT_PORT;
 50
 51  // tag::Inject[]
 52  @Inject
 53  // end::Inject[]
 54  // tag::RestClient[]
 55  @RestClient
 56  // end::RestClient[]
 57  // tag::SystemClient[]
 58  private SystemClient defaultRestClient;
 59  // end::SystemClient[]
 60
 61  public Properties get(String hostname) {
 62    Properties properties = null;
 63    if (hostname.equals("localhost")) {
 64      properties = getPropertiesWithDefaultHostName();
 65    } else {
 66      properties = getPropertiesWithGivenHostName(hostname);
 67    }
 68
 69    return properties;
 70  }
 71
 72  public void add(String hostname, Properties systemProps) {
 73    Properties props = new Properties();
 74    props.setProperty("os.name", systemProps.getProperty("os.name"));
 75    props.setProperty("user.name", systemProps.getProperty("user.name"));
 76
 77    SystemData host = new SystemData(hostname, props);
 78    if (!systems.contains(host))
 79      systems.add(host);
 80  }
 81
 82  public InventoryList list() {
 83    return new InventoryList(systems);
 84  }
 85
 86  // tag::getPropertiesWithDefaultHostName[]
 87  private Properties getPropertiesWithDefaultHostName() {
 88    try {
 89      // tag::defaultRCGetProperties[]
 90      return defaultRestClient.getProperties();
 91      // end::defaultRCGetProperties[]
 92    } catch (UnknownUriException e) {
 93      System.err.println("The given URI is not formatted correctly.");
 94    } catch (ProcessingException ex) {
 95      handleProcessingException(ex);
 96    }
 97    return null;
 98  }
 99  // end::getPropertiesWithDefaultHostName[]
100
101  // tag::getPropertiesWithGivenHostName[]
102  private Properties getPropertiesWithGivenHostName(String hostname) {
103    String customURIString = "http://" + hostname + ":" + DEFAULT_PORT + "/system";
104    URI customURI = null;
105    try {
106      customURI = URI.create(customURIString);
107      // tag::customRestClientBuilder[]
108      SystemClient customRestClient = RestClientBuilder.newBuilder()
109                                        .baseUri(customURI)
110                                        .register(UnknownUriExceptionMapper.class)
111                                        .build(SystemClient.class);
112      // end::customRestClientBuilder[]
113      // tag::customRCGetProperties[]
114      return customRestClient.getProperties();
115      // end::customRCGetProperties[]
116    } catch (ProcessingException ex) {
117      handleProcessingException(ex);
118    } catch (UnknownUriException e) {
119      System.err.println("The given URI is unreachable.");
120    }
121    return null;
122  }
123  // end::getPropertiesWithGivenHostName[]
124
125  private void handleProcessingException(ProcessingException ex) {
126    Throwable rootEx = ExceptionUtils.getRootCause(ex);
127    if (rootEx != null && (rootEx instanceof UnknownHostException
128        || rootEx instanceof ConnectException)) {
129      System.err.println("The specified host is unknown.");
130    } else {
131      throw ex;
132    }
133  }
134
135}
136// end::manager[]

The host name is provided as a parameter. This method first assembles the base URL that consists of the new host name. Then, the method instantiates a RestClientBuilder builder with the new URL, registers the response exception mapper, and builds the SystemClient instance.

Similarly, call the customRestClient.getProperties() method to invoke the system service.

Running the application

You started the Open Liberty server in dev mode at the beginning of the guide, so all the changes were automatically picked up.

When the server is running, select either approach to fetch your system properties:

  • Visit the http://localhost:9080/inventory/systems/localhost URL. The URL retrieves the system property information for localhost host name by invoking the http://localhost:9080/system/properties service.

  • Get your FQDN first. Then, visit the http://localhost:9080/inventory/systems/{your_hostname} URL by replacing {your_hostname} with your FQDN, which retrieves your system properties by invoking the http://{your_hostname}:9080/system/properties service.

Testing the application

Create the RestClientIT class.
src/test/java/it/io/openliberty/guides/client/RestClientIT.java

RestClientIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2020 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::testClass[]
 14package it.io.openliberty.guides.client;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17import javax.json.JsonObject;
 18import javax.ws.rs.client.Client;
 19import javax.ws.rs.client.ClientBuilder;
 20import javax.ws.rs.core.Response;
 21import javax.ws.rs.client.WebTarget;
 22import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 23import org.junit.jupiter.api.AfterEach;
 24import org.junit.jupiter.api.BeforeEach;
 25import org.junit.jupiter.api.BeforeAll;
 26import org.junit.jupiter.api.Test;
 27import java.net.InetAddress;
 28import java.net.UnknownHostException;
 29
 30public class RestClientIT {
 31
 32  private static String port;
 33
 34  private Client client;
 35
 36  private final String INVENTORY_SYSTEMS = "inventory/systems";
 37
 38  @BeforeAll
 39  public static void oneTimeSetup() {
 40    port = System.getProperty("http.port");
 41  }
 42
 43  @BeforeEach
 44  public void setup() {
 45    client = ClientBuilder.newClient();
 46    client.register(JsrJsonpProvider.class);
 47  }
 48
 49  @AfterEach
 50  public void teardown() {
 51    client.close();
 52  }
 53
 54  @Test
 55  public void testSuite() {
 56    this.testDefaultLocalhost();
 57    this.testRestClientBuilder();
 58  }
 59
 60  // tag::testDefaultLocalhost[]
 61  public void testDefaultLocalhost() {
 62    String hostname = "localhost";
 63
 64    String url = "http://localhost:" + port + "/" + INVENTORY_SYSTEMS + "/" + hostname;
 65
 66    JsonObject obj = fetchProperties(url);
 67
 68    assertEquals(System.getProperty("os.name"), obj.getString("os.name"),
 69                 "The system property for the local and remote JVM should match");
 70  }
 71  // end::testDefaultLocalhost[]
 72
 73  // tag::testRestClientBuilder[]
 74  public void testRestClientBuilder() {
 75    String hostname = null;
 76    try{
 77      hostname = InetAddress.getLocalHost().getHostAddress();
 78    } catch (UnknownHostException e) {
 79      System.err.println("Unknown Host.");
 80    }
 81
 82    String url = "http://localhost:" + port + "/" + INVENTORY_SYSTEMS + "/" + hostname;
 83
 84    JsonObject obj = fetchProperties(url);
 85
 86    assertEquals(System.getProperty("os.name"), obj.getString("os.name"),
 87                 "The system property for the local and remote JVM should match");
 88  }
 89  // end::testRestClientBuilder[]
 90
 91  private JsonObject fetchProperties(String url) {
 92    WebTarget target = client.target(url);
 93    Response response = target.request().get();
 94
 95    assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
 96
 97    JsonObject obj = response.readEntity(JsonObject.class);
 98    response.close();
 99    return obj;
100  }
101
102}
103// end::testClass[]

Each test case tests one of the methods for instantiating a RESTful client.

The testDefaultLocalhost() test fetches and compares system properties from the http://localhost:9080/inventory/systems/localhost URL.

The testRestClientBuilder() test gets your IP address. Then, use your IP address as the host name to fetch your system properties and compare them.

In addition, a few endpoint tests are provided for you to test the basic functionality of the inventory and system services. If a test failure occurs, you might have introduced a bug into the code.

Running the tests

Since you started Open Liberty in dev mode, press the enter/return key to run the tests.

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.377 sec - in it.io.openliberty.guides.system.SystemEndpointIT
Running it.io.openliberty.guides.inventory.InventoryEndpointIT
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.379 sec - in it.io.openliberty.guides.inventory.InventoryEndpointIT
Running it.io.openliberty.guides.client.RestClientIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.121 sec - in it.io.openliberty.guides.client.RestClientIT

Results :

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

To see whether the tests detect a failure, change the base URL in the configuration file so that when the inventory service tries to access the invalid URL, an UnknownUriException is thrown. Rerun the tests to see a test failure occur.

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Great work! You’re done!

You just invoked a remote service by using a template interface with MicroProfile Rest Client in Open Liberty.

MicroProfile Rest Client also provides a uniform way to configure SSL for the client. You can learn more in the Hostname verification with SSL on Open Liberty and MicroProfile Rest Client blog and the MicroProfile Rest Client specification.

Feel free to try one of the related guides where you can learn more technologies and expand on what you built here.

Guide Attribution

Consuming RESTful services with template interfaces by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star