Consuming a RESTful web service

duration 25 minutes

Prerequisites:

Explore how to access a simple RESTful web service and consume its resources in Java using JSON-B and JSON-P.

What you’ll learn

artists.json

 1[
 2    {
 3        "name" : "foo",
 4        "albums" : [
 5            {
 6                "title" : "album_one",
 7                "artist" : "foo",
 8                "ntracks" : 12
 9            },
10            {
11                "title" : "album_two",
12                "artist" : "foo",
13                "ntracks" : 15
14            }
15        ]
16    }, 
17    {
18        "name" : "bar",
19        "albums" : [
20            {
21                "title" : "foo walks into a bar",
22                "artist" : "bar",
23                "ntracks" : 12
24            }
25        ]
26    }, 
27    {
28        "name" : "dj",
29        "albums" : [
30        ]
31    }
32]

You will learn how to access a REST service, serialize a Java object that contains a list of artists and their albums, and use two different approaches to deserialize the returned JSON resources. The first approach consists of using the Java API for JSON Binding (JSON-B) to directly convert JSON messages into Java objects. The second approach consists of using the Java API for JSON Processing (JSON-P) to process the JSON.

The REST service that provides the artists and albums resources is already written for you. When the Liberty is running, this service is accessible at the http://localhost:9080/artists endpoint, which responds with the artists.json file.

You will implement the following two endpoints using the two deserialization approaches:

  • …​/artists/total to return the total number of artists in the JSON

  • …​/artists/total/<artist> to return the total number of albums in the JSON for the particular artist

If you are interested in learning more about REST services and how you can write them, read Creating a RESTful web service.

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-rest-client-java.git
cd guide-rest-client-java

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

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

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

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 Liberty instance is ready:

The defaultServer server is ready to run a smarter planet.

You can find your service at the http://localhost:9080/artists endpoint.

Now, you can access the endpoint at http://localhost:9080/artists/total to see the total number of artists, and you can access the endpoint at http://localhost:9080/artists/total/<artist> to see a particular artist’s total number of albums.

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

mvn liberty:stop

Starting the service

Navigate to the start directory to begin.

When you run Open Liberty in dev mode, dev mode 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 Liberty instance is ready in dev mode:

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

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 application that you’ll build upon was created for you. After your Liberty instance is ready, you can access the service at the http://localhost:9080/artists URL.

Creating POJOs

Artist.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.model;
13
14import jakarta.json.bind.annotation.JsonbCreator;
15import jakarta.json.bind.annotation.JsonbProperty;
16import jakarta.json.bind.annotation.JsonbTransient;
17
18// tag::Artist[]
19public class Artist {
20    // tag::name[]
21    public String name;
22    // end::name[]
23    // tag::Albums[]
24    public Album[] albums;
25    // end::Albums[]
26    // Object property that does not map to a JSON
27    // tag::JsonbTransient[]
28    @JsonbTransient
29    // end::JsonbTransient[]
30    public boolean legendary = true;
31
32    public Artist() {
33
34    }
35
36    // tag::JsonbCreator[]
37    @JsonbCreator
38    // end::JsonbCreator[]
39    public Artist(
40      // tag::JsonbProperty[]
41      @JsonbProperty("name") String name,
42      @JsonbProperty("albums") Album[] albums) {
43      // end::JsonbProperty[]
44
45      this.name = name;
46      this.albums = albums;
47    }
48
49    @Override
50    public String toString() {
51      return name + " wrote " + albums.length + " albums";
52    }
53}
54// end::Artist[]

Album.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.model;
13
14import jakarta.json.bind.annotation.JsonbCreator;
15import jakarta.json.bind.annotation.JsonbProperty;
16
17// tag::Album[]
18public class Album {
19    // tag::title[]
20    public String title;
21    // end::title[]
22
23    @JsonbProperty("artist")
24    // tag::artistName[]
25    public String artistName;
26    // end::artistName[]
27
28    @JsonbProperty("ntracks")
29    // tag::totalTracks[]
30    public int totalTracks;
31    // end::totalTracks[]
32
33    public Album() {
34    }
35
36    @JsonbCreator
37    public Album(
38      @JsonbProperty("title") String title,
39      @JsonbProperty("artist") String artistName,
40      @JsonbProperty("ntracks") int totalTracks) {
41
42      this.title = title;
43      this.artistName = artistName;
44      this.totalTracks = totalTracks;
45    }
46
47    @Override
48    public String toString() {
49      return "Album titled " + title + " by " + artistName
50                             + " contains " + totalTracks + " tracks";
51    }
52}
53// end::Album[]

To deserialize a JSON message, start with creating Plain Old Java Objects (POJOs) that represent what is in the JSON and whose instance members map to the keys in the JSON.

For the purpose of this guide, you are given two POJOs. The Artist object has two instance members name and albums, which map to the artist name and the collection of the albums they have written. The Album object represents a single object within the album collection, and contains three instance members title, artistName, and totalTracks, which map to the album title, the artist who wrote the album, and the number of tracks the album contains.

Introducing JSON-B and JSON-P

JSON-B is a feature introduced with Java EE 8 and strengthens Java support for JSON. With JSON-B you directly serialize and deserialize POJOs. This API gives you a variety of options for working with JSON resources.

In contrast, you need to use helper methods with JSON-P to process a JSON response. This tactic is more straightforward, but it can be cumbersome with more complex classes.

JSON-B is built on top of the existing JSON-P API. JSON-B can do everything that JSON-P can do and allows for more customization for serializing and deserializing.

Using JSON-B

