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

To try out the application, first navigate to the finish directory, which contains the complete inventory application. Then, run the following Maven goals to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

After you start the application, 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.

When you are done checking out the application, stop the Open Liberty server. You must stop your running Open Liberty server before you re-install it next time.

mvn liberty:stop-server

Writing the RESTful client interface

Now, navigate to the start directory to begin.

The MicroProfile Rest Client API is added as a dependency to your pom.xml file. Look for the dependency with the mpRestClient 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  <parent>
  8        <groupId>net.wasdev.wlp.maven.parent</groupId>
  9        <artifactId>liberty-maven-app-parent</artifactId>
 10        <version>RELEASE</version>
 11  </parent>
 12  <groupId>io.openliberty.guides</groupId>
 13  <artifactId>microprofile-rest-client</artifactId>
 14  <version>1.0.0-SNAPSHOT</version>
 15  <packaging>war</packaging>
 16    <properties>
 17        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 19        <maven.compiler.source>1.8</maven.compiler.source>
 20        <maven.compiler.target>1.8</maven.compiler.target>
 21        <app.name>LibertyProject</app.name>
 22        <testServerHttpPort>9080</testServerHttpPort>
 23        <testServerHttpsPort>9443</testServerHttpsPort>
 24        <package.file>${project.build.directory}/${app.name}.zip</package.file>
 25        <packaging.type>usr</packaging.type>
 26    </properties>
 27
 28    <dependencyManagement>
 29        <dependencies>
 30            <dependency>
 31                <groupId>io.openliberty.features</groupId>
 32                <artifactId>features-bom</artifactId>
 33                <version>RELEASE</version>
 34                <type>pom</type>
 35                <scope>import</scope>
 36            </dependency>
 37        </dependencies>
 38    </dependencyManagement>
 39
 40    <dependencies>
 41        <!-- For tests-->
 42        <dependency>
 43            <groupId>junit</groupId>
 44            <artifactId>junit</artifactId>
 45            <version>4.12</version>
 46            <scope>test</scope>
 47        </dependency>
 48        <dependency>
 49            <groupId>org.apache.cxf</groupId>
 50            <artifactId>cxf-rt-rs-client</artifactId>
 51            <version>3.2.6</version>
 52            <scope>test</scope>
 53        </dependency>
 54        <dependency>
 55            <groupId>org.apache.cxf</groupId>
 56            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 57            <version>3.2.6</version>
 58            <scope>test</scope>
 59        </dependency>
 60        <dependency>
 61            <groupId>org.glassfish</groupId>
 62            <artifactId>javax.json</artifactId>
 63            <version>1.0.4</version>
 64            <scope>test</scope>
 65        </dependency>
 66        <!-- Open Liberty features -->
 67        <dependency>
 68            <groupId>io.openliberty.features</groupId>
 69            <artifactId>jaxrs-2.1</artifactId>
 70            <type>esa</type>
 71            <scope>provided</scope>
 72        </dependency>
 73        <dependency>
 74            <groupId>io.openliberty.features</groupId>
 75            <artifactId>jsonp-1.1</artifactId>
 76            <type>esa</type>
 77            <scope>provided</scope>
 78        </dependency>
 79        <dependency>
 80            <groupId>io.openliberty.features</groupId>
 81            <artifactId>cdi-2.0</artifactId>
 82            <type>esa</type>
 83            <scope>provided</scope>
 84        </dependency>
 85        <dependency>
 86            <groupId>io.openliberty.features</groupId>
 87            <artifactId>mpConfig-1.3</artifactId>
 88            <type>esa</type>
 89            <scope>provided</scope>
 90        </dependency>
 91        <dependency>
 92            <groupId>io.openliberty.features</groupId>
 93            <artifactId>mpRestClient-1.3</artifactId>
 94            <type>esa</type>
 95            <scope>provided</scope>
 96        </dependency>
 97        <!-- Java utility classes -->
 98        <dependency>
 99            <groupId>org.apache.commons</groupId>
