Injecting dependencies into microservices

duration 15 minutes

Prerequisites:

Learn how to use Contexts and Dependency Injection (CDI) to manage scopes and inject dependencies into microservices.

What you’ll learn

You will learn how to use Contexts and Dependency Injection (CDI) to manage scopes and inject dependencies in a simple inventory management application.

The application that you will be working with is an inventory service, which stores the information about various JVMs that run on different systems. Whenever a request is made to the inventory service to retrieve the JVM system properties of a particular host, the inventory service communicates with the system service on that host to get these system properties. The system properties are then stored and returned.

You will use scopes to bind objects in this application to their well-defined contexts. CDI provides a variety of scopes for you to work with and while you will not use all of them in this guide, there is one for almost every scenario that you may encounter. Scopes are defined by using CDI annotations. You will also use dependency injection to inject one bean into another to make use of its functionalities. This enables you to inject the bean in its specified context without having to instantiate it yourself.

The implementation of the application and its services are provided for you in the start/src directory. The system service can be found in the start/src/main/java/io/openliberty/guides/system directory, and the inventory service can be found in the start/src/main/java/io/openliberty/guides/inventory directory. If you want to learn more about RESTful web services and how to build them, see Creating a RESTful web service for details about how to build the system service. The inventory service is built in a similar way.

What is CDI?

Contexts and Dependency Injection (CDI) defines a rich set of complementary services that improve the application structure. The most fundamental services that are provided by CDI are contexts that bind the lifecycle of stateful components to well-defined contexts, and dependency injection that is the ability to inject components into an application in a typesafe way. With CDI, the container does all the daunting work of instantiating dependencies, and controlling exactly when and how these components are instantiated and destroyed.

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-cdi-intro.git
cd guide-cdi-intro

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

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

Try what you’ll build

The finish directory in the root of this guide contains the finished inventory 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:

mvn liberty:run

Point your browser to the http://localhost:9080/inventory/systems URL. This is the starting point of the inventory service and it displays the current contents of the inventory. As you might expect, these are empty since nothing is stored in the inventory yet. Next, point your browser to the http://localhost:9080/inventory/systems/localhost URL. You see a result in JSON format with the system properties of your local JVM. When you visit this URL, these system properties are automatically stored in the inventory. Go back to http://localhost:9080/inventory/systems and you see a new entry for localhost. For simplicity, only the OS name and username are shown here for each host. You can repeat this process for your own hostname or any other machine that is running the system service.

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

mvn liberty:stop

Handling dependencies in the application

You will use CDI to inject dependencies into the inventory manager application and learn how to manage the life cycles of your objects.

Managing scopes and contexts

Navigate to the start directory to begin.

Start Open Liberty in development mode, which starts the Open Liberty server and listens for file changes:

mvn liberty:dev
Create the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.inventory;
14
15import java.util.ArrayList;
16import java.util.Collections;
17import java.util.List;
18import java.util.Properties;
19import io.openliberty.guides.inventory.model.InventoryList;
20import io.openliberty.guides.inventory.model.SystemData;
21import javax.enterprise.context.ApplicationScoped;
22
23// tag::ApplicationScoped[]
24@ApplicationScoped
25// end::ApplicationScoped[]
26public class InventoryManager {
27
28  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
29
30  // tag::add[]
31  public void add(String hostname, Properties systemProps) {
32    Properties props = new Properties();
33    props.setProperty("os.name", systemProps.getProperty("os.name"));
34    props.setProperty("user.name", systemProps.getProperty("user.name"));
35
36    SystemData system = new SystemData(hostname, props);
37    if (!systems.contains(system)) {
38      systems.add(system);
39    }
40  }
41  // end::add[]
42
43  // tag::list[]
44  public InventoryList list() {
45    return new InventoryList(systems);
46  }
47  // end::list[]
48}

This bean contains two simple functions. The add() function is for adding entries to the inventory. The list() function is for listing all the entries currently stored in the inventory.

This bean must be persistent between all of the clients, which means multiple clients need to share the same instance. To achieve this by using CDI, you can simply add the @ApplicationScoped annotation onto the class.