Artist.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.model;
13
14import jakarta.json.bind.annotation.JsonbCreator;
15import jakarta.json.bind.annotation.JsonbProperty;
16import jakarta.json.bind.annotation.JsonbTransient;
17
18// tag::Artist[]
19public class Artist {
20    // tag::name[]
21    public String name;
22    // end::name[]
23    // tag::Albums[]
24    public Album[] albums;
25    // end::Albums[]
26    // Object property that does not map to a JSON
27    // tag::JsonbTransient[]
28    @JsonbTransient
29    // end::JsonbTransient[]
30    public boolean legendary = true;
31
32    public Artist() {
33
34    }
35
36    // tag::JsonbCreator[]
37    @JsonbCreator
38    // end::JsonbCreator[]
39    public Artist(
40      // tag::JsonbProperty[]
41      @JsonbProperty("name") String name,
42      @JsonbProperty("albums") Album[] albums) {
43      // end::JsonbProperty[]
44
45      this.name = name;
46      this.albums = albums;
47    }
48
49    @Override
50    public String toString() {
51      return name + " wrote " + albums.length + " albums";
52    }
53}
54// end::Artist[]

JSON-B requires a POJO to have a public default no-argument constructor for deserialization and binding to work properly.

The JSON-B engine includes a set of default mapping rules, which can be run without any customization annotations or custom configuration. In some instances, you might find it useful to deserialize a JSON message with only certain fields, specific field names, or classes with custom constructors. In these cases, annotations are necessary and recommended:

  • The @JsonbProperty annotation to map JSON keys to class instance members and vice versa. Without the use of this annotation, JSON-B will attempt to do POJO mapping, matching the keys in the JSON to the class instance members by name. JSON-B will attempt to match the JSON key with a Java field or method annotated with @JsonbProperty where the value in the annotation exactly matches the JSON key. If no annotation exists with the given JSON key, JSON-B will attempt to find a matching field with the same name. If no match is found, JSON-B attempts to find a matching getter method for serialization or a matching setter method for de-serialization. A match occurs when the property name of the method matches the JSON key. If no matching getter or setter method is found, serialization or de-serialization, respectively, fails with an exception. The Artist POJO does not require this annotation because all instance members match the JSON keys by name.

  • The @JsonbCreator and @JsonbProperty annotations to annotate a custom constructor. These annotations are required for proper parameter substitution when a custom constructor is used.

  • The @JsonbTransient annotation to define an object property that does not map to a JSON property. While the use of this annotation is good practice, it is only necessary for serialization.

For more information on customization with JSON-B, see the official JSON-B site.

Consuming the REST resource

Artist.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.model;
13
14import jakarta.json.bind.annotation.JsonbCreator;
15import jakarta.json.bind.annotation.JsonbProperty;
16import jakarta.json.bind.annotation.JsonbTransient;
17
18// tag::Artist[]
19public class Artist {
20    // tag::name[]
21    public String name;
22    // end::name[]
23    // tag::Albums[]
24    public Album[] albums;
25    // end::Albums[]
26    // Object property that does not map to a JSON
27    // tag::JsonbTransient[]
28    @JsonbTransient
29    // end::JsonbTransient[]
30    public boolean legendary = true;
31
32    public Artist() {
33
34    }
35
36    // tag::JsonbCreator[]
37    @JsonbCreator
38    // end::JsonbCreator[]
39    public Artist(
40      // tag::JsonbProperty[]
41      @JsonbProperty("name") String name,
42      @JsonbProperty("albums") Album[] albums) {
43      // end::JsonbProperty[]
44
45      this.name = name;
46      this.albums = albums;
47    }
48
49    @Override
50    public String toString() {
51      return name + " wrote " + albums.length + " albums";
52    }
53}
54// end::Artist[]

Album.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.model;
13
14import jakarta.json.bind.annotation.JsonbCreator;
15import jakarta.json.bind.annotation.JsonbProperty;
16
17// tag::Album[]
18public class Album {
19    // tag::title[]
20    public String title;
21    // end::title[]
22
23    @JsonbProperty("artist")
24    // tag::artistName[]
25    public String artistName;
26    // end::artistName[]
27
28    @JsonbProperty("ntracks")
29    // tag::totalTracks[]
30    public int totalTracks;
31    // end::totalTracks[]
32
33    public Album() {
34    }
35
36    @JsonbCreator
37    public Album(
38      @JsonbProperty("title") String title,
39      @JsonbProperty("artist") String artistName,
40      @JsonbProperty("ntracks") int totalTracks) {
41
42      this.title = title;
43      this.artistName = artistName;
44      this.totalTracks = totalTracks;
45    }
46
47    @Override
48    public String toString() {
49      return "Album titled " + title + " by " + artistName
50                             + " contains " + totalTracks + " tracks";
51    }
52}
53// end::Album[]

The Artist and Album POJOs are ready for deserialization. Next, we’ll learn to consume the JSON response from your REST service.

Create the Consumer class.
src/main/java/io/openliberty/guides/consumingrest/Consumer.java

