Configuring microservices

duration 20 minutes

Prerequisites:

Learn how to provide external configuration to microservices using MicroProfile Config.

What you’ll learn

You will learn how to externalize and inject both static and dynamic configuration properties for microservices using MicroProfile Config.

You will learn to aggregate multiple configuration sources, assign prioritization values to these sources, merge configuration values, and create custom configuration sources.

The application that you will be working with is an inventory service which stores the information about various JVMs running on different hosts. Whenever a request is made to the inventory service to retrieve the JVM system properties of a particular host, the inventory service will communicate with the system service on that host to get these system properties. You will add configuration properties to simulate if a service is down for maintenance.

Getting started

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

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

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

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

Try what you’ll build

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

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

mvn liberty:run

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

The defaultServer server is ready to run a smarter planet.

You can access the following two microservices to test their availability:

In addition, you can access a third microservice, which retrieves and aggregates all of the configuration properties and sources that have been added throughout this guide. This is available at:

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

Ordering multiple configuration sources

Now, 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

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

Press the Enter key to run tests on demand.

The development mode holds your command prompt to listen for file changes. You need to open another command prompt to continue, or simply open the project in your editor.

MicroProfile Config combines configuration properties from multiple sources, each known as a ConfigSource. Each ConfigSource has a specified priority, defined by its config_ordinal value.

A higher ordinal value means that the values taken from this ConfigSource will override values from ConfigSources with a lower ordinal value.

There are three default configuration sources as following:

  • System properties has a default ordinal of 400. (e.g. bootstrap.properties file)

  • Environment variables have a default ordinal of 300. (e.g. server.env file)

  • The META-INF/microprofile-config.properties configuration property file on the classpath has a default ordinal of 100.

Access the src/main/resources/META-INF/microprofile-config.properties local configuration file. This configuration file is the default configuration source for an application that uses MicroProfile Config.

microprofile-config.properties

 1# tag::all-props[]
 2# tag::ordinal[]
 3config_ordinal=100
 4# end::ordinal[]
 5# tag::inventory-port-number[]
 6io_openliberty_guides_port_number=9080
 7# end::inventory-port-number[]
 8# tag::inventory-in-maintenance[]
 9io_openliberty_guides_inventory_inMaintenance=false
10# end::inventory-in-maintenance[]
11# tag::system-in-maintenance[]
12io_openliberty_guides_system_inMaintenance=false
13# tag::system-in-maintenance[]
14# tag::test-config-overwrite[]
15io_openliberty_guides_testConfigOverwrite=DefaultSource
16# tag::test-config-overwrite[]
17# end::all-props[]

Injecting static configuration

The MicroProfile Config API is included in the MicroProfile dependency that is specified in your pom.xml file. Look for the dependency with the microprofile artifact ID. This dependency provides a library that allows you to use the MicroProfile Config API to externalize configurations for your microservices. The mpConfig feature is also enabled in the src/main/liberty/config/server.xml file.

pom.xml

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

server.xml

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

Now navigate to the src/main/resources/META-INF/microprofile-config.properties local configuration file to check some static configuration. This configuration file is the default configuration source for an application that uses MicroProfile Config.

The io_openliberty_guides_port_number property that has already been defined in this file, determines the port number of the REST service.

microprofile-config.properties

 1# tag::all-props[]
 2# tag::ordinal[]
 3config_ordinal=100
 4# end::ordinal[]
 5# tag::inventory-port-number[]
 6io_openliberty_guides_port_number=9080
 7# end::inventory-port-number[]
 8# tag::inventory-in-maintenance[]
 9io_openliberty_guides_inventory_inMaintenance=false
10# end::inventory-in-maintenance[]
11# tag::system-in-maintenance[]
12io_openliberty_guides_system_inMaintenance=false
13# tag::system-in-maintenance[]
14# tag::test-config-overwrite[]
15io_openliberty_guides_testConfigOverwrite=DefaultSource
16# tag::test-config-overwrite[]
17# end::all-props[]

To use this configuration property,

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

