Using IntelliJ IDEA to develop a microservice

duration 30 minutes

Prerequisites:

Learn how to use the IntelliJ IDEA to develop a microservice with Open Liberty.

What you’ll learn

IntelliJ IDEA is a popular integrated development environment (IDE) created by JetBrains, used primarily for developing programs for the Java Virtual Machine (JVM).

You’ll learn how to get started with IntelliJ IDEA by building and testing a simple REST service. This service will display the JVM’s system properties. The REST service will respond to GET requests made to the http://localhost:9080/LibertyProject/System/properties URL.

To learn more about how to create a REST service, see Creating a RESTful web service.

Additional prerequisite

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-intellij.git

cd guide-intellij

Make a note of the directory path that the project is being cloned to.

Start IntelliJ IDEA, select Import Project. Navigate to the directory where the project was saved and click Open. On the Import Project dialog box, choose Import project from external model and select Maven and click Finish.

If the directory is not automatically open, click Open on the welcome screen and navigate to the directory mentioned previously and select Open. Select View in the menu bar and navigate to Tool Windows and click Project to display the Project Tool Window at top left side. Expand the guide-intellij project. If there is no guide directory showed up in the top left side, try to reopen the IntelliJ IDEA.

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

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

At the lower left of the IDE, click Terminal to open the console if needed. By default, it should start in the guide-intellij directory.

Configure the build project

From the menu bar, select Run and click Edit Configurations.

Click the + button at the upper left in the Run/Debug Configurations pop up window. Select Maven under Add new configuration.

  • In the Name field, put Run finish.

  • For the Working directory field, navigate to the finish directory.

  • In the Command line field, put liberty:run.

Next, repeat the above steps using the following values in the corresponding fields:

  • Name field: Stop finish

  • Working directory field: navigate to the finish directory

  • Command line field: liberty:stop.

Run through the steps again using the following values in the corresponding fields:

  • Name field: Develop start

  • Working directory field: navigate to the start directory

  • Command line field: liberty:dev.

Repeat one last time, using the following values in the corresponding fields:

  • Name field: Stop start

  • Working directory field: navigate to the start directory

  • Command line field: liberty:stop.

Once the configurations are set up, the drop down menu in the topscreen toolbar can be used to quickly select different configurations to run.

Setting up the SDK

The SDK should be configured for both the start and finish projects.

From the menu bar, select File and click Project Structure. On the panel on the left, locate the Project Settings section and select Project.

In the Project SDK section, click New, choose JDK and specify the path to the JDK set up on your machine.

Click OK to save changes.

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, you can select Run in the menu bar and click Run…​. Select Run finish in the pop up window and deploy it to Open Liberty.

The tool window will be activated by default, displaying a console which allows you to follow the progress of the build.

Look at the console out for the Run finish command. If the following statement "CWWKF0011I: The defaultServer server is ready to run a smarter planet. The defaultServer server started in 6.228 seconds." shows in the console, check out the service at the http://localhost:9080/LibertyProject/System/properties URL.

You are expected to see the system properties displayed in JSON format.

To stop the application, select Run in the menu bar and click Run…​ and then select Stop finish in the pop up window.

Developing the microserivce

Select Run in the menu bar and click Run…​. Select Develop start in the pop up window which will start the Open Liberty server in development mode and will listen for file changes.

Check out the service at the http://localhost:9080/LibertyProject/System/properties URL.

You are expected to see Context Root Not Found.

Configuring the server

If the Project Tool Window is not currently displayed, select View in the menu bar and navigate to Tool Windows and click Project to display the Project Tool Window at top left side. Expand the guide-intellij project and navigate to the start directory to begin. If there is no guide directory showed up in the top left side, try to reopen the IntelliJ IDEA.

To get the service running, the Open Liberty server needs to be correctly configured.

Replace the server configuration file.
src/main/liberty/config/server.xml

server.xml

 1<server description="Intro IntelliJ REST Guide Liberty server">
 2
 3  <!-- tag::featureManager[] -->
 4  <featureManager>
 5      <feature>jaxrs-2.1</feature>
 6  </featureManager>
 7  <!-- end::featureManager[] -->
 8
 9  <!-- tag::httpEndpoint[] -->