Consumer.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest;
13
14import java.util.List;
15import java.util.stream.Collectors;
16
17import jakarta.json.JsonArray;
18import jakarta.json.JsonObject;
19import jakarta.ws.rs.client.Client;
20import jakarta.ws.rs.client.ClientBuilder;
21import jakarta.ws.rs.core.Response;
22
23import io.openliberty.guides.consumingrest.model.Album;
24import io.openliberty.guides.consumingrest.model.Artist;
25
26// tag::Consumer[]
27public class Consumer {
28    // tag::consumeWithJsonb[]
29    public static Artist[] consumeWithJsonb(String targetUrl) {
30      Client client = ClientBuilder.newClient();
31      // tag::get-1[]
32      Response response = client.target(targetUrl).request().get();
33      // end::get-1[]
34      // tag::readEntity[]
35      Artist[] artists = response.readEntity(Artist[].class);
36      // end::readEntity[]
37
38      response.close();
39      client.close();
40
41      return artists;
42    }
43    // end::consumeWithJsonb[]
44
45    // tag::consumeWithJsonp[]
46    public static Artist[] consumeWithJsonp(String targetUrl) {
47      Client client = ClientBuilder.newClient();
48      // tag::get-2[]
49      Response response = client.target(targetUrl).request().get();
50      // end::get-2[]
51      JsonArray arr = response.readEntity(JsonArray.class);
52
53      response.close();
54      client.close();
55
56      return Consumer.collectArtists(arr);
57    }
58    // end::consumeWithJsonp[]
59
60    // tag::collectArtists[]
61    private static Artist[] collectArtists(JsonArray artistArr) {
62      List<Artist> artists = artistArr.stream().map(artistJson -> {
63        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
64        Artist artist = new Artist(
65          ((JsonObject) artistJson).getString("name"),
66          Consumer.collectAlbums(albumArr));
67        return artist;
68      }).collect(Collectors.toList());
69
70      return artists.toArray(new Artist[artists.size()]);
71    }
72    // end::collectArtists[]
73
74    // tag::collectAlbums[]
75    private static Album[] collectAlbums(JsonArray albumArr) {
76      List<Album> albums = albumArr.stream().map(albumJson -> {
77        Album album = new Album(
78          ((JsonObject) albumJson).getString("title"),
79          ((JsonObject) albumJson).getString("artist"),
80          ((JsonObject) albumJson).getInt("ntracks"));
81        return album;
82      }).collect(Collectors.toList());
83
84      return albums.toArray(new Album[albums.size()]);
85    }
86    // end::collectAlbums[]
87}
88// end::Consumer[]

Processing JSON using JSON-B

Consumer.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest;
13
14import java.util.List;
15import java.util.stream.Collectors;
16
17import jakarta.json.JsonArray;
18import jakarta.json.JsonObject;
19import jakarta.ws.rs.client.Client;
20import jakarta.ws.rs.client.ClientBuilder;
21import jakarta.ws.rs.core.Response;
22
23import io.openliberty.guides.consumingrest.model.Album;
24import io.openliberty.guides.consumingrest.model.Artist;
25
26// tag::Consumer[]
27public class Consumer {
28    // tag::consumeWithJsonb[]
29    public static Artist[] consumeWithJsonb(String targetUrl) {
30      Client client = ClientBuilder.newClient();
31      // tag::get-1[]
32      Response response = client.target(targetUrl).request().get();
33      // end::get-1[]
34      // tag::readEntity[]
35      Artist[] artists = response.readEntity(Artist[].class);
36      // end::readEntity[]
37
38      response.close();
39      client.close();
40
41      return artists;
42    }
43    // end::consumeWithJsonb[]
44
45    // tag::consumeWithJsonp[]
46    public static Artist[] consumeWithJsonp(String targetUrl) {
47      Client client = ClientBuilder.newClient();
48      // tag::get-2[]
49      Response response = client.target(targetUrl).request().get();
50      // end::get-2[]
51      JsonArray arr = response.readEntity(JsonArray.class);
52
53      response.close();
54      client.close();
55
56      return Consumer.collectArtists(arr);
57    }
58    // end::consumeWithJsonp[]
59
60    // tag::collectArtists[]
61    private static Artist[] collectArtists(JsonArray artistArr) {
62      List<Artist> artists = artistArr.stream().map(artistJson -> {
63        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
64        Artist artist = new Artist(
65          ((JsonObject) artistJson).getString("name"),
66          Consumer.collectAlbums(albumArr));
67        return artist;
68      }).collect(Collectors.toList());
69
70      return artists.toArray(new Artist[artists.size()]);
71    }
72    // end::collectArtists[]
73
74    // tag::collectAlbums[]
75    private static Album[] collectAlbums(JsonArray albumArr) {
76      List<Album> albums = albumArr.stream().map(albumJson -> {
77        Album album = new Album(
78          ((JsonObject) albumJson).getString("title"),
79          ((JsonObject) albumJson).getString("artist"),
80          ((JsonObject) albumJson).getInt("ntracks"));
81        return album;
82      }).collect(Collectors.toList());
83
84      return albums.toArray(new Album[albums.size()]);
85    }
86    // end::collectAlbums[]
87}
88// end::Consumer[]

pom.xml

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

JSON-B is a Java API that is used to serialize Java objects to JSON messages and vice versa.

Open Liberty’s JSON-B feature on Maven Central includes the JSON-B provider through transitive dependencies. The JSON-B APIs are provided by the MicroProfile dependency in your pom.xml file. Look for the dependency with the microprofile artifact ID.

The consumeWithJsonb() method in the Consumer class makes a GET request to the running artist service and retrieves the JSON. To bind the JSON into an Artist array, use the Artist[] entity type in the readEntity call.

Processing JSON using JSON-P

