Consuming a RESTful web service

duration 25 minutes
Git clone to get going right away:
git clone https://github.com/OpenLiberty/guide-rest-client-java.git
Copy Github clone command

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 has already been written for you and is accessible at the following link when the server is running http://localhost:9080/artists

Which responds with the artists.json

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.

Starting the service

This guide is already setup with a general application. As you progress through the guide you will make updates to the code directly, and then push updates to the server so you can see the results.

To start the REST service, run the Maven install and liberty:start-server goals from the start directory:

mvn install liberty:start-server

When the server is running, you can find your service at http://localhost:9080/artists

After you are done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Creating POJOs

Artist.java

 1package io.openliberty.guides.consumingrest.model;
 2
 3import javax.json.bind.annotation.JsonbCreator;
 4import javax.json.bind.annotation.JsonbProperty;
 5import javax.json.bind.annotation.JsonbTransient;
 6
 7public class Artist {
 8    public String name;
 9    public Album albums[];
10
11    //does not map to anything
12    @JsonbTransient
13    public boolean legendary = true;
14
15    //default constructor can be defined
16    public Artist() {
17
18    }
19
20    @JsonbCreator
21    //or custom constructor can be used
22    public Artist(
23      @JsonbProperty("name") String name,
24      @JsonbProperty("albums") Album albums[]) {
25
26      this.name = name;
27      this.albums = albums;
28    }
29
30    @Override
31    public String toString() {
32      return name + " wrote " + albums.length + " albums";
33    }
34}

Album.java

 1package io.openliberty.guides.consumingrest.model;
 2
 3import javax.json.bind.annotation.JsonbCreator;
 4import javax.json.bind.annotation.JsonbProperty;
 5
 6public class Album {
 7    public String title;
 8
 9    @JsonbProperty("artist")
10    public String artistName;
11
12    @JsonbProperty("ntracks")
13    public int totalTracks;
14
15    //default constructor can be defined
16    public Album() {
17    }
18
19    @JsonbCreator
20    //or custom constructor can be used
21    public Album(
22      @JsonbProperty("title") String title,
23      @JsonbProperty("artist") String artistName,
24      @JsonbProperty("ntracks") int totalTracks) {
25
26      this.title = title;
27      this.artistName = artistName;
28      this.totalTracks = totalTracks;
29    }
30
31    @Override
32    public String toString() {
33      return "Album titled " + title + " by " + artistName +
34        " contains " + totalTracks + " tracks";
35    }
36}

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

 1package io.openliberty.guides.consumingrest.model;
 2
 3import javax.json.bind.annotation.JsonbCreator;
 4import javax.json.bind.annotation.JsonbProperty;
 5import javax.json.bind.annotation.JsonbTransient;
 6
 7public class Artist {
 8    public String name;
 9    public Album albums[];
10
11    //does not map to anything
12    @JsonbTransient
13    public boolean legendary = true;
14
15    //default constructor can be defined
16    public Artist() {
17
18    }
19
20    @JsonbCreator
21    //or custom constructor can be used
22    public Artist(
23      @JsonbProperty("name") String name,
24      @JsonbProperty("albums") Album albums[]) {
25
26      this.name = name;
27      this.albums = albums;
28    }
29
30    @Override
31    public String toString() {
32      return name + " wrote " + albums.length + " albums";
33    }
34}

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 a match cannot be found, JSON-B will attempt to find a matching getter (for serialization) or setter (for de-serialization) method whose property name matches the JSON key. If no matching getter/setter method can be found, then serialization/de-serialization will fail 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

 1package io.openliberty.guides.consumingrest.model;
 2
 3import javax.json.bind.annotation.JsonbCreator;
 4import javax.json.bind.annotation.JsonbProperty;
 5import javax.json.bind.annotation.JsonbTransient;
 6
 7public class Artist {
 8    public String name;
 9    public Album albums[];
10
11    //does not map to anything
12    @JsonbTransient
13    public boolean legendary = true;
14
15    //default constructor can be defined
16    public Artist() {
17
18    }
19
20    @JsonbCreator
21    //or custom constructor can be used
22    public Artist(
23      @JsonbProperty("name") String name,
24      @JsonbProperty("albums") Album albums[]) {
25
26      this.name = name;
27      this.albums = albums;
28    }
29
30    @Override
31    public String toString() {
32      return name + " wrote " + albums.length + " albums";
33    }
34}