InventoryConfig.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::config-class[]
14package io.openliberty.guides.inventory;
15
16import javax.enterprise.context.RequestScoped;
17import javax.inject.Inject;
18import javax.inject.Provider;
19import org.eclipse.microprofile.config.inject.ConfigProperty;
20import io.openliberty.guides.config.Email;
21
22@RequestScoped
23public class InventoryConfig {
24
25  // tag::port-number[]
26  // tag::inject-port-number[]
27  @Inject
28  // end::inject-port-number[]
29  // tag::guides-port-number[]
30  @ConfigProperty(name = "io_openliberty_guides_port_number")
31  // end::guides-port-number[]
32  private int portNumber;
33
34  // end::port-number[]
35  // tag::build-in-converter[]
36  // tag::inject-inMaintenance[]
37  // tag::inject[]
38  @Inject
39  // end::inject[]
40  // tag::configPropety[]
41  @ConfigProperty(name = "io_openliberty_guides_inventory_inMaintenance")
42  // end::configPropety[]
43  // end::inject-inMaintenance[]
44  private Provider<Boolean> inMaintenance;
45
46  // end::build-in-converter[]
47  // tag::custom-converter[]
48  @Inject
49  @ConfigProperty(name = "io_openliberty_guides_email")
50  private Provider<Email> email;
51  // end::custom-converter[]
52
53  // tag::getPortNumber[]
54  public int getPortNumber() {
55    return portNumber;
56  }
57  // end::getPortNumber[]
58
59  // tag::isInMaintenance[]
60  public boolean isInMaintenance() {
61    // tag::inMaintenanceGet[]
62    return inMaintenance.get();
63    // end::inMaintenanceGet[]
64  }
65  // end::isInMaintenance[]
66
67  // tag::getEmail[]
68  public Email getEmail() {
69    return email.get();
70  }
71  // end::getEmail[]
72}
73// end::config-class[]

Inject the io_openliberty_guides_port_number property, and add the getPortNumber() class method to the InventoryConfig.java file.

The @Inject annotation injects the port number directly, the injection value is static and fixed on application starting.

The getPortNumber() method directly returns the value of portNumber because it has been injected.

Injecting dynamic configuration

Note that three default config sources mentioned above are static and fixed on application starting, so the properties within them cannot be modified while the server is running. However, you can externalize configuration data out of the application package, through the creation of custom configuration sources, so that the service updates configuration changes dynamically.

Creating custom configuration sources

CustomConfigSource.json

1{
2  "config_ordinal": 150,
3  "io_openliberty_guides_email": "[email protected]",
4  "io_openliberty_guides_inventory_inMaintenance": false,
5  "io_openliberty_guides_system_inMaintenance": false,
6  "io_openliberty_guides_testConfigOverwrite": "CustomSource"
7}

Custom configuration sources can be created by implementing the org.eclipse.microprofile.config.spi.ConfigSource interface and using the java.util.ServiceLoader mechanism.

A CustomConfigSource.json JSON file has already been created in the resources directory. This JSON file simulates a remote configuration resource in real life. This file contains 4 custom config properties and has an ordinal of 150. To use these properties in the application, the data object needs to be transformed from this JSON file to the configuration for your application.

To link this JSON file to your application and to implement the ConfigSource interface,

Create the CustomConfigSource class.
src/main/java/io/openliberty/guides/config/CustomConfigSource.java