Consumer.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest;
13
14import java.util.List;
15import java.util.stream.Collectors;
16
17import jakarta.json.JsonArray;
18import jakarta.json.JsonObject;
19import jakarta.ws.rs.client.Client;
20import jakarta.ws.rs.client.ClientBuilder;
21import jakarta.ws.rs.core.Response;
22
23import io.openliberty.guides.consumingrest.model.Album;
24import io.openliberty.guides.consumingrest.model.Artist;
25
26// tag::Consumer[]
27public class Consumer {
28    // tag::consumeWithJsonb[]
29    public static Artist[] consumeWithJsonb(String targetUrl) {
30      Client client = ClientBuilder.newClient();
31      // tag::get-1[]
32      Response response = client.target(targetUrl).request().get();
33      // end::get-1[]
34      // tag::readEntity[]
35      Artist[] artists = response.readEntity(Artist[].class);
36      // end::readEntity[]
37
38      response.close();
39      client.close();
40
41      return artists;
42    }
43    // end::consumeWithJsonb[]
44
45    // tag::consumeWithJsonp[]
46    public static Artist[] consumeWithJsonp(String targetUrl) {
47      Client client = ClientBuilder.newClient();
48      // tag::get-2[]
49      Response response = client.target(targetUrl).request().get();
50      // end::get-2[]
51      JsonArray arr = response.readEntity(JsonArray.class);
52
53      response.close();
54      client.close();
55
56      return Consumer.collectArtists(arr);
57    }
58    // end::consumeWithJsonp[]
59
60    // tag::collectArtists[]
61    private static Artist[] collectArtists(JsonArray artistArr) {
62      List<Artist> artists = artistArr.stream().map(artistJson -> {
63        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
64        Artist artist = new Artist(
65          ((JsonObject) artistJson).getString("name"),
66          Consumer.collectAlbums(albumArr));
67        return artist;
68      }).collect(Collectors.toList());
69
70      return artists.toArray(new Artist[artists.size()]);
71    }
72    // end::collectArtists[]
73
74    // tag::collectAlbums[]
75    private static Album[] collectAlbums(JsonArray albumArr) {
76      List<Album> albums = albumArr.stream().map(albumJson -> {
77        Album album = new Album(
78          ((JsonObject) albumJson).getString("title"),
79          ((JsonObject) albumJson).getString("artist"),
80          ((JsonObject) albumJson).getInt("ntracks"));
81        return album;
82      }).collect(Collectors.toList());
83
84      return albums.toArray(new Album[albums.size()]);
85    }
86    // end::collectAlbums[]
87}
88// end::Consumer[]

The consumeWithJsonp() method in the Consumer class makes a GET request to the running artist service and retrieves the JSON. This method then uses the collectArtists and collectAlbums helper methods. These helper methods will parse the JSON and collect its objects into individual POJOs. Notice that you can use the custom constructors to create instances of Artist and Album.

Creating additional REST resources

Consumer.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest;
13
14import java.util.List;
15import java.util.stream.Collectors;
16
17import jakarta.json.JsonArray;
18import jakarta.json.JsonObject;
19import jakarta.ws.rs.client.Client;
20import jakarta.ws.rs.client.ClientBuilder;
21import jakarta.ws.rs.core.Response;
22
23import io.openliberty.guides.consumingrest.model.Album;
24import io.openliberty.guides.consumingrest.model.Artist;
25
26// tag::Consumer[]
27public class Consumer {
28    // tag::consumeWithJsonb[]
29    public static Artist[] consumeWithJsonb(String targetUrl) {
30      Client client = ClientBuilder.newClient();
31      // tag::get-1[]
32      Response response = client.target(targetUrl).request().get();
33      // end::get-1[]
34      // tag::readEntity[]
35      Artist[] artists = response.readEntity(Artist[].class);
36      // end::readEntity[]
37
38      response.close();
39      client.close();
40
41      return artists;
42    }
43    // end::consumeWithJsonb[]
44
45    // tag::consumeWithJsonp[]
46    public static Artist[] consumeWithJsonp(String targetUrl) {
47      Client client = ClientBuilder.newClient();
48      // tag::get-2[]
49      Response response = client.target(targetUrl).request().get();
50      // end::get-2[]
51      JsonArray arr = response.readEntity(JsonArray.class);
52
53      response.close();
54      client.close();
55
56      return Consumer.collectArtists(arr);
57    }
58    // end::consumeWithJsonp[]
59
60    // tag::collectArtists[]
61    private static Artist[] collectArtists(JsonArray artistArr) {
62      List<Artist> artists = artistArr.stream().map(artistJson -> {
63        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
64        Artist artist = new Artist(
65          ((JsonObject) artistJson).getString("name"),
66          Consumer.collectAlbums(albumArr));
67        return artist;
68      }).collect(Collectors.toList());
69
70      return artists.toArray(new Artist[artists.size()]);
71    }
72    // end::collectArtists[]
73
74    // tag::collectAlbums[]
75    private static Album[] collectAlbums(JsonArray albumArr) {
76      List<Album> albums = albumArr.stream().map(albumJson -> {
77        Album album = new Album(
78          ((JsonObject) albumJson).getString("title"),
79          ((JsonObject) albumJson).getString("artist"),
80          ((JsonObject) albumJson).getInt("ntracks"));
81        return album;
82      }).collect(Collectors.toList());
83
84      return albums.toArray(new Album[albums.size()]);
85    }
86    // end::collectAlbums[]
87}
88// end::Consumer[]

Now that you can consume a JSON resource you can put that data to use.

Replace the ArtistResource class.
src/main/java/io/openliberty/guides/consumingrest/service/ArtistResource.java

ArtistResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.consumingrest.service;
13
14import jakarta.json.JsonArray;
15import jakarta.json.bind.Jsonb;
16import jakarta.json.bind.JsonbBuilder;
17import jakarta.ws.rs.GET;
18import jakarta.ws.rs.Path;
19import jakarta.ws.rs.PathParam;
20import jakarta.ws.rs.Produces;
21import jakarta.ws.rs.core.Context;
22import jakarta.ws.rs.core.MediaType;
23import jakarta.ws.rs.core.UriInfo;
24
25import io.openliberty.guides.consumingrest.model.Artist;
26import io.openliberty.guides.consumingrest.Consumer;
27
28@Path("artists")
29// tag::ArtistResource[]
30public class ArtistResource {
31
32    @Context
33    UriInfo uriInfo;
34
35    @GET
36    @Produces(MediaType.APPLICATION_JSON)
37    // tag::getArtists[]
38    public JsonArray getArtists() {
39      return Reader.getArtists();
40    }
41    // end::getArtists[]
42
43    @GET
44    @Path("jsonString")
45    @Produces(MediaType.TEXT_PLAIN)
46    // tag::getJsonString[]
47    public String getJsonString() {
48      Jsonb jsonb = JsonbBuilder.create();
49
50      Artist[] artists = Consumer.consumeWithJsonb(uriInfo.getBaseUri().toString()
51                                                   + "artists");
52      String result = jsonb.toJson(artists);
53
54      return result;
55    }
56    // end::getJsonString[]
57
58    @GET
59    @Path("total/{artist}")
60    @Produces(MediaType.TEXT_PLAIN)
61    // tag::getTotalAlbums[]
62    public int getTotalAlbums(@PathParam("artist") String artist) {
63      Artist[] artists = Consumer.consumeWithJsonb(uriInfo.getBaseUri().toString()
64        + "artists");
65
66      for (int i = 0; i < artists.length; i++) {
67        if (artists[i].name.equals(artist)) {
68          return artists[i].albums.length;
69        }
70      }
71      return -1;
72    }
73    // end::getTotalAlbums[]
74
75    @GET
76    @Path("total")
77    @Produces(MediaType.TEXT_PLAIN)
78    // tag::getTotalArtists[]
79    public int getTotalArtists() {
80      return Consumer.consumeWithJsonp(uriInfo.getBaseUri().toString()
81                                       + "artists").length;
82    }
83    // end::getTotalArtists[]
84}
85// end::ArtistResource[]
  • The getArtists() method provides the raw JSON data service that you accessed at the beginning of this guide.

  • The getJsonString() method uses JSON-B to return the JSON as a string that will be used later for testing.

  • The getTotalAlbums() method uses JSON-B to return the total number of albums present in the JSON for a particular artist. The method returns -1 if this artist does not exist.

  • The getTotalArtists() method uses JSON-P to return the total number of artists present in the JSON.

The methods that you wrote in the Consumer class could be written directly in the ArtistResource class. However, if you are consuming a REST resource from a third party service, you should separate your GET/POST requests from your data consumption.

Running the application

The Open Liberty was started in dev mode at the beginning of the guide and all the changes were automatically picked up.

You can find your service at http://localhost:9080/artists.

Now, you can access the endpoint at http://localhost:9080/artists/total to see the total number of artists, and you can access the endpoint at http://localhost:9080/artists/total/<artist> to see a particular artist’s total number of albums.

Testing deserialization

Create the ConsumingRestIT class.
src/test/java/it/io/openliberty/guides/consumingrest/ConsumingRestIT.java

ConsumingRestIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.consumingrest;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import jakarta.json.bind.Jsonb;
 17import jakarta.json.bind.JsonbBuilder;
 18import jakarta.ws.rs.client.Client;
 19import jakarta.ws.rs.client.ClientBuilder;
 20import jakarta.ws.rs.core.Response;
 21
 22import org.junit.jupiter.api.AfterEach;
 23import org.junit.jupiter.api.BeforeEach;
 24import org.junit.jupiter.api.BeforeAll;
 25import org.junit.jupiter.api.Test;
 26
 27import io.openliberty.guides.consumingrest.model.Artist;
 28
 29public class ConsumingRestIT {
 30
 31    private static String port;
 32    private static String baseUrl;
 33    private static String targetUrl;
 34
 35    private Client client;
 36    private Response response;
 37
 38    // tag::BeforeAll[]
 39    @BeforeAll
 40    // end::BeforeAll[]
 41    public static void oneTimeSetup() {
 42      port = System.getProperty("http.port");
 43      baseUrl = "http://localhost:" + port + "/artists/";
 44      targetUrl = baseUrl + "total/";
 45    }
 46
 47    // tag::BeforeEach[]
 48    @BeforeEach
 49    // end::BeforeEach[]
 50    public void setup() {
 51      client = ClientBuilder.newClient();
 52    }
 53
 54    // tag::AfterEach[]
 55    @AfterEach
 56    // end::AfterEach[]
 57    public void teardown() {
 58      client.close();
 59    }
 60
 61    // tag::test-1[]
 62    @Test
 63    // end::test-1[]
 64    // tag::testArtistDeserialization[]
 65    public void testArtistDeserialization() {
 66      response = client.target(baseUrl + "jsonString").request().get();
 67      this.assertResponse(baseUrl + "jsonString", response);
 68
 69      Jsonb jsonb = JsonbBuilder.create();
 70
 71      String expectedString = "{\"name\":\"foo\",\"albums\":"
 72        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 73      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 74
 75      String actualString = response.readEntity(String.class);
 76      Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 77
 78      assertEquals(expected.name, actual[0].name,
 79        "Expected names of artists does not match");
 80
 81      response.close();
 82    }
 83    // end::testArtistDeserialization[]
 84
 85    // tag::test-2[]
 86    @Test
 87    // end::test-2[]
 88    // tag::testJsonBAlbumCount[]
 89    public void testJsonBAlbumCount() {
 90      String[] artists = {"dj", "bar", "foo"};
 91      for (int i = 0; i < artists.length; i++) {
 92        response = client.target(targetUrl + artists[i]).request().get();
 93        this.assertResponse(targetUrl + artists[i], response);
 94
 95        int expected = i;
 96        int actual = response.readEntity(int.class);
 97        assertEquals(expected, actual, "Album count for "
 98                      + artists[i] + " does not match");
 99
100        response.close();
101      }
102    }
103    // end::testJsonBAlbumCount[]
104
105    // tag::testAlbumCountForUnknownArtist[]
106    // tag::test-3[]
107    @Test
108    // end::test-3[]
109    // tag::testJsonBAlbumCountForUnknownArtist[]
110    public void testJsonBAlbumCountForUnknownArtist() {
111      response = client.target(targetUrl + "unknown-artist").request().get();
112
113      int expected = -1;
114      int actual = response.readEntity(int.class);
115      assertEquals(expected, actual, "Unknown artist must have -1 albums");
116
117      response.close();
118    }
119    // end::testJsonBAlbumCountForUnknownArtist[]
120
121    // tag::test-4[]
122    @Test
123    // end::test-4[]
124    // tag::testJsonPArtistCount[]
125    public void testJsonPArtistCount() {
126      response = client.target(targetUrl).request().get();
127      this.assertResponse(targetUrl, response);
128
129      int expected = 3;
130      int actual = response.readEntity(int.class);
131      assertEquals(expected, actual, "Expected number of artists does not match");
132
133      response.close();
134    }
135    // end::testJsonPArtistCount[]
136
137    /**
138     * Asserts that the given URL has the correct (200) response code.
139     */
140    // tag::assertResponse[]
141    private void assertResponse(String url, Response response) {
142      assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
143    }
144    // end::assertResponse[]
145    // end::tests[]
146}