Album.java

 1package io.openliberty.guides.consumingrest.model;
 2
 3import javax.json.bind.annotation.JsonbCreator;
 4import javax.json.bind.annotation.JsonbProperty;
 5
 6public class Album {
 7    public String title;
 8
 9    @JsonbProperty("artist")
10    public String artistName;
11
12    @JsonbProperty("ntracks")
13    public int totalTracks;
14
15    //default constructor can be defined
16    public Album() {
17    }
18
19    @JsonbCreator
20    //or custom constructor can be used
21    public Album(
22      @JsonbProperty("title") String title,
23      @JsonbProperty("artist") String artistName,
24      @JsonbProperty("ntracks") int totalTracks) {
25
26      this.title = title;
27      this.artistName = artistName;
28      this.totalTracks = totalTracks;
29    }
30
31    @Override
32    public String toString() {
33      return "Album titled " + title + " by " + artistName +
34        " contains " + totalTracks + " tracks";
35    }
36}

Consumer.java

 1package io.openliberty.guides.consumingrest;
 2
 3import java.util.List;
 4import java.util.stream.Collectors;
 5
 6import javax.json.JsonArray;
 7import javax.json.JsonObject;
 8import javax.ws.rs.client.Client;
 9import javax.ws.rs.client.ClientBuilder;
10import javax.ws.rs.core.Response;
11
12import io.openliberty.guides.consumingrest.model.Album;
13import io.openliberty.guides.consumingrest.model.Artist;
14
15public class Consumer {
16    public static Artist[] consumeWithJsonb(String targetUrl) {
17      Client client = ClientBuilder.newClient();
18
19      Response response = client.target(targetUrl).request().get();
20      Artist[] artists = response.readEntity(Artist[].class);
21
22      response.close();
23      client.close();
24
25      return artists;
26    }
27
28    public static Artist[] consumeWithJsonp(String targetUrl) {
29      Client client = ClientBuilder.newClient();
30
31      Response response = client.target(targetUrl).request().get();
32      JsonArray arr = response.readEntity(JsonArray.class);
33
34      response.close();
35      client.close();
36
37      return Consumer.collectArtists(arr);
38    }
39
40    private static Artist[] collectArtists(JsonArray artistArr) {
41      List<Artist> artists = artistArr.stream().map(artistJson -> {
42        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
43        Artist artist = new Artist(
44          ((JsonObject) artistJson).getString("name"),
45          Consumer.collectAlbums(albumArr));
46        return artist;
47      }).collect(Collectors.toList());
48
49      return artists.toArray(new Artist[artists.size()]);
50    }
51
52    private static Album[] collectAlbums(JsonArray albumArr) {
53      List<Album> albums = albumArr.stream().map(albumJson -> {
54        Album album = new Album(
55          ((JsonObject) albumJson).getString("title"),
56          ((JsonObject) albumJson).getString("artist"),
57          ((JsonObject) albumJson).getInt("ntracks") );
58        return album;
59      }).collect(Collectors.toList());
60
61      return albums.toArray(new Album[albums.size()]);
62    }
63}

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

Processing JSON using JSON-B

Consumer.java

 1package io.openliberty.guides.consumingrest;
 2
 3import java.util.List;
 4import java.util.stream.Collectors;
 5
 6import javax.json.JsonArray;
 7import javax.json.JsonObject;
 8import javax.ws.rs.client.Client;
 9import javax.ws.rs.client.ClientBuilder;
10import javax.ws.rs.core.Response;
11
12import io.openliberty.guides.consumingrest.model.Album;
13import io.openliberty.guides.consumingrest.model.Artist;
14
15public class Consumer {
16    public static Artist[] consumeWithJsonb(String targetUrl) {
17      Client client = ClientBuilder.newClient();
18
19      Response response = client.target(targetUrl).request().get();
20      Artist[] artists = response.readEntity(Artist[].class);
21
22      response.close();
23      client.close();
24
25      return artists;
26    }
27
28    public static Artist[] consumeWithJsonp(String targetUrl) {
29      Client client = ClientBuilder.newClient();
30
31      Response response = client.target(targetUrl).request().get();
32      JsonArray arr = response.readEntity(JsonArray.class);
33
34      response.close();
35      client.close();
36
37      return Consumer.collectArtists(arr);
38    }
39
40    private static Artist[] collectArtists(JsonArray artistArr) {
41      List<Artist> artists = artistArr.stream().map(artistJson -> {
42        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
43        Artist artist = new Artist(
44          ((JsonObject) artistJson).getString("name"),
45          Consumer.collectAlbums(albumArr));
46        return artist;
47      }).collect(Collectors.toList());
48
49      return artists.toArray(new Artist[artists.size()]);
50    }
51
52    private static Album[] collectAlbums(JsonArray albumArr) {
53      List<Album> albums = albumArr.stream().map(albumJson -> {
54        Album album = new Album(
55          ((JsonObject) albumJson).getString("title"),
56          ((JsonObject) albumJson).getString("artist"),
57          ((JsonObject) albumJson).getInt("ntracks") );
58        return album;
59      }).collect(Collectors.toList());
60
61      return albums.toArray(new Album[albums.size()]);
62    }
63}

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

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