This annotation indicates that this particular bean is to be initialized once per application. By making it application-scoped, the container ensures that the same instance of the bean is used whenever it is injected into the application.

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

InventoryResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.inventory;
14
15import java.util.Properties;
16import javax.enterprise.context.ApplicationScoped;
17import javax.inject.Inject;
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.PathParam;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23import javax.ws.rs.core.Response;
24import io.openliberty.guides.inventory.model.InventoryList;
25import io.openliberty.guides.inventory.client.SystemClient;
26
27// tag::ApplicationScoped[]
28@ApplicationScoped
29// end::ApplicationScoped[]
30// tag::endpoint[]
31@Path("/systems")
32// end::endpoint[]
33// tag::InventoryResource[]
34public class InventoryResource {
35
36  // tag::inject[]
37  @Inject
38  // end::inject[]
39  InventoryManager manager;
40
41  // tag::inject2[]
42  @Inject
43  // end::inject2[]
44  SystemClient systemClient;
45
46  @GET
47  @Path("/{hostname}")
48  @Produces(MediaType.APPLICATION_JSON)
49  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
50    // Get properties for host
51    // tag::properties[]
52    Properties props = systemClient.getProperties(hostname);
53    // end::properties[]
54    if (props == null) {
55      return Response.status(Response.Status.NOT_FOUND)
56                     .entity("ERROR: Unknown hostname or the system service may not be "
57                             + "running on " + hostname)
58                     .build();
59    }
60
61    // Add to inventory
62    // tag::managerAdd[]
63    manager.add(hostname, props);
64    // end::managerAdd[]
65    return Response.ok(props).build();
66  }
67
68  @GET
69  @Produces(MediaType.APPLICATION_JSON)
70  public InventoryList listContents() {
71    // tag::managerList[]
72    return manager.list();
73    // end::managerList[]
74  }
75}
76// tag::InventoryResource[]

The inventory resource is a RESTful service that is served at the inventory/systems endpoint.

Annotating a class with the @ApplicationScoped annotation indicates that the bean is initialized once and is shared between all requests while the application runs.

If you want this bean to be initialized once for every request, you can annotate the class with the @RequestScoped annotation instead. With the @RequestScoped annotation, the bean is instantiated when the request is received and destroyed when a response is sent back to the client. A request scope is short-lived.

Injecting a dependency

Refer to the InventoryResource class you created above.

The @Inject annotation indicates a dependency injection. You are injecting your InventoryManager and SystemClient beans into the InventoryResource class. This injects the beans in their specified context and makes all of their functionalities available without the need of instantiating them yourself. The injected bean InventoryManager can then be invoked directly through the manager.add(hostname, props) and manager.list() function calls. The injected bean SystemClient can be invoked through the systemClient.getProperties(hostname) function call.

Finally, you have a client component SystemClient that can be found in the src/main/java/io/openliberty/guides/inventory/client directory. This class communicates with the system service to retrieve the JVM system properties for a particular host that exposes them. This class also contains detailed Javadocs that you can read for reference.

Your inventory application is now completed.

InventoryResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.inventory;
14
15import java.util.Properties;
16import javax.enterprise.context.ApplicationScoped;
17import javax.inject.Inject;
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.PathParam;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23import javax.ws.rs.core.Response;
24import io.openliberty.guides.inventory.model.InventoryList;
25import io.openliberty.guides.inventory.client.SystemClient;
26
27// tag::ApplicationScoped[]
28@ApplicationScoped
29// end::ApplicationScoped[]
30// tag::endpoint[]
31@Path("/systems")
32// end::endpoint[]
33// tag::InventoryResource[]
34public class InventoryResource {
35
36  // tag::inject[]
37  @Inject
38  // end::inject[]
39  InventoryManager manager;
40
41  // tag::inject2[]
42  @Inject
43  // end::inject2[]
44  SystemClient systemClient;
45
46  @GET
47  @Path("/{hostname}")
48  @Produces(MediaType.APPLICATION_JSON)
49  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
50    // Get properties for host
51    // tag::properties[]
52    Properties props = systemClient.getProperties(hostname);
53    // end::properties[]
54    if (props == null) {
55      return Response.status(Response.Status.NOT_FOUND)
56                     .entity("ERROR: Unknown hostname or the system service may not be "
57                             + "running on " + hostname)
58                     .build();
59    }
60
61    // Add to inventory
62    // tag::managerAdd[]
63    manager.add(hostname, props);
64    // end::managerAdd[]
65    return Response.ok(props).build();
66  }
67
68  @GET
69  @Produces(MediaType.APPLICATION_JSON)
70  public InventoryList listContents() {
71    // tag::managerList[]
72    return manager.list();
73    // end::managerList[]
74  }
75}
76// tag::InventoryResource[]

