Configuring microservices

duration 20 minutes
Git clone to get going right away:
git clone https://github.com/OpenLiberty/guide-microprofile-config.git
Copy Github clone command

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 inventory application. Feel free to give it a try before you proceed.

To try out the application, first navigate to the finish directory and then run the following Maven goals to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

After starting the application, 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:

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

mvn liberty:stop-server

Ordering multiple configuration sources

Now, navigate to the start directory to begin.

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

1config_ordinal=100
2io_openliberty_guides_port_number=9080
3io_openliberty_guides_inventory_inMaintenance=false
4io_openliberty_guides_system_inMaintenance=false
5io_openliberty_guides_testConfigOverwrite=DefaultSource

Injecting static configuration

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

1config_ordinal=100
2io_openliberty_guides_port_number=9080
3io_openliberty_guides_inventory_inMaintenance=false
4io_openliberty_guides_system_inMaintenance=false
5io_openliberty_guides_testConfigOverwrite=DefaultSource

To use this configuration property,

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

InventoryConfig.java

 1package io.openliberty.guides.inventory;
 2
 3import javax.enterprise.context.RequestScoped;
 4import javax.inject.Inject;
 5import javax.inject.Provider;
 6import org.eclipse.microprofile.config.inject.ConfigProperty;
 7import io.openliberty.guides.config.Email;
 8
 9@RequestScoped
10public class InventoryConfig {
11
12  @Inject
13  @ConfigProperty(name = "io_openliberty_guides_port_number")
14  private int portNumber;
15
16  public int getPortNumber() {
17    return portNumber;
18  }
19
20}

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

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

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

 1package io.openliberty.guides.inventory;
 2
 3import javax.enterprise.context.RequestScoped;
 4import javax.inject.Inject;
 5import javax.inject.Provider;
 6import org.eclipse.microprofile.config.inject.ConfigProperty;
 7import io.openliberty.guides.config.Email;
 8
 9@RequestScoped
10public class InventoryConfig {
11
12  @Inject
13  @ConfigProperty(name = "io_openliberty_guides_port_number")
14  private int portNumber;
15
16  @Inject
17  @ConfigProperty(name = "io_openliberty_guides_inventory_inMaintenance")
18  private Provider<Boolean> inMaintenance;
19
20  public int getPortNumber() {
21    return portNumber;
22  }
23
24  public boolean isInMaintenance() {
25    return inMaintenance.get();
26  }
27
28}

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,

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

Email.java

 1package io.openliberty.guides.config;
 2
 3public class Email {
 4  private String name;
 5  private String domain;
 6
 7  public Email(String value) {
 8    String[] components = value.split("@");
 9    if (components.length == 2) {
10      name = components[0];
11      domain = components[1];
12    }
13  }
14
15  public String getEmailName() {
16    return name;
17  }
18
19  public String getEmailDomain() {
20    return domain;
21  }
22
23  public String toString() {
24    return name + "@" + domain;
25  }
26}

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

 1package io.openliberty.guides.config;
 2
 3import org.eclipse.microprofile.config.spi.Converter;
 4import io.openliberty.guides.config.Email;
 5
 6public class CustomEmailConverter implements Converter<Email> {
 7
 8  @Override
 9  public Email convert(String value) {
10    return new Email(value);
11  }
12
13}

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

 1package io.openliberty.guides.inventory;
 2
 3import javax.enterprise.context.RequestScoped;
 4import javax.inject.Inject;
 5import javax.inject.Provider;
 6import org.eclipse.microprofile.config.inject.ConfigProperty;
 7import io.openliberty.guides.config.Email;
 8
 9@RequestScoped