Processing JSON using JSON-P

Consumer.java

 1package io.openliberty.guides.consumingrest;
 2
 3import java.util.List;
 4import java.util.stream.Collectors;
 5
 6import javax.json.JsonArray;
 7import javax.json.JsonObject;
 8import javax.ws.rs.client.Client;
 9import javax.ws.rs.client.ClientBuilder;
10import javax.ws.rs.core.Response;
11
12import io.openliberty.guides.consumingrest.model.Album;
13import io.openliberty.guides.consumingrest.model.Artist;
14
15public class Consumer {
16    public static Artist[] consumeWithJsonb(String targetUrl) {
17      Client client = ClientBuilder.newClient();
18
19      Response response = client.target(targetUrl).request().get();
20      Artist[] artists = response.readEntity(Artist[].class);
21
22      response.close();
23      client.close();
24
25      return artists;
26    }
27
28    public static Artist[] consumeWithJsonp(String targetUrl) {
29      Client client = ClientBuilder.newClient();
30
31      Response response = client.target(targetUrl).request().get();
32      JsonArray arr = response.readEntity(JsonArray.class);
33
34      response.close();
35      client.close();
36
37      return Consumer.collectArtists(arr);
38    }
39
40    private static Artist[] collectArtists(JsonArray artistArr) {
41      List<Artist> artists = artistArr.stream().map(artistJson -> {
42        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
43        Artist artist = new Artist(
44          ((JsonObject) artistJson).getString("name"),
45          Consumer.collectAlbums(albumArr));
46        return artist;
47      }).collect(Collectors.toList());
48
49      return artists.toArray(new Artist[artists.size()]);
50    }
51
52    private static Album[] collectAlbums(JsonArray albumArr) {
53      List<Album> albums = albumArr.stream().map(albumJson -> {
54        Album album = new Album(
55          ((JsonObject) albumJson).getString("title"),
56          ((JsonObject) albumJson).getString("artist"),
57          ((JsonObject) albumJson).getInt("ntracks") );
58        return album;
59      }).collect(Collectors.toList());
60
61      return albums.toArray(new Album[albums.size()]);
62    }
63}

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

 1package io.openliberty.guides.consumingrest;
 2
 3import java.util.List;
 4import java.util.stream.Collectors;
 5
 6import javax.json.JsonArray;
 7import javax.json.JsonObject;
 8import javax.ws.rs.client.Client;
 9import javax.ws.rs.client.ClientBuilder;
10import javax.ws.rs.core.Response;
11
12import io.openliberty.guides.consumingrest.model.Album;
13import io.openliberty.guides.consumingrest.model.Artist;
14
15public class Consumer {
16    public static Artist[] consumeWithJsonb(String targetUrl) {
17      Client client = ClientBuilder.newClient();
18
19      Response response = client.target(targetUrl).request().get();
20      Artist[] artists = response.readEntity(Artist[].class);
21
22      response.close();
23      client.close();
24
25      return artists;
26    }
27
28    public static Artist[] consumeWithJsonp(String targetUrl) {
29      Client client = ClientBuilder.newClient();
30
31      Response response = client.target(targetUrl).request().get();
32      JsonArray arr = response.readEntity(JsonArray.class);
33
34      response.close();
35      client.close();
36
37      return Consumer.collectArtists(arr);
38    }
39
40    private static Artist[] collectArtists(JsonArray artistArr) {
41      List<Artist> artists = artistArr.stream().map(artistJson -> {
42        JsonArray albumArr = ((JsonObject) artistJson).getJsonArray("albums");
43        Artist artist = new Artist(
44          ((JsonObject) artistJson).getString("name"),
45          Consumer.collectAlbums(albumArr));
46        return artist;
47      }).collect(Collectors.toList());
48
49      return artists.toArray(new Artist[artists.size()]);
50    }
51
52    private static Album[] collectAlbums(JsonArray albumArr) {
53      List<Album> albums = albumArr.stream().map(albumJson -> {
54        Album album = new Album(
55          ((JsonObject) albumJson).getString("title"),
56          ((JsonObject) albumJson).getString("artist"),
57          ((JsonObject) albumJson).getInt("ntracks") );
58        return album;
59      }).collect(Collectors.toList());
60
61      return albums.toArray(new Album[albums.size()]);
62    }
63}