10  <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
11                id="defaultHttpEndpoint" host="*" />
12  <!-- end::httpEndpoint[] -->
13  
14  <!-- tag::webApplication[] -->
15  <webApplication location="guide-intellij.war" contextRoot="${app.context.root}"/>
16  <!-- end::webApplication[] -->
17</server>

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    <modelVersion>4.0.0</modelVersion>
  6
  7    <groupId>io.openliberty.guides</groupId>
  8    <artifactId>guide-intellij</artifactId>
  9    <version>1.0-SNAPSHOT</version>
 10    <packaging>war</packaging>
 11
 12    <properties>
 13        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 14        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 15        <maven.compiler.source>1.8</maven.compiler.source>
 16        <maven.compiler.target>1.8</maven.compiler.target>
 17        <failOnMissingWebXml>false</failOnMissingWebXml>
 18        <!-- Plugin versions -->
 19        <version.liberty-maven-plugin>3.2</version.liberty-maven-plugin>
 20        <version.maven-failsafe-plugin>2.22.2</version.maven-failsafe-plugin>
 21        <version.maven-surefire-plugin>2.22.2</version.maven-surefire-plugin>
 22        <version.maven-war-plugin>3.2.3</version.maven-war-plugin>
 23        <!-- Liberty configuration -->
 24        <!-- tag::defaultHttpPort[] -->
 25        <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 26        <!-- end::defaultHttpPort[] -->
 27        <!-- tag::defaultHttpsPort[] -->
 28        <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 29        <!-- end::defaultHttpsPort[] -->
 30        <!-- tag::appContextRoot[] -->
 31        <liberty.var.app.context.root>LibertyProject</liberty.var.app.context.root>
 32        <!-- end::appContextRoot[] -->
 33    </properties>
 34
 35    <dependencies>
 36        <!-- Provided dependencies -->
 37        <dependency>
 38            <groupId>jakarta.platform</groupId>
 39            <artifactId>jakarta.jakartaee-web-api</artifactId>
 40            <version>8.0.0</version>
 41            <scope>provided</scope>
 42        </dependency>
 43        <!-- For tests -->
 44        <dependency>
 45            <groupId>org.junit.jupiter</groupId>
 46            <artifactId>junit-jupiter</artifactId>
 47            <version>5.6.1</version>
 48            <scope>test</scope>
 49        </dependency>
 50        <dependency>
 51            <groupId>org.apache.cxf</groupId>
 52            <artifactId>cxf-rt-rs-client</artifactId>
 53            <version>3.3.4</version>
 54            <scope>test</scope>
 55        </dependency>
 56        <dependency>
 57            <groupId>org.apache.cxf</groupId>
 58            <artifactId>cxf-rt-rs-extension-providers</artifactId>
 59            <version>3.3.4</version>
 60            <scope>test</scope>
 61        </dependency>
 62        <dependency>
 63            <groupId>org.eclipse</groupId>
 64            <artifactId>yasson</artifactId>
 65            <version>1.0.5</version>
 66            <scope>test</scope>
 67        </dependency>
 68        <!-- Support for JDK 9 and above -->
 69        <dependency>
 70            <groupId>javax.xml.bind</groupId>
 71            <artifactId>jaxb-api</artifactId>
 72            <version>2.3.1</version>
 73            <scope>test</scope>
 74        </dependency>
 75    </dependencies>
 76
 77    <build>
 78        <finalName>${project.artifactId}</finalName>
 79        <plugins>
 80            <!-- Enable liberty-maven plugin -->
 81            <plugin>
 82                <groupId>io.openliberty.tools</groupId>
 83                <artifactId>liberty-maven-plugin</artifactId>
 84                <version>${version.liberty-maven-plugin}</version>
 85            </plugin>
 86            <!-- Plugin to run functional tests -->
 87            <plugin>
 88                <groupId>org.apache.maven.plugins</groupId>
 89                <artifactId>maven-failsafe-plugin</artifactId>
 90                <version>${version.maven-failsafe-plugin}</version>
 91                <configuration>
 92                    <!-- tag::testsysprops[] -->
 93                    <systemPropertyVariables>
 94                        <http.port>${liberty.var.default.http.port}</http.port>
 95                        <context.root>${liberty.var.app.context.root}</context.root>
 96                    </systemPropertyVariables>
 97                    <!-- end::testsysprops[] -->
 98                </configuration>
 99            </plugin>
100            <plugin>
101                <groupId>org.apache.maven.plugins</groupId>
102                <artifactId>maven-war-plugin</artifactId>
103                <version>${version.maven-war-plugin}</version>
104            </plugin>
105            <!-- Plugin to run unit tests -->
106            <plugin>
107                <groupId>org.apache.maven.plugins</groupId>
108                <artifactId>maven-surefire-plugin</artifactId>
109                <version>${version.maven-surefire-plugin}</version>
110            </plugin>
111        </plugins>
112    </build>
113</project>

<HttpEndpoint/> and contextRoot is added in the replaced file to connect to the liberty server.

The context root value context root is defined at the pom.xml.

The Open Liberty server was started in development mode in the previous section and all the changes were automatically picked up.

Check out the service at the http://localhost:9080/LibertyProject/System/properties URL.

You are expected to see the system properties displayed in JSON format.

Debugging the microservice

You may want to debug the program. After you run Develop start you can attach the IntelliJ IDEA debugger to the Open Liberty process.