100            <artifactId>commons-lang3</artifactId>
101            <version>3.0</version>
102        </dependency>
103        <!-- Support for JDK 9 and above -->
104        <dependency>
105            <groupId>javax.xml.bind</groupId>
106            <artifactId>jaxb-api</artifactId>
107            <version>2.3.1</version>
108            <scope>test</scope>
109        </dependency>
110        <dependency>
111            <groupId>com.sun.xml.bind</groupId>
112            <artifactId>jaxb-core</artifactId>
113            <version>2.3.0.1</version>
114            <scope>test</scope>
115        </dependency>
116        <dependency>
117            <groupId>com.sun.xml.bind</groupId>
118            <artifactId>jaxb-impl</artifactId>
119            <version>2.3.2</version>
120            <scope>test</scope>
121        </dependency>
122        <dependency>
123            <groupId>javax.activation</groupId>
124            <artifactId>activation</artifactId>
125            <version>1.1.1</version>
126            <scope>test</scope>
127        </dependency>
128    </dependencies>
129
130    <build>
131        <plugins>
132            <plugin>
133                <groupId>org.apache.maven.plugins</groupId>
134                <artifactId>maven-war-plugin</artifactId>
135                <version>3.2.2</version>
136                <configuration>
137                    <failOnMissingWebXml>false</failOnMissingWebXml>
138                    <packagingExcludes>pom.xml</packagingExcludes>
139                </configuration>
140            </plugin>
141            <!-- Plugin to run unit tests -->
142            <plugin>
143                <groupId>org.apache.maven.plugins</groupId>
144                <artifactId>maven-surefire-plugin</artifactId>
145                <version>3.0.0-M1</version>
146                <executions>
147                    <execution>
148                        <phase>test</phase>
149                        <id>default-test</id>
150                        <configuration>
151                            <excludes>
152                                <exclude>**/it/**</exclude>
153                            </excludes>
154                            <reportsDirectory>${project.build.directory}/test-reports/unit
155                            </reportsDirectory>
156                        </configuration>
157                    </execution>
158                </executions>
159            </plugin>
160            <!-- Enable liberty-maven plugin -->
161            <plugin>
162                <groupId>net.wasdev.wlp.maven.plugins</groupId>
163                <artifactId>liberty-maven-plugin</artifactId>
164                <configuration>
165                    <assemblyArtifact>
166                        <groupId>io.openliberty</groupId>
167                        <artifactId>openliberty-runtime</artifactId>
168                        <version>RELEASE</version>
169                        <type>zip</type>
170                    </assemblyArtifact>
171                    <configFile>src/main/liberty/config/server.xml</configFile>
172                    <packageFile>${package.file}</packageFile>
173                    <include>${packaging.type}</include>
174                    <bootstrapProperties>
175                        <default.http.port>${testServerHttpPort}</default.http.port>
176                        <default.https.port>${testServerHttpsPort}</default.https.port>
177                    </bootstrapProperties>
178                </configuration>
179                <executions>
180                    <execution>
181                        <id>install-apps</id>
182                        <configuration>
183                            <looseApplication>true</looseApplication>
184                            <stripVersion>true</stripVersion>
185                            <installAppPackages>project</installAppPackages>
186                        </configuration>
187                    </execution>
188                    <execution>
189                        <id>package-app</id>
190                        <configuration>
191                            <outputDirectory>target/wlp-package</outputDirectory>
192                        </configuration>
193                    </execution>
194                </executions>
195            </plugin>
196            <!-- Plugin to run functional tests -->
197            <plugin>
198                <groupId>org.apache.maven.plugins</groupId>
199                <artifactId>maven-failsafe-plugin</artifactId>
200                <version>3.0.0-M1</version>
201                <executions>
202                    <execution>
203                        <phase>integration-test</phase>
204                        <id>integration-test</id>
205                        <goals>
206                            <goal>integration-test</goal>
207                        </goals>
208                        <configuration>
209                            <includes>
210                                <include>**/it/**/*.java</include>
211                            </includes>
212                            <systemPropertyVariables>
213                                             <liberty.test.port>${testServerHttpPort}
214                                 </liberty.test.port>
215                            </systemPropertyVariables>
216                            <runOrder>reversealphabetical</runOrder>
217                        </configuration>
218                    </execution>
219                    <execution>
220                        <id>verify-results</id>
221                        <goals>
222                            <goal>verify</goal>
223                        </goals>
224                    </execution>
225                </executions>
226                <configuration>
227                    <summaryFile>
228                    ${project.build.directory}/test-reports/it/failsafe-summary.xml
229                    </summaryFile>
230                    <reportsDirectory>${project.build.directory}/test-reports/it
231                    </reportsDirectory>
232                </configuration>
233            </plugin>
234        </plugins>
235    </build>
236</project>