CustomConfigSource.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::customConfig[]
 14package io.openliberty.guides.config;
 15
 16import javax.json.stream.JsonParser;
 17import javax.json.stream.JsonParser.Event;
 18import javax.json.Json;
 19import java.math.BigDecimal;
 20import java.util.*;
 21import java.io.StringReader;
 22
 23import java.io.BufferedReader;
 24import java.io.FileReader;
 25import org.eclipse.microprofile.config.spi.ConfigSource;
 26
 27/**
 28 * User-provided ConfigSources are dynamic.
 29 * The getProperties() method will be periodically invoked by the runtime
 30 * to retrieve up-to-date values. The frequency is controlled by
 31 * the microprofile.config.refresh.rate Java system property,
 32 * which is in milliseconds and can be customized.
 33 */
 34public class CustomConfigSource implements ConfigSource {
 35
 36  String fileLocation = System.getProperty("user.dir").split("target")[0]
 37      + "resources/CustomConfigSource.json";
 38
 39  @Override
 40  public int getOrdinal() {
 41    return Integer.parseInt(getProperties().get("config_ordinal"));
 42  }
 43
 44  @Override
 45  public Set<String> getPropertyNames() {
 46    return getProperties().keySet();
 47  }
 48
 49  @Override
 50  public String getValue(String key) {
 51    return getProperties().get(key);
 52  }
 53
 54  @Override
 55  public String getName() {
 56    return "Custom Config Source: file:" + this.fileLocation;
 57  }
 58
 59  // tag::getProperties[]
 60  public Map<String, String> getProperties() {
 61    Map<String, String> m = new HashMap<String, String>();
 62    String jsonData = this.readFile(this.fileLocation);
 63    JsonParser parser = Json.createParser(new StringReader(jsonData));
 64    String key = null;
 65    while (parser.hasNext()) {
 66      final Event event = parser.next();
 67      switch (event) {
 68      case KEY_NAME:
 69        key = parser.getString();
 70        break;
 71      case VALUE_STRING:
 72        String string = parser.getString();
 73        m.put(key, string);
 74        break;
 75      case VALUE_NUMBER:
 76        BigDecimal number = parser.getBigDecimal();
 77        m.put(key, number.toString());
 78        break;
 79      case VALUE_TRUE:
 80        m.put(key, "true");
 81        break;
 82      case VALUE_FALSE:
 83        m.put(key, "false");
 84        break;
 85      default:
 86        break;
 87      }
 88    }
 89    parser.close();
 90    return m;
 91  }
 92  // end::getProperties[]
 93
 94  public String readFile(String fileName) {
 95    String result = "";
 96    try {
 97      BufferedReader br = new BufferedReader(new FileReader(fileName));
 98      StringBuilder sb = new StringBuilder();
 99      String line = br.readLine();
100      while (line != null) {
101        sb.append(line);
102        line = br.readLine();
103      }
104      result = sb.toString();
105      br.close();
106    } catch (Exception e) {
107      e.printStackTrace();
108    }
109    return result;
110  }
111}
112// end::customConfig[]

The getProperties() method reads the key value pairs from the resources/CustomConfigSource.json JSON file and writes the information into a map.

Finally, register the custom configuration source.

Create the configuration file.
src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource

org.eclipse.microprofile.config.spi.ConfigSource

1io.openliberty.guides.config.CustomConfigSource

Add the fully qualified class name of the configuration source into it.

Enabling dynamic configuration injection

Now that the custom configuration source has successfully been set up, you can enable dynamic configuration injection of the properties being set in this ConfigSource. To enable this dynamic injection,

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

InventoryConfig.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::config-class[]
14package io.openliberty.guides.inventory;
15
16import javax.enterprise.context.RequestScoped;
17import javax.inject.Inject;
18import javax.inject.Provider;
19import org.eclipse.microprofile.config.inject.ConfigProperty;
20import io.openliberty.guides.config.Email;
21
22@RequestScoped
23public class InventoryConfig {
24
25  // tag::port-number[]
26  // tag::inject-port-number[]
27  @Inject
28  // end::inject-port-number[]
29  // tag::guides-port-number[]
30  @ConfigProperty(name = "io_openliberty_guides_port_number")
31  // end::guides-port-number[]
32  private int portNumber;
33
34  // end::port-number[]
35  // tag::build-in-converter[]
36  // tag::inject-inMaintenance[]
37  // tag::inject[]
38  @Inject
39  // end::inject[]
40  // tag::configPropety[]
41  @ConfigProperty(name = "io_openliberty_guides_inventory_inMaintenance")
42  // end::configPropety[]
43  // end::inject-inMaintenance[]
44  private Provider<Boolean> inMaintenance;
45
46  // end::build-in-converter[]
47  // tag::custom-converter[]
48  @Inject
49  @ConfigProperty(name = "io_openliberty_guides_email")
50  private Provider<Email> email;
51  // end::custom-converter[]
52
53  // tag::getPortNumber[]
54  public int getPortNumber() {
55    return portNumber;
56  }
57  // end::getPortNumber[]
58
59  // tag::isInMaintenance[]
60  public boolean isInMaintenance() {
61    // tag::inMaintenanceGet[]
62    return inMaintenance.get();
63    // end::inMaintenanceGet[]
64  }
65  // end::isInMaintenance[]
66
67  // tag::getEmail[]
68  public Email getEmail() {
69    return email.get();
70  }
71  // end::getEmail[]
72}
73// end::config-class[]

Inject the io_openliberty_guides_inventory_inMaintenance property, and add the isInMaintenance() class method.