10public class InventoryConfig {
11
12  @Inject
13  @ConfigProperty(name = "io_openliberty_guides_port_number")
14  private int portNumber;
15
16  @Inject
17  @ConfigProperty(name = "io_openliberty_guides_inventory_inMaintenance")
18  private Provider<Boolean> inMaintenance;
19
20  @Inject
21  @ConfigProperty(name = "io_openliberty_guides_email")
22  private Provider<Email> email;
23
24  public int getPortNumber() {
25    return portNumber;
26  }
27
28  public boolean isInMaintenance() {
29    return inMaintenance.get();
30  }
31
32  public Email getEmail() {
33    return email.get();
34  }
35}

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

 1package io.openliberty.guides.inventory;
 2
 3import java.util.Properties;
 4
 5// CDI
 6import javax.enterprise.context.RequestScoped;
 7import javax.inject.Inject;
 8import javax.ws.rs.GET;
 9import javax.ws.rs.Path;
10import javax.ws.rs.PathParam;
11import javax.ws.rs.Produces;
12import javax.ws.rs.core.MediaType;
13import javax.ws.rs.core.Response;
14
15import io.openliberty.guides.inventory.InventoryConfig;
16
17@RequestScoped
18@Path("systems")
19public class InventoryResource {
20
21  @Inject
22  InventoryManager manager;
23
24  @Inject
25  InventoryConfig inventoryConfig;
26
27  @GET
28  @Path("{hostname}")
29  @Produces(MediaType.APPLICATION_JSON)
30  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
31
32    if (!inventoryConfig.isInMaintenance()) {
33      Properties props = manager.get(hostname, inventoryConfig.getPortNumber());
34      if (props == null) {
35        return Response.status(Response.Status.NOT_FOUND)
36                       .entity("ERROR: Unknown hostname or the resource may not be " +
37                               "running on the host machine")
38                       .build();
39      }
40
41      // Add to inventory
42      manager.add(hostname, props);
43      return Response.ok(props).build();
44    } else {
45      return Response.status(Response.Status.SERVICE_UNAVAILABLE)
46                     .entity("ERROR: Service is currently in maintenance. Contact: " +
47                             inventoryConfig.getEmail().toString())
48                     .build();
49    }
50  }
51
52  @GET
53  @Produces(MediaType.APPLICATION_JSON)
54  public Response listContents() {
55    if (!inventoryConfig.isInMaintenance()) {
56      return Response.ok(manager.list()).build();
57    } else {
58      return Response.status(Response.Status.SERVICE_UNAVAILABLE)
59                     .entity("ERROR: Service is currently in maintenance. Contact: " +
60                             inventoryConfig.getEmail().toString())
61                     .build();
62    }
63  }
64
65}

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}

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.

Once 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

1config_ordinal=100
2io_openliberty_guides_port_number=9080
3io_openliberty_guides_inventory_inMaintenance=false
4io_openliberty_guides_system_inMaintenance=false
5io_openliberty_guides_testConfigOverwrite=DefaultSource

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.

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

mvn compile

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

mvn liberty:stop-server

Testing the application

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