This dependency provides the 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    <feature>mpConfig-1.3</feature>
 8    <feature>mpRestClient-1.3</feature>
 9  </featureManager>
10
11  <httpEndpoint host="*" httpPort="${default.http.port}" httpsPort="${default.https.port}"
12                id="defaultHttpEndpoint"/>
13
14  <webApplication location="microprofile-rest-client.war" contextRoot="/"/>
15</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 detail.

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

 1package io.openliberty.guides.inventory.client;
 2
 3public class UnknownUriException extends Exception {
 4
 5  private static final long serialVersionUID = 1L;
 6
 7  public UnknownUriException() {
 8    super();
 9  }
10
11  public UnknownUriException(String message) {
12    super(message);
13  }
14}

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

 1package io.openliberty.guides.inventory.client;
 2
 3import java.util.logging.Logger;
 4import javax.ws.rs.core.MultivaluedMap;
 5import javax.ws.rs.core.Response;
 6import javax.ws.rs.ext.Provider;
 7import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
 8
 9@Provider
10public class UnknownUriExceptionMapper
11    implements ResponseExceptionMapper<UnknownUriException> {
12  Logger LOG = Logger.getLogger(UnknownUriExceptionMapper.class.getName());
13
14  @Override
15  public boolean handles(int status, MultivaluedMap<String, Object> headers) {
16    LOG.info("status = " + status);
17    return status == 404;
18  }
19
20  @Override
21  public UnknownUriException toThrowable(Response response) {
22    return new UnknownUriException();
23  }
24}

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 both server.xml and pom.xml files.

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. For this guide, try to specify an invalid URI value for the baseUri variable and comment out the mp-rest/uri property in the microprofile-config.properties file. Then, run the mvn install command to verify that the InventoryEndpointTest fails to connect to the system service.

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.

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