The @Inject and @ConfigProperty annotations inject the io_openliberty_guides_inventory_inMaintenance configuration property from the CustomConfigSource.json file. The Provider<> interface used, forces the service to retrieve the inMaintenance value just in time. This retrieval of the value just in time makes the config injection dynamic and able to change without having to restart the application.

Every time that you invoke the inMaintenance.get() method, the Provider<> interface picks up the latest value of the io_openliberty_guides_inventory_inMaintenance property from configuration sources.

CustomConfigSource.json

1{
2  "config_ordinal": 150,
3  "io_openliberty_guides_email": "[email protected]",
4  "io_openliberty_guides_inventory_inMaintenance": false,
5  "io_openliberty_guides_system_inMaintenance": false,
6  "io_openliberty_guides_testConfigOverwrite": "CustomSource"
7}

Creating custom converters

Configuration values are purely Strings. MicroProfile Config API has built-in converters that automatically converts configured Strings into target types such as int, Integer, boolean, Boolean, float, Float, double and Double. Therefore, in the previous section, it is type-safe to directly set the variable type to Provider<Boolean>.

To convert configured Strings to an arbitrary class type, such as the Email class type,

Replace the Email Class.
src/main/java/io/openliberty/guides/config/Email.java

Email.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
14package io.openliberty.guides.config;
15
16// tag::email[]
17public class Email {
18  private String name;
19  private String domain;
20
21  public Email(String value) {
22    String[] components = value.split("@");
23    if (components.length == 2) {
24      name = components[0];
25      domain = components[1];
26    }
27  }
28
29  public String getEmailName() {
30    return name;
31  }
32
33  public String getEmailDomain() {
34    return domain;
35  }
36
37  public String toString() {
38    return name + "@" + domain;
39  }
40}
41// end::email[]

To use this Email class type, add a custom converter by implementing the generic interface org.eclipse.microprofile.config.spi.Converter<T>. The Type parameter of the interface is the target type the String is converted to.

Create the CustomEmailConverter class.
src/main/java/io/openliberty/guides/config/CustomEmailConverter.java

CustomEmailConverter.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.config;
14
15import org.eclipse.microprofile.config.spi.Converter;
16import io.openliberty.guides.config.Email;
17
18// tag::customConfig[]
19public class CustomEmailConverter implements Converter<Email> {
20
21  @Override
22  public Email convert(String value) {
23    return new Email(value);
24  }
25
26}
27// end::customConfig[]

This implements the Converter<T> interface.

To register your implementation,

Create the configuration file.
src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.Converter

org.eclipse.microprofile.config.spi.Converter

1io.openliberty.guides.config.CustomEmailConverter

Add the fully qualified class name of the custom converter into it.

To use the custom Email converter,

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

InventoryConfig.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::config-class[]
14package io.openliberty.guides.inventory;
15
16import javax.enterprise.context.RequestScoped;
17import javax.inject.Inject;
18import javax.inject.Provider;
19import org.eclipse.microprofile.config.inject.ConfigProperty;
20import io.openliberty.guides.config.Email;
21
22@RequestScoped
23public class InventoryConfig {
24
25  // tag::port-number[]
26  // tag::inject-port-number[]
27  @Inject
28  // end::inject-port-number[]
29  // tag::guides-port-number[]
30  @ConfigProperty(name = "io_openliberty_guides_port_number")
31  // end::guides-port-number[]
32  private int portNumber;
33
34  // end::port-number[]
35  // tag::build-in-converter[]
36  // tag::inject-inMaintenance[]
37  // tag::inject[]
38  @Inject
39  // end::inject[]
40  // tag::configPropety[]
41  @ConfigProperty(name = "io_openliberty_guides_inventory_inMaintenance")
42  // end::configPropety[]
43  // end::inject-inMaintenance[]
44  private Provider<Boolean> inMaintenance;
45
46  // end::build-in-converter[]
47  // tag::custom-converter[]
48  @Inject
49  @ConfigProperty(name = "io_openliberty_guides_email")
50  private Provider<Email> email;
51  // end::custom-converter[]
52
53  // tag::getPortNumber[]
54  public int getPortNumber() {
55    return portNumber;
56  }
57  // end::getPortNumber[]
58
59  // tag::isInMaintenance[]
60  public boolean isInMaintenance() {
61    // tag::inMaintenanceGet[]
62    return inMaintenance.get();
63    // end::inMaintenanceGet[]
64  }
65  // end::isInMaintenance[]
66
67  // tag::getEmail[]
68  public Email getEmail() {
69    return email.get();
70  }
71  // end::getEmail[]
72}
73// end::config-class[]