SystemClient.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2019 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.inventory.client;
 14
 15import javax.enterprise.context.ApplicationScoped;
 16import javax.inject.Inject;
 17import javax.ws.rs.client.Client;
 18import javax.ws.rs.client.ClientBuilder;
 19import javax.ws.rs.client.Invocation.Builder;
 20import javax.ws.rs.core.HttpHeaders;
 21import javax.ws.rs.core.MediaType;
 22import javax.ws.rs.core.Response;
 23import javax.ws.rs.core.Response.Status;
 24import java.util.Properties;
 25import java.net.URI;
 26import org.eclipse.microprofile.config.inject.ConfigProperty;
 27
 28@ApplicationScoped
 29public class SystemClient {
 30
 31  // Constants for building URI to the system service.
 32  private final String SYSTEM_PROPERTIES = "/system/properties";
 33  private final String PROTOCOL = "http";
 34
 35  @Inject
 36  @ConfigProperty(name = "system.http.port")
 37  String SYS_HTTP_PORT;
 38
 39  // Wrapper function that gets properties
 40  public Properties getProperties(String hostname) {
 41    String url = buildUrl(PROTOCOL, hostname, Integer.valueOf(SYS_HTTP_PORT), SYSTEM_PROPERTIES);
 42    Builder clientBuilder = buildClientBuilder(url);
 43    return getPropertiesHelper(clientBuilder);
 44  }
 45
 46  // tag::doc[]
 47  /**
 48   * Builds the URI string to the system service for a particular host.
 49   * @param protocol
 50   *          - http or https.
 51   * @param host
 52   *          - name of host.
 53   * @param port
 54   *          - port number.
 55   * @param path
 56   *          - Note that the path needs to start with a slash!!!
 57   * @return String representation of the URI to the system properties service.
 58   */
 59  // end::doc[]
 60  protected String buildUrl(String protocol, String host, int port, String path) {
 61    try {
 62      URI uri = new URI(protocol, null, host, port, path, null, null);
 63      return uri.toString();
 64    } catch (Exception e) {
 65      System.err.println("Exception thrown while building the URL: " + e.getMessage());
 66      return null;
 67    }
 68  }
 69
 70  // Method that creates the client builder
 71  protected Builder buildClientBuilder(String urlString) {
 72    try {
 73      Client client = ClientBuilder.newClient();
 74      Builder builder = client.target(urlString).request();
 75      return builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
 76    } catch (Exception e) {
 77      System.err.println("Exception thrown while building the client: " + e.getMessage());
 78      return null;
 79    }
 80  }
 81
 82  // Helper method that processes the request
 83  protected Properties getPropertiesHelper(Builder builder) {
 84    try {
 85      Response response = builder.get();
 86      if (response.getStatus() == Status.OK.getStatusCode()) {
 87        return response.readEntity(Properties.class);
 88      } else {
 89        System.err.println("Response Status is not OK.");
 90      }
 91    } catch (RuntimeException e) {
 92      System.err.println("Runtime exception: " + e.getMessage());
 93    } catch (Exception e) {
 94      System.err.println("Exception thrown while invoking the request: " + e.getMessage());
 95    }
 96    return null;
 97  }
 98
 99}

Building and running the application

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

You can find the inventory and system services at the following URLs:

Testing the inventory application