Maven finds and executes all tests under the src/test/java/it/ directory, and each test method must be marked with the @Test annotation.

You can use the @BeforeAll and @AfterAll annotations to perform any one-time setup and teardown tasks before and after all of your tests run. You can also use the @BeforeEach and @AfterEach annotations to perform setup and teardown tasks for individual test cases.

Testing the binding process

ConsumingRestIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.consumingrest;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import jakarta.json.bind.Jsonb;
 17import jakarta.json.bind.JsonbBuilder;
 18import jakarta.ws.rs.client.Client;
 19import jakarta.ws.rs.client.ClientBuilder;
 20import jakarta.ws.rs.core.Response;
 21
 22import org.junit.jupiter.api.AfterEach;
 23import org.junit.jupiter.api.BeforeEach;
 24import org.junit.jupiter.api.BeforeAll;
 25import org.junit.jupiter.api.Test;
 26
 27import io.openliberty.guides.consumingrest.model.Artist;
 28
 29public class ConsumingRestIT {
 30
 31    private static String port;
 32    private static String baseUrl;
 33    private static String targetUrl;
 34
 35    private Client client;
 36    private Response response;
 37
 38    // tag::BeforeAll[]
 39    @BeforeAll
 40    // end::BeforeAll[]
 41    public static void oneTimeSetup() {
 42      port = System.getProperty("http.port");
 43      baseUrl = "http://localhost:" + port + "/artists/";
 44      targetUrl = baseUrl + "total/";
 45    }
 46
 47    // tag::BeforeEach[]
 48    @BeforeEach
 49    // end::BeforeEach[]
 50    public void setup() {
 51      client = ClientBuilder.newClient();
 52    }
 53
 54    // tag::AfterEach[]
 55    @AfterEach
 56    // end::AfterEach[]
 57    public void teardown() {
 58      client.close();
 59    }
 60
 61    // tag::test-1[]
 62    @Test
 63    // end::test-1[]
 64    // tag::testArtistDeserialization[]
 65    public void testArtistDeserialization() {
 66      response = client.target(baseUrl + "jsonString").request().get();
 67      this.assertResponse(baseUrl + "jsonString", response);
 68
 69      Jsonb jsonb = JsonbBuilder.create();
 70
 71      String expectedString = "{\"name\":\"foo\",\"albums\":"
 72        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 73      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 74
 75      String actualString = response.readEntity(String.class);
 76      Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 77
 78      assertEquals(expected.name, actual[0].name,
 79        "Expected names of artists does not match");
 80
 81      response.close();
 82    }
 83    // end::testArtistDeserialization[]
 84
 85    // tag::test-2[]
 86    @Test
 87    // end::test-2[]
 88    // tag::testJsonBAlbumCount[]
 89    public void testJsonBAlbumCount() {
 90      String[] artists = {"dj", "bar", "foo"};
 91      for (int i = 0; i < artists.length; i++) {
 92        response = client.target(targetUrl + artists[i]).request().get();
 93        this.assertResponse(targetUrl + artists[i], response);
 94
 95        int expected = i;
 96        int actual = response.readEntity(int.class);
 97        assertEquals(expected, actual, "Album count for "
 98                      + artists[i] + " does not match");
 99
100        response.close();
101      }
102    }
103    // end::testJsonBAlbumCount[]
104
105    // tag::testAlbumCountForUnknownArtist[]
106    // tag::test-3[]
107    @Test
108    // end::test-3[]
109    // tag::testJsonBAlbumCountForUnknownArtist[]
110    public void testJsonBAlbumCountForUnknownArtist() {
111      response = client.target(targetUrl + "unknown-artist").request().get();
112
113      int expected = -1;
114      int actual = response.readEntity(int.class);
115      assertEquals(expected, actual, "Unknown artist must have -1 albums");
116
117      response.close();
118    }
119    // end::testJsonBAlbumCountForUnknownArtist[]
120
121    // tag::test-4[]
122    @Test
123    // end::test-4[]
124    // tag::testJsonPArtistCount[]
125    public void testJsonPArtistCount() {
126      response = client.target(targetUrl).request().get();
127      this.assertResponse(targetUrl, response);
128
129      int expected = 3;
130      int actual = response.readEntity(int.class);
131      assertEquals(expected, actual, "Expected number of artists does not match");
132
133      response.close();
134    }
135    // end::testJsonPArtistCount[]
136
137    /**
138     * Asserts that the given URL has the correct (200) response code.
139     */
140    // tag::assertResponse[]
141    private void assertResponse(String url, Response response) {
142      assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
143    }
144    // end::assertResponse[]
145    // end::tests[]
146}