Inject the io_openliberty_guides_email property, and add the getEmail() method.

Adding configuration to the microservice

To use externalized configuration in the inventory service,

Replace 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[]
13// tag::config-methods[]
14package io.openliberty.guides.inventory;
15
16import java.util.Properties;
17
18// CDI
19import javax.enterprise.context.RequestScoped;
20import javax.inject.Inject;
21import javax.ws.rs.GET;
22import javax.ws.rs.Path;
23import javax.ws.rs.PathParam;
24import javax.ws.rs.Produces;
25import javax.ws.rs.core.MediaType;
26import javax.ws.rs.core.Response;
27
28import io.openliberty.guides.inventory.InventoryConfig;
29
30@RequestScoped
31@Path("systems")
32public class InventoryResource {
33
34  @Inject
35  InventoryManager manager;
36
37  // tag::config-injection[]
38  @Inject
39  InventoryConfig inventoryConfig;
40  // end::config-injection[]
41
42  @GET
43  @Path("{hostname}")
44  @Produces(MediaType.APPLICATION_JSON)
45  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
46
47    if (!inventoryConfig.isInMaintenance()) {
48      // tag::config-port[]
49      Properties props = manager.get(hostname, inventoryConfig.getPortNumber());
50      // end::config-port[]
51      if (props == null) {
52        return Response.status(Response.Status.NOT_FOUND)
53                       .entity("ERROR: Unknown hostname or the resource may not be " +
54                               "running on the host machine")
55                       .build();
56      }
57
58      // Add to inventory
59      manager.add(hostname, props);
60      return Response.ok(props).build();
61    } else {
62      // tag::email[]
63      return Response.status(Response.Status.SERVICE_UNAVAILABLE)
64                     .entity("ERROR: Service is currently in maintenance. Contact: " +
65                             inventoryConfig.getEmail().toString())
66                     .build();
67      // end::email[]
68    }
69  }
70
71  @GET
72  @Produces(MediaType.APPLICATION_JSON)
73  public Response listContents() {
74    // tag::isInMaintenance[]
75    if (!inventoryConfig.isInMaintenance()) {
76    // end::isInMaintenance[]
77      return Response.ok(manager.list()).build();
78    } else {
79      return Response.status(Response.Status.SERVICE_UNAVAILABLE)
80                     .entity("ERROR: Service is currently in maintenance. Contact: " +
81                     // tag::getEmail[]
82                             inventoryConfig.getEmail().toString())
83                    // end::getEmail[]
84                     .build();
85    }
86  }
87
88}
89
90// end::config-methods[]

To add configuration to the inventory service, the InventoryConfig object is injected to the existing class.

The port number from the configuration is retrieved by the inventoryConfig.getPortNumber() method and passed to the manager.get() method as a parameter.

To determine whether the inventory service is in maintenance or not (according to the configuration value), inventoryConfig.isInMaintenance() class method is used. If you set the io_openliberty_guides_inventory_inMaintenance property to true in the configuration, the inventory service returns the message, ERROR: Service is currently in maintenance, along with the contact email. The email configuration value can be obtained by calling inventoryConfig.getEmail() method.

CustomConfigSource.json

1{
2  "config_ordinal": 150,
3  "io_openliberty_guides_email": "[email protected]",
4  "io_openliberty_guides_inventory_inMaintenance": false,
5  "io_openliberty_guides_system_inMaintenance": false,
6  "io_openliberty_guides_testConfigOverwrite": "CustomSource"
7}

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.

While the server is running, the following two microservices should be available to access:

You can find the service that retrieves configuration information that is specific to this guide at the following location:

The config_ordinal value of the custom configuration source is set to 150. It overrides configuration values of the default microprofile-config.properties source, which has a config_ordinal value of 100.

CustomConfigSource.json

1{
2  "config_ordinal": 150,
3  "io_openliberty_guides_email": "[email protected]",
4  "io_openliberty_guides_inventory_inMaintenance": false,
5  "io_openliberty_guides_system_inMaintenance": false,
6  "io_openliberty_guides_testConfigOverwrite": "CustomSource"
7}

microprofile-config.properties

 1# tag::all-props[]
 2# tag::ordinal[]
 3config_ordinal=100
 4# end::ordinal[]
 5# tag::inventory-port-number[]
 6io_openliberty_guides_port_number=9080
 7# end::inventory-port-number[]
 8# tag::inventory-in-maintenance[]
 9io_openliberty_guides_inventory_inMaintenance=false
10# end::inventory-in-maintenance[]
11# tag::system-in-maintenance[]
12io_openliberty_guides_system_inMaintenance=false
13# tag::system-in-maintenance[]
14# tag::test-config-overwrite[]
15io_openliberty_guides_testConfigOverwrite=DefaultSource
16# tag::test-config-overwrite[]
17# end::all-props[]

Play with this application by changing configuration values for each property in the resources/CustomConfigSource.json file. Your changes are added dynamically, and you do not need to restart the server. Refresh http://localhost:9080/config to see the dynamic changes.

For example, change io_openliberty_guides_inventory_inMaintenance from false to true, then try to access http://localhost:9080/inventory/systems again. The following message displays: ERROR: Service is currently in maintenance.

Testing the application

Create the ConfigurationIT class.
src/test/java/it/io/openliberty/guides/config/ConfigurationIT.java

ConfigurationIT.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::test[]
 14package it.io.openliberty.guides.config;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17
 18import javax.ws.rs.client.Client;
 19import javax.ws.rs.client.ClientBuilder;
 20import javax.ws.rs.core.Response;
 21
 22import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 23import org.junit.jupiter.api.AfterEach;
 24import org.junit.jupiter.api.BeforeEach;
 25import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 26import org.junit.jupiter.api.Order;
 27import org.junit.jupiter.api.Test;
 28import org.junit.jupiter.api.TestMethodOrder;
 29
 30@TestMethodOrder(OrderAnnotation.class)
 31public class ConfigurationIT {
 32
 33  private String port;
 34  private String baseUrl;
 35  private Client client;
 36
 37  private final String INVENTORY_HOSTS = "inventory/systems";
 38  private final String USER_DIR = System.getProperty("user.dir");
 39  private final String DEFAULT_CONFIG_FILE = USER_DIR
 40      + "/src/main/resources/META-INF/microprofile-config.properties";
 41  private final String CUSTOM_CONFIG_FILE = USER_DIR.split("target")[0]
 42      + "/resources/CustomConfigSource.json";
 43  private final String INV_MAINTENANCE_PROP = "io_openliberty_guides"
 44      + "_inventory_inMaintenance";
 45
 46  @BeforeEach
 47  // tag::setup[]
 48  public void setup() {
 49    port = System.getProperty("default.http.port");
 50    baseUrl = "http://localhost:" + port + "/";
 51    ConfigITUtil.setDefaultJsonFile(CUSTOM_CONFIG_FILE);
 52
 53    client = ClientBuilder.newClient();
 54    client.register(JsrJsonpProvider.class);
 55  }
 56  // end::setup[]
 57
 58  @AfterEach
 59  public void teardown() {
 60    ConfigITUtil.setDefaultJsonFile(CUSTOM_CONFIG_FILE);
 61    client.close();
 62  }
 63
 64  @Test
 65  @Order(1)
 66  // tag::testInitialServiceStatus[]
 67  public void testInitialServiceStatus() {
 68    boolean status = Boolean.valueOf(ConfigITUtil.readPropertyValueInFile(
 69        INV_MAINTENANCE_PROP, DEFAULT_CONFIG_FILE));
 70    if (!status) {
 71      Response response = ConfigITUtil.getResponse(client, baseUrl + INVENTORY_HOSTS);
 72
 73      int expected = Response.Status.OK.getStatusCode();
 74      int actual = response.getStatus();
 75      assertEquals(expected, actual);
 76    } else {
 77      assertEquals(
 78          "ERROR: Service is currently in maintenance. "
 79          + "Contact: [email protected]",
 80          ConfigITUtil.getStringFromURL(client, baseUrl + INVENTORY_HOSTS),
 81          "The Inventory Service should be in maintenance");
 82    }
 83  }
 84  // end::testInitialServiceStatus[]
 85
 86  @Test
 87  @Order(2)
 88  // tag::testPutServiceInMaintenance[]
 89  public void testPutServiceInMaintenance() {
 90    Response response = ConfigITUtil.getResponse(client, baseUrl + INVENTORY_HOSTS);
 91
 92    int expected = Response.Status.OK.getStatusCode();
 93    int actual = response.getStatus();
 94    assertEquals(expected, actual);
 95
 96    ConfigITUtil.switchInventoryMaintenance(CUSTOM_CONFIG_FILE, true);
 97
 98    String error = ConfigITUtil.getStringFromURL(client, baseUrl + INVENTORY_HOSTS);
 99
100    assertEquals(
101        "ERROR: Service is currently in maintenance. "
102        + "Contact: [email protected]",
103        error, "The inventory service should be down in the end");
104  }
105  // end::testPutServiceInMaintenance[]
106
107  @Test
108  @Order(3)
109  // tag::testChangeEmail[]
110  public void testChangeEmail() {
111    ConfigITUtil.switchInventoryMaintenance(CUSTOM_CONFIG_FILE, true);
112
113    String error = ConfigITUtil.getStringFromURL(client, baseUrl + INVENTORY_HOSTS);
114
115    assertEquals(
116        "ERROR: Service is currently in maintenance. "
117        + "Contact: [email protected]",
118        error, "The email should be [email protected] in the beginning");
119
120    ConfigITUtil.changeEmail(CUSTOM_CONFIG_FILE, "[email protected]");
121
122    error = ConfigITUtil.getStringFromURL(client, baseUrl + INVENTORY_HOSTS);
123
124    assertEquals(
125        "ERROR: Service is currently in maintenance. "
126        + "Contact: [email protected]",
127        error, "The email should be [email protected] in the beginning");
128  }
129  // end::testChangeEmail[]
130
131}
132// end::test[]