InventoryManager.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 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::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;
 31
 32import io.openliberty.guides.inventory.client.SystemClient;
 33import io.openliberty.guides.inventory.client.UnknownUriException;
 34import io.openliberty.guides.inventory.client.UnknownUriExceptionMapper;
 35import io.openliberty.guides.inventory.model.InventoryList;
 36import io.openliberty.guides.inventory.model.SystemData;
 37
 38// tag::ApplicationScoped[]
 39@ApplicationScoped
 40// end::ApplicationScoped[]
 41public class InventoryManager {
 42
 43  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 44  private final String DEFAULT_PORT = System.getProperty("default.http.port");
 45
 46  // tag::Inject[]
 47  @Inject
 48  // end::Inject[]
 49  // tag::RestClient[]
 50  @RestClient
 51  // end::RestClient[]
 52  // tag::SystemClient[]
 53  private SystemClient defaultRestClient;
 54  // end::SystemClient[]
 55
 56  public Properties get(String hostname) {
 57    Properties properties = null;
 58    if (hostname.equals("localhost")) {
 59      properties = getPropertiesWithDefaultHostName();
 60    } else {
 61      properties = getPropertiesWithGivenHostName(hostname);
 62    }
 63
 64    return properties;
 65  }
 66
 67  public void add(String hostname, Properties systemProps) {
 68    Properties props = new Properties();
 69    props.setProperty("os.name", systemProps.getProperty("os.name"));
 70    props.setProperty("user.name", systemProps.getProperty("user.name"));
 71
 72    SystemData host = new SystemData(hostname, props);
 73    if (!systems.contains(host))
 74      systems.add(host);
 75  }
 76
 77  public InventoryList list() {
 78    return new InventoryList(systems);
 79  }
 80
 81  // tag::getPropertiesWithDefaultHostName[]
 82  private Properties getPropertiesWithDefaultHostName() {
 83    try {
 84      // tag::defaultRCGetProperties[]
 85      return defaultRestClient.getProperties();
 86      // end::defaultRCGetProperties[]
 87    } catch (UnknownUriException e) {
 88      System.err.println("The given URI is not formatted correctly.");
 89    } catch (ProcessingException ex) {
 90      handleProcessingException(ex);
 91    }
 92    return null;
 93  }
 94  // end::getPropertiesWithDefaultHostName[]
 95
 96  // tag::getPropertiesWithGivenHostName[]
 97  private Properties getPropertiesWithGivenHostName(String hostname) {
 98    String customURIString = "http://" + hostname + ":" + DEFAULT_PORT + "/system";
 99    URI customURI = null;
100    try {
101      customURI = URI.create(customURIString);
102      // tag::customRestClientBuilder[]
103      SystemClient customRestClient = RestClientBuilder.newBuilder()
104                                          .baseUri(customURI)
105                                          .register(UnknownUriExceptionMapper.class)
106                                          .build(SystemClient.class);
107      // end::customRestClientBuilder[]
108      // tag::customRCGetProperties[]
109      return customRestClient.getProperties();
110      // end::customRCGetProperties[]
111    } catch (ProcessingException ex) {
112      handleProcessingException(ex);
113    } catch (UnknownUriException e) {
114      System.err.println("The given URI is unreachable.");
115    }
116    return null;
117  }
118  // end::getPropertiesWithGivenHostName[]
119
120  private void handleProcessingException(ProcessingException ex) {
121    Throwable rootEx = ExceptionUtils.getRootCause(ex);
122    if (rootEx != null && (rootEx instanceof UnknownHostException
123        || rootEx instanceof ConnectException)) {
124      System.err.println("The specified host is unknown.");
125    } else {
126      throw ex;
127    }
128  }
129
130}
131// 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.

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, 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::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;
 31
 32import io.openliberty.guides.inventory.client.SystemClient;
 33import io.openliberty.guides.inventory.client.UnknownUriException;
 34import io.openliberty.guides.inventory.client.UnknownUriExceptionMapper;
 35import io.openliberty.guides.inventory.model.InventoryList;
 36import io.openliberty.guides.inventory.model.SystemData;
 37
 38// tag::ApplicationScoped[]
 39@ApplicationScoped
 40// end::ApplicationScoped[]
 41public class InventoryManager {
 42
 43  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
 44  private final String DEFAULT_PORT = System.getProperty("default.http.port");
 45
 46  // tag::Inject[]
 47  @Inject
 48  // end::Inject[]
 49  // tag::RestClient[]
 50  @RestClient
 51  // end::RestClient[]
 52  // tag::SystemClient[]
 53  private SystemClient defaultRestClient;
 54  // end::SystemClient[]
 55
 56  public Properties get(String hostname) {
 57    Properties properties = null;
 58    if (hostname.equals("localhost")) {
 59      properties = getPropertiesWithDefaultHostName();
 60    } else {
 61      properties = getPropertiesWithGivenHostName(hostname);
 62    }
 63
 64    return properties;
 65  }
 66
 67  public void add(String hostname, Properties systemProps) {
 68    Properties props = new Properties();
 69    props.setProperty("os.name", systemProps.getProperty("os.name"));
 70    props.setProperty("user.name", systemProps.getProperty("user.name"));
 71
 72    SystemData host = new SystemData(hostname, props);
 73    if (!systems.contains(host))
 74      systems.add(host);
 75  }
 76
 77  public InventoryList list() {
 78    return new InventoryList(systems);
 79  }
 80
 81  // tag::getPropertiesWithDefaultHostName[]
 82  private Properties getPropertiesWithDefaultHostName() {
 83    try {
 84      // tag::defaultRCGetProperties[]
 85      return defaultRestClient.getProperties();
 86      // end::defaultRCGetProperties[]
 87    } catch (UnknownUriException e) {
 88      System.err.println("The given URI is not formatted correctly.");
 89    } catch (ProcessingException ex) {
 90      handleProcessingException(ex);
 91    }
 92    return null;
 93  }
 94  // end::getPropertiesWithDefaultHostName[]
 95
 96  // tag::getPropertiesWithGivenHostName[]
 97  private Properties getPropertiesWithGivenHostName(String hostname) {
 98    String customURIString = "http://" + hostname + ":" + DEFAULT_PORT + "/system";
 99    URI customURI = null;
100    try {
101      customURI = URI.create(customURIString);
102      // tag::customRestClientBuilder[]
103      SystemClient customRestClient = RestClientBuilder.newBuilder()
104                                          .baseUri(customURI)
105                                          .register(UnknownUriExceptionMapper.class)
106                                          .build(SystemClient.class);
107      // end::customRestClientBuilder[]
108      // tag::customRCGetProperties[]
109      return customRestClient.getProperties();
110      // end::customRCGetProperties[]
111    } catch (ProcessingException ex) {
112      handleProcessingException(ex);
113    } catch (UnknownUriException e) {
114      System.err.println("The given URI is unreachable.");
115    }
116    return null;
117  }
118  // end::getPropertiesWithGivenHostName[]
119
120  private void handleProcessingException(ProcessingException ex) {
121    Throwable rootEx = ExceptionUtils.getRootCause(ex);
122    if (rootEx != null && (rootEx instanceof UnknownHostException
123        || rootEx instanceof ConnectException)) {
124      System.err.println("The specified host is unknown.");
125    } else {
126      throw ex;
127    }
128  }
129
130}
131// 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.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

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.