ArtistResource.java

 1package io.openliberty.guides.consumingrest.service;
 2
 3import javax.json.JsonArray;
 4import javax.json.bind.Jsonb;
 5import javax.json.bind.JsonbBuilder;
 6import javax.ws.rs.GET;
 7import javax.ws.rs.Path;
 8import javax.ws.rs.PathParam;
 9import javax.ws.rs.Produces;
10import javax.ws.rs.core.Context;
11import javax.ws.rs.core.MediaType;
12import javax.ws.rs.core.UriInfo;
13
14import io.openliberty.guides.consumingrest.model.Artist;
15import io.openliberty.guides.consumingrest.Consumer;
16
17@Path("artists")
18public class ArtistResource {
19
20    @Context
21    UriInfo uriInfo;
22
23    @GET
24    @Produces(MediaType.APPLICATION_JSON)
25    public JsonArray getArtists() {
26            return Reader.getArtists();
27    }
28
29    @GET
30    @Path("jsonString")
31    @Produces(MediaType.TEXT_PLAIN)
32    public String getJsonString() {
33      Jsonb jsonb = JsonbBuilder.create();
34
35      Artist[] artists = Consumer.consumeWithJsonb(uriInfo.getBaseUri().toString() +
36        "artists");
37      String result = jsonb.toJson(artists);
38
39      return result;
40    }
41
42    @GET
43    @Path("total/{artist}")
44    @Produces(MediaType.TEXT_PLAIN)
45    public int getTotalAlbums(@PathParam("artist") String artist) {
46      Artist[] artists = Consumer.consumeWithJsonb(uriInfo.getBaseUri().toString()
47        + "artists");
48
49      for (int i = 0; i < artists.length; i++) {
50        if (artists[i].name.equals(artist)) {
51          return artists[i].albums.length;
52        }
53      }
54      return -1;
55    }
56
57    @GET
58    @Path("total")
59    @Produces(MediaType.TEXT_PLAIN)
60    public int getTotalArtists() {
61      return Consumer.consumeWithJsonp(uriInfo.getBaseUri().toString() +
62        "artists").length;
63    }
64
65}

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

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, you can find your service at http://localhost:9080/artists

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 deserialization