microprofile-config.properties

 1# tag::all-props[]
 2# tag::ordinal[]
 3config_ordinal=100
 4# end::ordinal[]
 5# tag::inventory-port-number[]
 6io_openliberty_guides_port_number=9080
 7# end::inventory-port-number[]
 8# tag::inventory-in-maintenance[]
 9io_openliberty_guides_inventory_inMaintenance=false
10# end::inventory-in-maintenance[]
11# tag::system-in-maintenance[]
12io_openliberty_guides_system_inMaintenance=false
13# tag::system-in-maintenance[]
14# tag::test-config-overwrite[]
15io_openliberty_guides_testConfigOverwrite=DefaultSource
16# tag::test-config-overwrite[]
17# end::all-props[]

The testInitialServiceStatus() test case reads the value of the io_openliberty_guides_inventory_inMaintenance configuration property in the META-INF/microprofile-config.properties file and checks the HTTP response of the inventory service. If the configuration value is false, the service returns a valid response. Otherwise, the service returns the following message: ERROR: Service is currently in maintenance.

Because the io_openliberty_guides_inventory_inMaintenance configuration property is set to false by default, the testPutServiceInMaintenance() test case first checks that the inventory service is not in maintenance in the beginning. Next, this test switches the value of the io_openliberty_guides_inventory_inMaintenance configuration property to true. In the end, the inventory service returns the following message: ERROR: Service is currently in maintenance.

The testChangeEmail() test case first puts the inventory service in maintenance, then it changes the email address in the configuration file. In the end, the inventory service should display the error message with the latest email address.

In addition, a few endpoint tests have been provided for you to test the basic functionality of the inventory and system services. If a test failure occurs, then you must have introduced a bug into the code. Remember that you must register the custom configuration source and custom converter in the src/main/resources/META-INF/services/ directory. If you don’t complete these steps, the tests will fail. These tests run automatically as a part of the integration test suite.

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.

You see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.config.ConfigurationIT
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.92 s - in it.io.openliberty.guides.config.ConfigurationIT
Running it.io.openliberty.guides.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.017 s - 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.077 s - in it.io.openliberty.guides.inventory.InventoryEndpointIT

Results:

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

To see whether the tests detect a failure, remove the configuration resetting line in the setup() method of the ConfigurationIT.java file. Then, manually change some configuration values in the resources/CustomConfigSource.json file. Rerun the tests. You will see a test failure occur.

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

Great work! You’re done!

You just built and tested a MicroProfile application with MicroProfile Config in Open Liberty.

Feel free to try one of the related guides. They demonstrate new technologies that you can learn and expand on top what you built in this guide.

Guide Attribution

Configuring 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