If you make changes to the code, use the Maven compile goal to rebuild the application and have the running Open Liberty server pick them up automatically:

mvn compile

To stop the Open Liberty server, run the Maven liberty:stop-server goal:

mvn liberty:stop-server

Testing the application

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

RestClientTest.java

 1package it.io.openliberty.guides.client;
 2
 3import static org.junit.Assert.assertEquals;
 4import javax.json.JsonObject;
 5import javax.ws.rs.client.Client;
 6import javax.ws.rs.client.ClientBuilder;
 7import javax.ws.rs.core.Response;
 8import javax.ws.rs.client.WebTarget;
 9import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
10import org.junit.After;
11import org.junit.Before;
12import org.junit.BeforeClass;
13import org.junit.Test;
14import java.net.InetAddress;
15import java.net.UnknownHostException;
16
17public class RestClientTest {
18
19  private static String port;
20
21  private Client client;
22
23  private final String INVENTORY_SYSTEMS = "inventory/systems";
24
25  @BeforeClass
26  public static void oneTimeSetup() {
27    port = System.getProperty("liberty.test.port");
28  }
29
30  @Before
31  public void setup() {
32    client = ClientBuilder.newClient();
33    client.register(JsrJsonpProvider.class);
34  }
35
36  @After
37  public void teardown() {
38    client.close();
39  }
40
41  @Test
42  public void testSuite() {
43    this.testDefaultLocalhost();
44    this.testRestClientBuilder();
45  }
46
47  public void testDefaultLocalhost() {
48    String hostname = "localhost";
49
50    String url = "http://localhost:" + port + "/" + INVENTORY_SYSTEMS + "/" + hostname;
51
52    JsonObject obj = fetchProperties(url);
53
54    assertEquals("The system property for the local and remote JVM should match",
55                 System.getProperty("os.name"),
56                 obj.getString("os.name"));
57  }
58
59  public void testRestClientBuilder() {
60    String hostname = null;
61    try{
62      hostname = InetAddress.getLocalHost().getHostAddress();
63    } catch (UnknownHostException e) {
64      System.err.println("Unknown Host.");
65    }
66
67    String url = "http://localhost:" + port + "/" + INVENTORY_SYSTEMS + "/" + hostname;
68
69    JsonObject obj = fetchProperties(url);
70
71    assertEquals("The system property for the local and remote JVM should match",
72                 System.getProperty("os.name"),
73                 obj.getString("os.name"));
74  }
75
76  private JsonObject fetchProperties(String url) {
77    WebTarget target = client.target(url);
78    Response response = target.request().get();
79
80    assertEquals("Incorrect response code from " + url, 200, response.getStatus());
81
82    JsonObject obj = response.readEntity(JsonObject.class);
83    response.close();
84    return obj;
85  }
86
87}

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

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

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

Results :

Tests run: 3, 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 Maven build. You see a test failure occur.

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