pom.xml

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

The yasson dependency was added in your pom.xml file so that your test classes have access to JSON-B.

The testArtistDeserialization test case checks that Artist instances created from the REST data and those that are hardcoded perform the same.

The assertResponse helper method ensures that the response code you receive is valid (200).

Processing with JSON-B test

ConsumingRestIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.consumingrest;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import jakarta.json.bind.Jsonb;
 17import jakarta.json.bind.JsonbBuilder;
 18import jakarta.ws.rs.client.Client;
 19import jakarta.ws.rs.client.ClientBuilder;
 20import jakarta.ws.rs.core.Response;
 21
 22import org.junit.jupiter.api.AfterEach;
 23import org.junit.jupiter.api.BeforeEach;
 24import org.junit.jupiter.api.BeforeAll;
 25import org.junit.jupiter.api.Test;
 26
 27import io.openliberty.guides.consumingrest.model.Artist;
 28
 29public class ConsumingRestIT {
 30
 31    private static String port;
 32    private static String baseUrl;
 33    private static String targetUrl;
 34
 35    private Client client;
 36    private Response response;
 37
 38    // tag::BeforeAll[]
 39    @BeforeAll
 40    // end::BeforeAll[]
 41    public static void oneTimeSetup() {
 42      port = System.getProperty("http.port");
 43      baseUrl = "http://localhost:" + port + "/artists/";
 44      targetUrl = baseUrl + "total/";
 45    }
 46
 47    // tag::BeforeEach[]
 48    @BeforeEach
 49    // end::BeforeEach[]
 50    public void setup() {
 51      client = ClientBuilder.newClient();
 52    }
 53
 54    // tag::AfterEach[]
 55    @AfterEach
 56    // end::AfterEach[]
 57    public void teardown() {
 58      client.close();
 59    }
 60
 61    // tag::test-1[]
 62    @Test
 63    // end::test-1[]
 64    // tag::testArtistDeserialization[]
 65    public void testArtistDeserialization() {
 66      response = client.target(baseUrl + "jsonString").request().get();
 67      this.assertResponse(baseUrl + "jsonString", response);
 68
 69      Jsonb jsonb = JsonbBuilder.create();
 70
 71      String expectedString = "{\"name\":\"foo\",\"albums\":"
 72        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 73      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 74
 75      String actualString = response.readEntity(String.class);
 76      Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 77
 78      assertEquals(expected.name, actual[0].name,
 79        "Expected names of artists does not match");
 80
 81      response.close();
 82    }
 83    // end::testArtistDeserialization[]
 84
 85    // tag::test-2[]
 86    @Test
 87    // end::test-2[]
 88    // tag::testJsonBAlbumCount[]
 89    public void testJsonBAlbumCount() {
 90      String[] artists = {"dj", "bar", "foo"};
 91      for (int i = 0; i < artists.length; i++) {
 92        response = client.target(targetUrl + artists[i]).request().get();
 93        this.assertResponse(targetUrl + artists[i], response);
 94
 95        int expected = i;
 96        int actual = response.readEntity(int.class);
 97        assertEquals(expected, actual, "Album count for "
 98                      + artists[i] + " does not match");
 99
100        response.close();
101      }
102    }
103    // end::testJsonBAlbumCount[]
104
105    // tag::testAlbumCountForUnknownArtist[]
106    // tag::test-3[]
107    @Test
108    // end::test-3[]
109    // tag::testJsonBAlbumCountForUnknownArtist[]
110    public void testJsonBAlbumCountForUnknownArtist() {
111      response = client.target(targetUrl + "unknown-artist").request().get();
112
113      int expected = -1;
114      int actual = response.readEntity(int.class);
115      assertEquals(expected, actual, "Unknown artist must have -1 albums");
116
117      response.close();
118    }
119    // end::testJsonBAlbumCountForUnknownArtist[]
120
121    // tag::test-4[]
122    @Test
123    // end::test-4[]
124    // tag::testJsonPArtistCount[]
125    public void testJsonPArtistCount() {
126      response = client.target(targetUrl).request().get();
127      this.assertResponse(targetUrl, response);
128
129      int expected = 3;
130      int actual = response.readEntity(int.class);
131      assertEquals(expected, actual, "Expected number of artists does not match");
132
133      response.close();
134    }
135    // end::testJsonPArtistCount[]
136
137    /**
138     * Asserts that the given URL has the correct (200) response code.
139     */
140    // tag::assertResponse[]
141    private void assertResponse(String url, Response response) {
142      assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
143    }
144    // end::assertResponse[]
145    // end::tests[]
146}