ConsumingRestTest.java

  1package it.io.openliberty.guides.consumingrest;
  2
  3import static org.junit.Assert.assertEquals;
  4
  5import javax.json.bind.Jsonb;
  6import javax.json.bind.JsonbBuilder;
  7import javax.ws.rs.client.Client;
  8import javax.ws.rs.client.ClientBuilder;
  9import javax.ws.rs.core.Response;
 10
 11import org.junit.After;
 12import org.junit.Before;
 13import org.junit.BeforeClass;
 14import org.junit.Test;
 15
 16import io.openliberty.guides.consumingrest.model.Artist;
 17
 18public class ConsumingRestTest {
 19
 20    private static String port;
 21    private static String baseUrl;
 22    private static String targetUrl;
 23
 24    private Client client;
 25    private Response response;
 26
 27    @BeforeClass
 28    public static void oneTimeSetup() {
 29      port = System.getProperty("liberty.test.port");
 30      baseUrl = "http://localhost:" + port + "/artists/";
 31      targetUrl = baseUrl + "total/";
 32    }
 33
 34    @Before
 35    public void setup() {
 36      client = ClientBuilder.newClient();
 37    }
 38
 39    @After
 40    public void teardown() {
 41      client.close();
 42    }
 43
 44    @Test
 45    public void testArtistDeserialization() {
 46      response = client.target(baseUrl + "jsonString").request().get();
 47      this.assertResponse(baseUrl + "jsonString", response);
 48
 49      Jsonb jsonb = JsonbBuilder.create();
 50
 51      String expectedString = "{\"name\":\"foo\",\"albums\":"
 52        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 53      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 54
 55      String actualString = response.readEntity(String.class);
 56                  Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 57
 58      assertEquals("Expected names of artists does not match", expected.name,
 59        actual[0].name);
 60
 61      response.close();
 62    }
 63
 64    @Test
 65    public void testJsonBAlbumCount() {
 66      String[] artists = {"dj", "bar", "foo"};
 67      for (int i = 0; i < artists.length; i++) {
 68        response = client.target(targetUrl + artists[i]).request().get();
 69        this.assertResponse(targetUrl + artists[i], response);
 70
 71        int expected = i;
 72        int actual = response.readEntity(int.class);
 73        assertEquals("Album count for " + artists[i] + " does not match", expected, actual);
 74
 75        response.close();
 76      }
 77    }
 78
 79    @Test
 80    public void testJsonBAlbumCountForUnknownArtist() {
 81      response = client.target(targetUrl + "unknown-artist").request().get();
 82
 83      int expected = -1;
 84      int actual = response.readEntity(int.class);
 85      assertEquals("Unknown artist must have -1 albums", expected, actual);
 86
 87      response.close();
 88    }
 89
 90    @Test
 91    public void testJsonPArtistCount() {
 92      response = client.target(targetUrl).request().get();
 93      this.assertResponse(targetUrl, response);
 94
 95      int expected = 3;
 96      int actual = response.readEntity(int.class);
 97      assertEquals("Expected number of artists does not match", expected, actual);
 98
 99      response.close();
100    }
101
102    /**
103     * Asserts that the given URL has the correct (200) response code.
104     */
105    private void assertResponse(String url, Response response) {
106      assertEquals("Incorrect response code from " + url, 200, response.getStatus());
107    }
108}
Create the ConsumingRestTest class.
src/test/java/it/io/openliberty/guides/consumingrest/ConsumingRestTest.java

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

You can use the @BeforeClass and @AfterClass annotations to perform any one time setup and teardown tasks before and after all of your tests execute, as well as the @Before and @After annotations to do the same but for each individual test case.

Testing the binding process

ConsumingRestTest.java

  1package it.io.openliberty.guides.consumingrest;
  2
  3import static org.junit.Assert.assertEquals;
  4
  5import javax.json.bind.Jsonb;
  6import javax.json.bind.JsonbBuilder;
  7import javax.ws.rs.client.Client;
  8import javax.ws.rs.client.ClientBuilder;
  9import javax.ws.rs.core.Response;
 10
 11import org.junit.After;
 12import org.junit.Before;
 13import org.junit.BeforeClass;
 14import org.junit.Test;
 15
 16import io.openliberty.guides.consumingrest.model.Artist;
 17
 18public class ConsumingRestTest {
 19
 20    private static String port;
 21    private static String baseUrl;
 22    private static String targetUrl;
 23
 24    private Client client;
 25    private Response response;
 26
 27    @BeforeClass
 28    public static void oneTimeSetup() {
 29      port = System.getProperty("liberty.test.port");
 30      baseUrl = "http://localhost:" + port + "/artists/";
 31      targetUrl = baseUrl + "total/";
 32    }
 33
 34    @Before
 35    public void setup() {
 36      client = ClientBuilder.newClient();
 37    }
 38
 39    @After
 40    public void teardown() {
 41      client.close();
 42    }
 43
 44    @Test
 45    public void testArtistDeserialization() {
 46      response = client.target(baseUrl + "jsonString").request().get();
 47      this.assertResponse(baseUrl + "jsonString", response);
 48
 49      Jsonb jsonb = JsonbBuilder.create();
 50
 51      String expectedString = "{\"name\":\"foo\",\"albums\":"
 52        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 53      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 54
 55      String actualString = response.readEntity(String.class);
 56                  Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 57
 58      assertEquals("Expected names of artists does not match", expected.name,
 59        actual[0].name);
 60
 61      response.close();
 62    }
 63
 64    @Test
 65    public void testJsonBAlbumCount() {
 66      String[] artists = {"dj", "bar", "foo"};
 67      for (int i = 0; i < artists.length; i++) {
 68        response = client.target(targetUrl + artists[i]).request().get();
 69        this.assertResponse(targetUrl + artists[i], response);
 70
 71        int expected = i;
 72        int actual = response.readEntity(int.class);
 73        assertEquals("Album count for " + artists[i] + " does not match", expected, actual);
 74
 75        response.close();
 76      }
 77    }
 78
 79    @Test
 80    public void testJsonBAlbumCountForUnknownArtist() {
 81      response = client.target(targetUrl + "unknown-artist").request().get();
 82
 83      int expected = -1;
 84      int actual = response.readEntity(int.class);
 85      assertEquals("Unknown artist must have -1 albums", expected, actual);
 86
 87      response.close();
 88    }
 89
 90    @Test
 91    public void testJsonPArtistCount() {
 92      response = client.target(targetUrl).request().get();
 93      this.assertResponse(targetUrl, response);
 94
 95      int expected = 3;
 96      int actual = response.readEntity(int.class);
 97      assertEquals("Expected number of artists does not match", expected, actual);
 98
 99      response.close();
100    }
101
102    /**
103     * Asserts that the given URL has the correct (200) response code.
104     */
105    private void assertResponse(String url, Response response) {
106      assertEquals("Incorrect response code from " + url, 200, response.getStatus());
107    }
108}

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