While you can test your application manually, you should rely on automated tests since they trigger a failure whenever a code change introduces a defect. Since the application is a RESTful web service application, you can use JUnit and the RESTful web service Client API to write tests. In testing the functionality of the application, the scopes and dependencies are being tested.

Create the InventoryEndpointIT class.
src/test/java/it/io/openliberty/guides/inventory/InventoryEndpointIT.java

The @BeforeAll annotation is placed on a method that runs before any of the test cases. In this case, the oneTimeSetup() method retrieves the port number for the Open Liberty server and builds a base URL string that is used throughout the tests.

The @BeforeEach and @AfterEach annotations are placed on methods that run before and after every test case. These methods are generally used to perform any setup and teardown tasks. In this case, the setup() method creates a JAX-RS client, which makes HTTP requests to the inventory service. This client must also be registered with a JSON-P provider (JsrJsonpProvider) to process JSON resources. The teardown() method simply destroys this client instance.

See the following descriptions of the test cases:

  • testHostRegistration() verifies that a host is correctly added to the inventory.

  • testSystemPropertiesMatch() verifies that the JVM system properties returned by the system service match the ones stored in the inventory service.

  • testUnknownHost() verifies that an unknown host or a host that does not expose their JVM system properties is correctly handled as an error.

To force these test cases to run in a particular order, annotate your InventoryEndpointIT test class with the @TestMethodOrder(OrderAnnotation.class) annotation. OrderAnnotation.class runs test methods in numerical order, according to the values specified in the @Order annotation. You can also create a custom MethodOrderer class or use built-in MethodOrderer implementations, such as OrderAnnotation.class, Alphanumeric.class, or Random.class. Label your test cases with the @Test annotation so that they automatically run when your test class runs.

Finally, the src/test/java/it/io/openliberty/guides/system/SystemEndpointIT.java file is included for you to test the basic functionality of the system service. If a test failure occurs, then you might have introduced a bug into the code.

InventoryEndpointIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2019 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::testClass[]
 14package it.io.openliberty.guides.inventory;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17import static org.junit.jupiter.api.Assertions.assertTrue;
 18
 19import javax.json.JsonArray;
 20import javax.json.JsonObject;
 21import javax.ws.rs.client.Client;
 22import javax.ws.rs.client.ClientBuilder;
 23import javax.ws.rs.core.MediaType;
 24import javax.ws.rs.core.Response;
 25
 26import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 27import org.junit.jupiter.api.AfterEach;
 28import org.junit.jupiter.api.BeforeEach;
 29import org.junit.jupiter.api.BeforeAll;
 30// tag::MethodOrderer[]
 31import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 32// end::MethodOrderer[]
 33import org.junit.jupiter.api.Order;
 34import org.junit.jupiter.api.Test;
 35import org.junit.jupiter.api.TestMethodOrder;
 36
 37// tag::TestMethodOrder[]
 38@TestMethodOrder(OrderAnnotation.class)
 39// end::TestMethodOrder[]
 40public class InventoryEndpointIT {
 41
 42  private static String port;
 43  private static String baseUrl;
 44
 45  private Client client;
 46
 47  private final String SYSTEM_PROPERTIES = "system/properties";
 48  private final String INVENTORY_SYSTEMS = "inventory/systems";
 49
 50  // tag::BeforeAll[]
 51  @BeforeAll
 52  // end::BeforeAll[]
 53  // tag::oneTimeSetup[]
 54  public static void oneTimeSetup() {
 55    port = System.getProperty("http.port");
 56    baseUrl = "http://localhost:" + port + "/";
 57  }
 58  // end::oneTimeSetup[]
 59
 60  // tag::BeforeEach[]
 61  @BeforeEach
 62  // end::BeforeEach[]
 63  // tag::setup[]
 64  public void setup() {
 65    client = ClientBuilder.newClient();
 66    // tag::JsrJsonpProvider[]
 67    client.register(JsrJsonpProvider.class);
 68    // end::JsrJsonpProvider[]
 69  }
 70  // end::setup[]
 71
 72  // tag::AfterEach[]
 73  @AfterEach
 74  // end::AfterEach[]
 75  // tag::teardown[]
 76  public void teardown() {
 77    client.close();
 78  }
 79  // end::teardown[]
 80
 81  // tag::tests[]
 82  // tag::Test1[]
 83  @Test
 84  // end::Test1[]
 85  // tag::Order1[]
 86  @Order(1)
 87  // end::Order1[]
 88  // tag::testHostRegistration[]
 89  public void testHostRegistration() {
 90    this.visitLocalhost();
 91
 92    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 93    this.assertResponse(baseUrl, response);
 94
 95    JsonObject obj = response.readEntity(JsonObject.class);
 96
 97    JsonArray systems = obj.getJsonArray("systems");
 98
 99    boolean localhostExists = false;
100    for (int n = 0; n < systems.size(); n++) {
101      localhostExists = systems.getJsonObject(n)
102                                .get("hostname").toString()
103                                .contains("localhost");
104      if (localhostExists) {
105          break;
106      }
107    }
108    assertTrue(localhostExists,
109              "A host was registered, but it was not localhost");
110
111    response.close();
112  }
113  // end::testHostRegistration[]
114
115  // tag::Test2[]
116  @Test
117  // end::Test2[]
118  // tag::Order2[]
119  @Order(2)
120  // end::Order2[]
121  // tag::testSystemPropertiesMatch[]
122  public void testSystemPropertiesMatch() {
123    Response invResponse = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
124    Response sysResponse = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
125
126    this.assertResponse(baseUrl, invResponse);
127    this.assertResponse(baseUrl, sysResponse);
128
129    JsonObject jsonFromInventory = (JsonObject) invResponse.readEntity(JsonObject.class)
130                                                           .getJsonArray("systems")
131                                                           .getJsonObject(0)
132                                                           .get("properties");
133
134    JsonObject jsonFromSystem = sysResponse.readEntity(JsonObject.class);
135
136    String osNameFromInventory = jsonFromInventory.getString("os.name");
137    String osNameFromSystem = jsonFromSystem.getString("os.name");
138    this.assertProperty("os.name", "localhost", osNameFromSystem,
139                        osNameFromInventory);
140
141    String userNameFromInventory = jsonFromInventory.getString("user.name");
142    String userNameFromSystem = jsonFromSystem.getString("user.name");
143    this.assertProperty("user.name", "localhost", userNameFromSystem,
144                        userNameFromInventory);
145
146    invResponse.close();
147    sysResponse.close();
148  }
149  // end::testSystemPropertiesMatch[]
150
151  // tag::Test3[]
152  @Test
153  // end::Test3[]
154  // tag::Order3[]
155  @Order(3)
156  // end::Order3[]
157  // tag::testUnknownHost[]
158  public void testUnknownHost() {
159    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
160    this.assertResponse(baseUrl, response);
161
162    Response badResponse = client.target(baseUrl + INVENTORY_SYSTEMS + "/"
163        + "badhostname").request(MediaType.APPLICATION_JSON).get();
164
165    String obj = badResponse.readEntity(String.class);
166
167    boolean isError = obj.contains("ERROR");
168    assertTrue(isError,
169              "badhostname is not a valid host but it didn't raise an error");
170
171    response.close();
172    badResponse.close();
173  }
174  // end::testUnknownHost[]
175  // end::tests[]
176
177  private Response getResponse(String url) {
178    return client.target(url).request().get();
179  }
180
181  private void assertResponse(String url, Response response) {
182    assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
183  }
184
185  private void assertProperty(String propertyName, String hostname,
186      String expected, String actual) {
187    assertEquals(expected, actual, "JVM system property [" + propertyName + "] "
188        + "in the system service does not match the one stored in "
189        + "the inventory service for " + hostname);
190  }
191
192  private void visitLocalhost() {
193    Response response = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
194    this.assertResponse(baseUrl, response);
195    response.close();
196
197    Response targetResponse = client.target(baseUrl + INVENTORY_SYSTEMS
198        + "/localhost").request().get();
199    targetResponse.close();
200  }
201}
202// end::testClass[]