The testJsonBAlbumCount and testJsonBAlbumCountForUnknownArtist tests both use the total/{artist} endpoint which invokes JSON-B.

The testJsonBAlbumCount test case checks that deserialization with JSON-B was done correctly and that the correct number of albums is returned for each artist in the JSON.

The testJsonBAlbumCountForUnknownArtist test case is similar to testJsonBAlbumCount but instead checks an artist that does not exist in the JSON and ensures that a value of -1 is returned.

Processing with JSON-P test

ConsumingRestIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.consumingrest;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import jakarta.json.bind.Jsonb;
 17import jakarta.json.bind.JsonbBuilder;
 18import jakarta.ws.rs.client.Client;
 19import jakarta.ws.rs.client.ClientBuilder;
 20import jakarta.ws.rs.core.Response;
 21
 22import org.junit.jupiter.api.AfterEach;
 23import org.junit.jupiter.api.BeforeEach;
 24import org.junit.jupiter.api.BeforeAll;
 25import org.junit.jupiter.api.Test;
 26
 27import io.openliberty.guides.consumingrest.model.Artist;
 28
 29public class ConsumingRestIT {
 30
 31    private static String port;
 32    private static String baseUrl;
 33    private static String targetUrl;
 34
 35    private Client client;
 36    private Response response;
 37
 38    // tag::BeforeAll[]
 39    @BeforeAll
 40    // end::BeforeAll[]
 41    public static void oneTimeSetup() {
 42      port = System.getProperty("http.port");
 43      baseUrl = "http://localhost:" + port + "/artists/";
 44      targetUrl = baseUrl + "total/";
 45    }
 46
 47    // tag::BeforeEach[]
 48    @BeforeEach
 49    // end::BeforeEach[]
 50    public void setup() {
 51      client = ClientBuilder.newClient();
 52    }
 53
 54    // tag::AfterEach[]
 55    @AfterEach
 56    // end::AfterEach[]
 57    public void teardown() {
 58      client.close();
 59    }
 60
 61    // tag::test-1[]
 62    @Test
 63    // end::test-1[]
 64    // tag::testArtistDeserialization[]
 65    public void testArtistDeserialization() {
 66      response = client.target(baseUrl + "jsonString").request().get();
 67      this.assertResponse(baseUrl + "jsonString", response);
 68
 69      Jsonb jsonb = JsonbBuilder.create();
 70
 71      String expectedString = "{\"name\":\"foo\",\"albums\":"
 72        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 73      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 74
 75      String actualString = response.readEntity(String.class);
 76      Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 77
 78      assertEquals(expected.name, actual[0].name,
 79        "Expected names of artists does not match");
 80
 81      response.close();
 82    }
 83    // end::testArtistDeserialization[]
 84
 85    // tag::test-2[]
 86    @Test
 87    // end::test-2[]
 88    // tag::testJsonBAlbumCount[]
 89    public void testJsonBAlbumCount() {
 90      String[] artists = {"dj", "bar", "foo"};
 91      for (int i = 0; i < artists.length; i++) {
 92        response = client.target(targetUrl + artists[i]).request().get();
 93        this.assertResponse(targetUrl + artists[i], response);
 94
 95        int expected = i;
 96        int actual = response.readEntity(int.class);
 97        assertEquals(expected, actual, "Album count for "
 98                      + artists[i] + " does not match");
 99
100        response.close();
101      }
102    }
103    // end::testJsonBAlbumCount[]
104
105    // tag::testAlbumCountForUnknownArtist[]
106    // tag::test-3[]
107    @Test
108    // end::test-3[]
109    // tag::testJsonBAlbumCountForUnknownArtist[]
110    public void testJsonBAlbumCountForUnknownArtist() {
111      response = client.target(targetUrl + "unknown-artist").request().get();
112
113      int expected = -1;
114      int actual = response.readEntity(int.class);
115      assertEquals(expected, actual, "Unknown artist must have -1 albums");
116
117      response.close();
118    }
119    // end::testJsonBAlbumCountForUnknownArtist[]
120
121    // tag::test-4[]
122    @Test
123    // end::test-4[]
124    // tag::testJsonPArtistCount[]
125    public void testJsonPArtistCount() {
126      response = client.target(targetUrl).request().get();
127      this.assertResponse(targetUrl, response);
128
129      int expected = 3;
130      int actual = response.readEntity(int.class);
131      assertEquals(expected, actual, "Expected number of artists does not match");
132
133      response.close();
134    }
135    // end::testJsonPArtistCount[]
136
137    /**
138     * Asserts that the given URL has the correct (200) response code.
139     */
140    // tag::assertResponse[]
141    private void assertResponse(String url, Response response) {
142      assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
143    }
144    // end::assertResponse[]
145    // end::tests[]
146}

The testJsonPArtistCount test uses the total endpoint which invokes JSON-P. This test checks that deserialization with JSON-P was done correctly and that the correct number of artists is returned.

Running the tests

Becayse you started Open Liberty in dev mode at the start of the guide, press the enter/return key to run the tests.

If the tests pass, you see a similar output to the following example:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.consumingrest.ConsumingRestIT
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.59 sec - in it.io.openliberty.guides.consumingrest.ConsumingRestIT

Results :

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

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran Liberty.

Building the application

If you are satisfied with your application, run the Maven package goal to build the WAR file in the target directory:

mvn package

Great work! You’re done!

You just accessed a simple RESTful web service and consumed its resources by using JSON-B and JSON-P in Open Liberty.

Guide Attribution

Consuming a RESTful web service by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star