For your test classes to have access to JSON-B, the yasson dependency has been added in your pom.xml.

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

ConsumingRestTest.java

  1package it.io.openliberty.guides.consumingrest;
  2
  3import static org.junit.Assert.assertEquals;
  4
  5import javax.json.bind.Jsonb;
  6import javax.json.bind.JsonbBuilder;
  7import javax.ws.rs.client.Client;
  8import javax.ws.rs.client.ClientBuilder;
  9import javax.ws.rs.core.Response;
 10
 11import org.junit.After;
 12import org.junit.Before;
 13import org.junit.BeforeClass;
 14import org.junit.Test;
 15
 16import io.openliberty.guides.consumingrest.model.Artist;
 17
 18public class ConsumingRestTest {
 19
 20    private static String port;
 21    private static String baseUrl;
 22    private static String targetUrl;
 23
 24    private Client client;
 25    private Response response;
 26
 27    @BeforeClass
 28    public static void oneTimeSetup() {
 29      port = System.getProperty("liberty.test.port");
 30      baseUrl = "http://localhost:" + port + "/artists/";
 31      targetUrl = baseUrl + "total/";
 32    }
 33
 34    @Before
 35    public void setup() {
 36      client = ClientBuilder.newClient();
 37    }
 38
 39    @After
 40    public void teardown() {
 41      client.close();
 42    }
 43
 44    @Test
 45    public void testArtistDeserialization() {
 46      response = client.target(baseUrl + "jsonString").request().get();
 47      this.assertResponse(baseUrl + "jsonString", response);
 48
 49      Jsonb jsonb = JsonbBuilder.create();
 50
 51      String expectedString = "{\"name\":\"foo\",\"albums\":"
 52        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 53      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 54
 55      String actualString = response.readEntity(String.class);
 56                  Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 57
 58      assertEquals("Expected names of artists does not match", expected.name,
 59        actual[0].name);
 60
 61      response.close();
 62    }
 63
 64    @Test
 65    public void testJsonBAlbumCount() {
 66      String[] artists = {"dj", "bar", "foo"};
 67      for (int i = 0; i < artists.length; i++) {
 68        response = client.target(targetUrl + artists[i]).request().get();
 69        this.assertResponse(targetUrl + artists[i], response);
 70
 71        int expected = i;
 72        int actual = response.readEntity(int.class);
 73        assertEquals("Album count for " + artists[i] + " does not match", expected, actual);
 74
 75        response.close();
 76      }
 77    }
 78
 79    @Test
 80    public void testJsonBAlbumCountForUnknownArtist() {
 81      response = client.target(targetUrl + "unknown-artist").request().get();
 82
 83      int expected = -1;
 84      int actual = response.readEntity(int.class);
 85      assertEquals("Unknown artist must have -1 albums", expected, actual);
 86
 87      response.close();
 88    }
 89
 90    @Test
 91    public void testJsonPArtistCount() {
 92      response = client.target(targetUrl).request().get();
 93      this.assertResponse(targetUrl, response);
 94
 95      int expected = 3;
 96      int actual = response.readEntity(int.class);
 97      assertEquals("Expected number of artists does not match", expected, actual);
 98
 99      response.close();
100    }
101
102    /**
103     * Asserts that the given URL has the correct (200) response code.
104     */
105    private void assertResponse(String url, Response response) {
106      assertEquals("Incorrect response code from " + url, 200, response.getStatus());
107    }
108}

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