From the menu bar, select Run and click Edit Configurations. Click the + button at the upper left in the Run/Debug Configurations pop up window. Select Remote in Add new configuration. Type Check in the Name field and 7777 into the Port field. Click OK to save the changes. Select Run from the menu bar and click Debug…​. Select Check in the pop-up window to start the debugger.

PropertiesResource.java

 1// tag::comment[]
 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::comment[]
13package io.openliberty.guides.rest;
14
15import java.util.Properties;
16
17import javax.ws.rs.GET;
18import javax.ws.rs.Path;
19import javax.ws.rs.Produces;
20import javax.ws.rs.core.MediaType;
21
22// tag::path[]
23@Path("properties")
24// end::path[]
25public class PropertiesResource {
26
27    // tag::get[]
28    @GET
29    // end::get[]
30    // tag::produces[]
31    @Produces(MediaType.APPLICATION_JSON)
32    // end::produces[]
33    public Properties getProperties() {
34        // tag::getProperty[]
35        Properties props = System.getProperties();
36        // end::getProperty[]
37        return props;
38    }
39
40}

In the editor open the class PropertiesResource which is located in the start/src/main/java/io/openliberty/guides/rest directory. Click in the margin on line 35. This action will set a breakpoint on that line.

Now refresh the browser at the http://localhost:9080/LibertyProject/System/properties URL. The server will stop at the breakpoint you set and you can examine the state of your JVM. Select Run in the menu bar and click Resume Program to continue testing your application.

Remove the breakpoint you set after debugging.

Testing the microservice

You can test this service manually by starting a server and pointing a web browser at the http://localhost:9080/LibertyProject/System/properties URL. Automated tests are a much better approach because they trigger a failure if a change introduces a bug. JUnit and the JAX-RS Client API provide a simple environment to test the application.

You can write tests for the individual units of code outside of a running application server, or they can be written to call the application server directly.

EndpointIT.java

 1// tag::comment[]
 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::comment[]
13package it.io.openliberty.guides.rest;
14
15import static org.junit.jupiter.api.Assertions.assertEquals;
16
17import java.util.Properties;
18
19import javax.json.bind.Jsonb;
20import javax.json.bind.JsonbBuilder;
21import javax.ws.rs.client.Client;
22import javax.ws.rs.client.ClientBuilder;
23import javax.ws.rs.client.WebTarget;
24import javax.ws.rs.core.Response;
25
26import org.junit.jupiter.api.Test;
27
28// tag::endpointTest[]
29public class EndpointIT {
30// end::endpointTest[]
31    
32    private static final Jsonb jsonb = JsonbBuilder.create();
33
34    // tag::test[]
35    @Test
36    // end::test[]
37    public void testGetProperties() {
38        // tag::systemProperties[]
39        String port = System.getProperty("http.port");
40        String context = System.getProperty("context.root");
41        // end::systemProperties[]
42        String url = "http://localhost:" + port + "/" + context + "/";
43
44        // tag::clientSetup[]
45        Client client = ClientBuilder.newClient();
46        // end::clientSetup[]
47
48        // tag::target[]
49        WebTarget target = client.target(url + "System/properties");
50        // end::target[]
51        // tag::requestget[]
52        Response response = target.request().get();
53        // end::requestget[]
54
55        // tag::assertequals[]
56        assertEquals( Response.Status.OK.getStatusCode(), response.getStatus(), "Incorrect response code from " + url);
57        // end::assertequals[]
58
59        // tag::body[]
60        String json = response.readEntity(String.class);
61        Properties sysProps = jsonb.fromJson(json, Properties.class);
62
63        // tag::assertosname[]
64        assertEquals(System.getProperty("os.name"),
65        sysProps.getProperty("os.name"), "The system property for the local and remote JVM should match");
66        // end::assertosname[]
67        // end::body[]
68        response.close();
69    }
70}

The test EndpointIT class is already provided for you to test the REST service. This test class has more lines of code than the resource implementation. This situation is common. The test method is indicated with the @Test annotation.

Running the tests

Since you started Open Liberty in development mode earlier in the guide, you will be able to run tests with the enter/return key. To navigate back to the terminal where development mode is running, select the Run tab in the bottom left corner of the IDE, and then select the Develop start tab at the top of the terminal window. Press the enter/return key to run the tests. You will see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.rest.EndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.884 sec - in it.io.openliberty.guides.rest.EndpointIT

Results :

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

To see whether the tests detect a failure, add an assertion that you know fails, or change the existing assertion to a constant value that doesn’t match the os.name system property.

When you are done checking out the service, exit development mode by selecting Run in the menu bar and clicking Run…​ and then selecting Stop start in the pop up window. Alternatively, type q in the terminal where development mode is running and then press the enter/return key.

Great work! You’re done!

You developed a REST service in Open Liberty using IntelliJ IDEA.

Learn more about MicroProfile.

Guide Attribution

Using IntelliJ IDEA to develop a microservice by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Great work! You're done!

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

Guide license