SystemEndpointIT.java

 1//tag::copyright[]
 2/*******************************************************************************
 3* Copyright (c) 2017, 2019 IBM Corporation and others.
 4* All rights reserved. This program and the accompanying materials
 5* are made available under the terms of the Eclipse Public License v1.0
 6* which accompanies this distribution, and is available at
 7* http://www.eclipse.org/legal/epl-v10.html
 8*
 9* Contributors:
10*     IBM Corporation - initial API and implementation
11*******************************************************************************/
12// end::copyright[]
13package it.io.openliberty.guides.system;
14
15import static org.junit.jupiter.api.Assertions.assertEquals;
16import javax.json.JsonObject;
17import javax.ws.rs.client.Client;
18import javax.ws.rs.client.ClientBuilder;
19import javax.ws.rs.client.WebTarget;
20import javax.ws.rs.core.Response;
21
22import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
23import org.junit.jupiter.api.Test;
24
25public class SystemEndpointIT {
26
27 @Test
28 public void testGetProperties() {
29     String port = System.getProperty("http.port");
30     String url = "http://localhost:" + port + "/";
31
32     Client client = ClientBuilder.newClient();
33     client.register(JsrJsonpProvider.class);
34
35     WebTarget target = client.target(url + "system/properties");
36     Response response = target.request().get();
37
38     assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
39
40     JsonObject obj = response.readEntity(JsonObject.class);
41
42     assertEquals(System.getProperty("os.name"),
43                  obj.getString("os.name"),
44                  "The system property for the local and remote JVM should match");
45
46     response.close();
47 }
48}

Running the tests

Since you started Open Liberty in development 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.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.99 sec - in it.io.openliberty.guides.system.SystemEndpointIT
Running it.io.openliberty.guides.inventory.InventoryEndpointIT
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.325 sec - in it.io.openliberty.guides.inventory.InventoryEndpointIT

Results :

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

To see whether the tests detect a failure, change the endpoint for the inventory service in the src/main/java/io/openliberty/guides/inventory/InventoryResource.java file to something else. Then, run the tests again to see that a test failure occurs.

InventoryResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.inventory;
14
15import java.util.Properties;
16import javax.enterprise.context.ApplicationScoped;
17import javax.inject.Inject;
18import javax.ws.rs.GET;
19import javax.ws.rs.Path;
20import javax.ws.rs.PathParam;
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23import javax.ws.rs.core.Response;
24import io.openliberty.guides.inventory.model.InventoryList;
25import io.openliberty.guides.inventory.client.SystemClient;
26
27// tag::ApplicationScoped[]
28@ApplicationScoped
29// end::ApplicationScoped[]
30// tag::endpoint[]
31@Path("/systems")
32// end::endpoint[]
33// tag::InventoryResource[]
34public class InventoryResource {
35
36  // tag::inject[]
37  @Inject
38  // end::inject[]
39  InventoryManager manager;
40
41  // tag::inject2[]
42  @Inject
43  // end::inject2[]
44  SystemClient systemClient;
45
46  @GET
47  @Path("/{hostname}")
48  @Produces(MediaType.APPLICATION_JSON)
49  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
50    // Get properties for host
51    // tag::properties[]
52    Properties props = systemClient.getProperties(hostname);
53    // end::properties[]
54    if (props == null) {
55      return Response.status(Response.Status.NOT_FOUND)
56                     .entity("ERROR: Unknown hostname or the system service may not be "
57                             + "running on " + hostname)
58                     .build();
59    }
60
61    // Add to inventory
62    // tag::managerAdd[]
63    manager.add(hostname, props);
64    // end::managerAdd[]
65    return Response.ok(props).build();
66  }
67
68  @GET
69  @Produces(MediaType.APPLICATION_JSON)
70  public InventoryList listContents() {
71    // tag::managerList[]
72    return manager.list();
73    // end::managerList[]
74  }
75}
76// tag::InventoryResource[]

When you are done checking out the service, exit development mode by typing q in the shell session where you ran the server, and then press the enter/return key.

Great work! You’re done!

You just used CDI services in Open Liberty to build a simple inventory application.

Guide Attribution

Injecting dependencies into microservices by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star