ConsumingRestTest.java

  1package it.io.openliberty.guides.consumingrest;
  2
  3import static org.junit.Assert.assertEquals;
  4
  5import javax.json.bind.Jsonb;
  6import javax.json.bind.JsonbBuilder;
  7import javax.ws.rs.client.Client;
  8import javax.ws.rs.client.ClientBuilder;
  9import javax.ws.rs.core.Response;
 10
 11import org.junit.After;
 12import org.junit.Before;
 13import org.junit.BeforeClass;
 14import org.junit.Test;
 15
 16import io.openliberty.guides.consumingrest.model.Artist;
 17
 18public class ConsumingRestTest {
 19
 20    private static String port;
 21    private static String baseUrl;
 22    private static String targetUrl;
 23
 24    private Client client;
 25    private Response response;
 26
 27    @BeforeClass
 28    public static void oneTimeSetup() {
 29      port = System.getProperty("liberty.test.port");
 30      baseUrl = "http://localhost:" + port + "/artists/";
 31      targetUrl = baseUrl + "total/";
 32    }
 33
 34    @Before
 35    public void setup() {
 36      client = ClientBuilder.newClient();
 37    }
 38
 39    @After
 40    public void teardown() {
 41      client.close();
 42    }
 43
 44    @Test
 45    public void testArtistDeserialization() {
 46      response = client.target(baseUrl + "jsonString").request().get();
 47      this.assertResponse(baseUrl + "jsonString", response);
 48
 49      Jsonb jsonb = JsonbBuilder.create();
 50
 51      String expectedString = "{\"name\":\"foo\",\"albums\":"
 52        + "[{\"title\":\"album_one\",\"artist\":\"foo\",\"ntracks\":12}]}";
 53      Artist expected = jsonb.fromJson(expectedString, Artist.class);
 54
 55      String actualString = response.readEntity(String.class);
 56                  Artist[] actual = jsonb.fromJson(actualString, Artist[].class);
 57
 58      assertEquals("Expected names of artists does not match", expected.name,
 59        actual[0].name);
 60
 61      response.close();
 62    }
 63
 64    @Test
 65    public void testJsonBAlbumCount() {
 66      String[] artists = {"dj", "bar", "foo"};
 67      for (int i = 0; i < artists.length; i++) {
 68        response = client.target(targetUrl + artists[i]).request().get();
 69        this.assertResponse(targetUrl + artists[i], response);
 70
 71        int expected = i;
 72        int actual = response.readEntity(int.class);
 73        assertEquals("Album count for " + artists[i] + " does not match", expected, actual);
 74
 75        response.close();
 76      }
 77    }
 78
 79    @Test
 80    public void testJsonBAlbumCountForUnknownArtist() {
 81      response = client.target(targetUrl + "unknown-artist").request().get();
 82
 83      int expected = -1;
 84      int actual = response.readEntity(int.class);
 85      assertEquals("Unknown artist must have -1 albums", expected, actual);
 86
 87      response.close();
 88    }
 89
 90    @Test
 91    public void testJsonPArtistCount() {
 92      response = client.target(targetUrl).request().get();
 93      this.assertResponse(targetUrl, response);
 94
 95      int expected = 3;
 96      int actual = response.readEntity(int.class);
 97      assertEquals("Expected number of artists does not match", expected, actual);
 98
 99      response.close();
100    }
101
102    /**
103     * Asserts that the given URL has the correct (200) response code.
104     */
105    private void assertResponse(String url, Response response) {
106      assertEquals("Incorrect response code from " + url, 200, response.getStatus());
107    }
108}

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

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.consumingrest.ConsumingRestTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.59 sec - in it.io.openliberty.guides.consumingrest.ConsumingRestTest

Results :

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

Great work! You’re done!

You have just accessed a simple RESTful web service and consumed its resources 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

Copied to clipboard
Copy file contents
Git clone this repo to get going right away:
git clone https://github.com/OpenLiberty/guide-rest-client-java.git
Copy github clone command
Copied to clipboard

Nice work! Where to next?

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

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like