ConfigurationTest.java

  1package it.io.openliberty.guides.config;
  2
  3import static org.junit.Assert.*;
  4
  5import javax.ws.rs.client.Client;
  6import javax.ws.rs.client.ClientBuilder;
  7import javax.ws.rs.core.Response;
  8
  9import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 10import org.junit.After;
 11import org.junit.Before;
 12import org.junit.Test;
 13
 14public class ConfigurationTest {
 15
 16  private String port;
 17  private String baseUrl;
 18  private Client client;
 19
 20  private final String INVENTORY_HOSTS = "inventory/systems";
 21  private final String USER_DIR = System.getProperty("user.dir");
 22  private final String DEFAULT_CONFIG_FILE = USER_DIR
 23      + "/src/main/resources/META-INF/microprofile-config.properties";
 24  private final String CUSTOM_CONFIG_FILE = USER_DIR.split("target")[0]
 25      + "/resources/CustomConfigSource.json";
 26  private final String INV_MAINTENANCE_PROP =
 27        "io_openliberty_guides_inventory_inMaintenance";
 28
 29  @Before
 30  public void setup() {
 31    port = System.getProperty("liberty.test.port");
 32    baseUrl = "http://localhost:" + port + "/";
 33    ConfigTestUtil.setDefaultJsonFile(CUSTOM_CONFIG_FILE);
 34
 35    client = ClientBuilder.newClient();
 36    client.register(JsrJsonpProvider.class);
 37  }
 38
 39  @After
 40  public void teardown() {
 41    ConfigTestUtil.setDefaultJsonFile(CUSTOM_CONFIG_FILE);
 42    client.close();
 43  }
 44
 45  @Test
 46  public void testSuite() {
 47    this.testInitialServiceStatus();
 48    this.testPutServiceInMaintenance();
 49    this.testChangeEmail();
 50  }
 51
 52  public void testInitialServiceStatus() {
 53    boolean status = Boolean.valueOf(ConfigTestUtil.readPropertyValueInFile(
 54        INV_MAINTENANCE_PROP, DEFAULT_CONFIG_FILE));
 55    if (!status) {
 56        Response response = ConfigTestUtil.getResponse(
 57            client, baseUrl + INVENTORY_HOSTS);
 58
 59        int expected = Response.Status.OK.getStatusCode();
 60        int actual = response.getStatus();
 61        assertEquals(expected, actual);
 62    } else {
 63      assertEquals("The Inventory Service should be in maintenance",
 64       "ERROR: Service is currently in maintenance. Contact: [email protected]",
 65        ConfigTestUtil.getStringFromURL(client, baseUrl + INVENTORY_HOSTS));
 66    }
 67  }
 68
 69  public void testPutServiceInMaintenance() {
 70    Response response = ConfigTestUtil.getResponse(
 71        client, baseUrl + INVENTORY_HOSTS);
 72
 73    int expected = Response.Status.OK.getStatusCode();
 74    int actual = response.getStatus();
 75    assertEquals(expected, actual);
 76
 77    ConfigTestUtil.switchInventoryMaintenance(CUSTOM_CONFIG_FILE, true);
 78
 79    String error = ConfigTestUtil.getStringFromURL(client,
 80        baseUrl + INVENTORY_HOSTS);
 81
 82    assertEquals("The inventory service should be down in the end",
 83       "ERROR: Service is currently in maintenance. Contact: [email protected]",
 84        error);
 85  }
 86
 87  public void testChangeEmail() {
 88    ConfigTestUtil.switchInventoryMaintenance(CUSTOM_CONFIG_FILE, true);
 89
 90    String error = ConfigTestUtil.getStringFromURL(client,
 91        baseUrl + INVENTORY_HOSTS);
 92
 93    assertEquals("The email should be [email protected] in the beginning",
 94       "ERROR: Service is currently in maintenance. Contact: [email protected]",
 95        error);
 96
 97    ConfigTestUtil.changeEmail(CUSTOM_CONFIG_FILE, "[email protected]");
 98
 99    error = ConfigTestUtil.getStringFromURL(client,
100        baseUrl + INVENTORY_HOSTS);
101
102    assertEquals("The email should be [email protected] in the beginning",
103     "ERROR: Service is currently in maintenance. Contact: [email protected]",
104      error);
105  }
106
107}

The testInitialServiceStatus() test case reads the value of the io_openliberty_guides_inventory_inMaintenance configuration property in the file META-INF/microprofile-config.properties 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. Reminder that you must register the custom configuration source and custom converter in the src/main/resources/META-INF/services/ directory, if you miss to complete these steps, the tests will fail.

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.config.ConfigurationTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.729 sec - in it.io.openliberty.guides.config.ConfigurationTest
Running it.io.openliberty.guides.inventory.InventoryEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.477 sec - in it.io.openliberty.guides.inventory.InventoryEndpointTest
Running it.io.openliberty.guides.system.SystemEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.013 sec - in it.io.openliberty.guides.system.SystemEndpointTest

Results :

Tests run: 3, 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 ConfigurationTest.java file. Then manually change some configuration values in the resources/CustomConfigSource.json file. Re-run the Maven build. You will see a test failure occur.

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
Git clone this repo to get going right away:
git clone https://github.com/OpenLiberty/guide-microprofile-config.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