Building a simple microservice using Spring Boot

In this short post, I will show how to build a simple JPA Microservice using Spring Boot. Spring Boot makes it easy to create stand-alone based applications that you can run and need very little Spring configuration as we will see in this short tutorial.

springboot

For an explanation about microservices, read this article of Martin Fowler.

As I was saying we are going to use Spring Boot. First start of with a simple java maven enabled project in the IDE of your choice. We will first start with the .pom file to get all the Spring dependencies right. I am going to build a simple ReferenceDataService microservice which can deliver some simple reference data such as a list of countries. Let take a look at the pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ReferenceDataService</artifactId>
    <groupId>nl.redrock</groupId>
    <packaging>jar</packaging>
    <name>ReferenceData Microservice</name>
    <description>ReferenceData Service</description>
    <version>1.0</version>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>
    
	
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Oracle JDBC driver -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>7.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

As you can see, we the 1.5.2.RELEASE as a basis. We then have 4 dependencies. We need spring-boot-starter-web for libraries to creating the rest service, we need spring-boot-starter-data-jpa for the jpa capability, we need spring-boot-starter-test for testing capabilities and last an ojdbc.jar because the data is located in a Oracle database. I am also adding the spring-boot-maven-plugin to be able to run it from maven using Tomcat.

Let start of with the entry point….the application. This is the starting point of our simple service. It will look like this:

package nl.redrock.referencedataservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ReferenceDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReferenceDataApplication.class, args);
    }
}

As you can see, it is very simple. Use the @SpringBootApplication annotation to tag it as a Spring Boot application and that is it. Next we want a class which can retrieve data from database. Spring has a bunch helpful classes and templates for you to help with this. I already have a pre-filled oracle database running with 1 table called country. It has 3 columns….ID, CODE and NAME.

database

So as a first step we will create a Country class which maps to the table.

package nl.redrock.referencedataservice.data;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Country {
    
    @Id
    private int id;
    private String code;
    private String name;

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return String.format("Country[id=%d, code='%s', name='%s']",
                id, code, name);
    }
}

As you can see this is also a very simple POJO with the 3 attributes mapping to the 3 columns with getter and setters. The annotation which does al the magic here is @Entity. This tells spring that it can be used for Object Relational Mapping. Next we we will create a class which will fetch the data.

package nl.redrock.referencedataservice.repository;

import nl.redrock.referencedataservice.data.Country;
import org.springframework.data.repository.CrudRepository;

public interface CountryRepository extends CrudRepository<Country, Long> {

    Country findById(int id);
}

And again….not much coding here. Just a simple interface which extends Spring’s CRUDRepository. We define just 1 extra interface for retrieving a country by its id. And basically that is it. We just have 1 thing left to do, and that is telling Spring which database to connect to. This is easily done by adding an application.properties to you classpath with all the settings in so it is automatically picked up by Spring.

#port to run apache on
server.port=8888

# Oracle settings
spring.datasource.url=jdbc:oracle:thin:@private.eu-west-1.compute.amazonaws.com:1521:xe
spring.datasource.username=SECRET
spring.datasource.password=SECRET
spring.datasource.driver-class-oracle.jdbc.driver.OracleDriver

#set sql level to debug to see all the sql statements
logging.level.org.hibernate.SQL=debug
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n

The server.port is a setting which you can use to adjust the port tomcat runs on. Next up are the oracle database connection settings. And last of all some logging tweaking. A last thing to do is to make a unit test to see if it al works.

package nl.redrock.referencedataservice.repository;

import junit.framework.TestCase;
import nl.redrock.referencedataservice.data.Country;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class CountryRepositoryTest extends TestCase {
    
    @Autowired
    CountryRepository countryRepository;
    
    @Test
    public void testCountryRepository(){
        Country c = this.countryRepository.findById(1);
        assertTrue(c != null);
        assertTrue(c.getCode().equals("ac"));
        assertTrue(c.getName().equals("Ascension Island"));
    }
}

The things to look for here are the @DataJpaTest annotation which tells Spring it is a JPA test. The @AutoConfigureTestDatabase(replace=Replace.NONE) annotation tells Spring to not replace the application default DataSource.

Run the test:

UT

As you can see, we can fetch data from the database with minimal coding.

Now for the service part. Spring also has easy ways to accommodate this using the @RestController annotation.

package nl.redrock.referencedataservice.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.redrock.referencedataservice.data.Country;
import nl.redrock.referencedataservice.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/referencedataservice/countries")
public class ReferenceDataController {
    
    private final static Logger LOGGER = Logger.getLogger(ReferenceDataController.class.getName());
    
    @Autowired
    CountryRepository countryRepository;


    @RequestMapping("/{id}")
    public Country getCountry(@PathVariable int id) {
        Country result;
        LOGGER.log(Level.INFO, "Getting country with id " + id);
        result = countryRepository.findById(id);
        return result;
    }

    @RequestMapping(method = RequestMethod.GET)
    List<Country> getCountries() {
        List<Country> result;
        LOGGER.log(Level.INFO, "Getting all countries");
        result = new ArrayList();
        Iterable<Country> countryList = countryRepository.findAll();
        for (Country country : countryList) {
            result.add(country);
        }
        return result;
    }
}

As you can see we implement 2 operations. 1 to get all the countries and 1 to get a specific country by its id. We use @Autowired to inject the countryRepository. And now for the proof of the pudding. Run mvn clean spring-boot:run and watch maven spin up a Tomcat instance with the referencedataservice application deployed on it. Open up the browser and call:

http://localhost:8888/referencedataservice/countries

countriesResult

Now call http://localhost:8888/referencedataservice/countries/160 to get a specific country

countryResult

As you can see Spring makes it very easy to create rest services with minimal coding. If you want to look into some more advanced microservice features Spring has to offer, have a look here and here to see how you can use microservices in conjunction with Netflixs Eureka server.

A first glance at Mule’s API capabilities

Since 2006, Mulesoft is offering middleware and messaging. Back then, building integrations was still heavily XML file based, with a set of Eclipse based plugins. This has changed though! With their Anypoint Studio, an Eclipse-based graphical development environment for designing, testing and running Mule flows, they really upped their game. Together with their new IPaaS platform CloudHub and their API capabilities, Mulesoft is looked at as a big player in IPaaS and API arena as shown in a previous article here where both Gartner and Ovum rate them as leaders. To add to that, Mulesoft was placed in the Forbes Cloud top 100 at number 20.

mulesoft

As I was quite curious how the new studio compared to my daily integration work with JDeveloper, I downloaded it and gave it a swing with a simple integration. You can download Anypoint Studio right here.

I started of by creating a simple mule project. File > New > Mule Project and clicking finish. As you can see, you can also use Maven but I will leave this unchecked for now.

MuleProject

After clicking finish you will see that it generates a project structure on the left side:

MuleProjectExplorer

In the middle is the canvas on which you can drag and drop items from the palette which is on the right. Straight away you can see there are quite a few connector which come out-of-the-box.

MuleProjectConnectors

I will start of with a HTTP connector. You can search in palette by typing HTTP. Now just drag the component onto the canvas. When you select the component, you can see the properties at the bottom. I will just keep the HTTP Display Name but I will set the Path to /simplemuleservice. Then I will need to generate a listener configuration by clicking the + sign on the right. I will accept all the default values which are 0.0.0.0 at port 8081. Next I am going to add a simple response. Look for Set Payload in the palette and drag it in the box next to the HTTP connector. Now select it and input a value. Mine is Hello…this is a simple Mule service.

setpayload

Next lets add some Logging. Add the Logger component and add it to the canvas. In the Message property of the Logger we can state what we want to log. The settings for the logging are defined in the log4j2.xml under resources. You can also use the Mule expression language here to access all sorts of info. I will just log all of the parameters send with the request by adding the next message: My simple mule service called with parameter #[message.inboundProperties.'http.query.params']

logger

Now save the whole project. Lets see if it also runs. Just right click the application a choose > Run as > Mule application.

You can see the application is running.

running

Now open your browser and type in server and port you defined. In my case http://localhost:8081/simplemuleservice. As I also added the parameters to the Logger step, I will also add some of those like this: http://localhost:8081/simplemuleservice?caller=Hugo&message=Hi

As you will see the browser will respond with the output we defined.

browser

And the logging shows:
loggerOutput

As you can see, creating a flow is much easier then before. Underneath it is still al XML but the visual wrapper around it makes it easier to work with in my opinion. This was actually a very simple flow. The next step is to do something which is a bit more work but more like an actual usecase.

Lets say we have a SOAP service running on-premise. We want to expose that service as an API to the outside world. So basically 2 things:

  • Design the API first
  • Convert REST to SOAP and call the webservice
  • Convert the SOAP response back to a JSON result and return it

I want to make an API for a webservice which I have used before…..the ConversionRateService. It has 2 input values. FromCurrency and ToCurrency. The result is ConversionRate result. So let’s start with creating a simple RAML file. Mine looks like this:

#%RAML 1.0
title: Conversionrate API
version: v1.0
baseUri: http://conversionrate/api
mediaType: application/json
documentation:
  - title: Introduction
    content: |
      API to lookup currency conversion rates
/convert:
  get:
    responses:
      200:
        body:
          example: |
            {
                "conversionrate" : "1.2345",
                
            }

Now that we have our RAML file, start a new project, in my case simplemule2. Don’t forget to tick the Add APIkit components box below and select the RAML file we just created.

newProject

When you click finish, Anypoint Studio will generate skeletal backend flows, based on the RAML file. The next step is to delete the Set Payload in the get:/convert:conversionrate-config. This is the flow in which we will call our webservice. Drag the Web Service Consumer component onto the canvas. Then down below we can create a Connector Configuration.

webserviceconsumer. I used the WSDL from an old project here.

Now that I have the call to the webservice, I have to map the rest call to soap. Drag a Transform Message before the Web Service Consumer component. If you look at the properties below, you can see on the left side the Input, and on the right side the output. As the input parameters will be incoming as http query parameters, we can just type in the mapper file on the right, how we want to map them.

mapRequest

Next we want to transform the result from SOAP to a JSON response so drag another Transform Message but this time place it after the Web Service Consumer component. Again look at the properties below. On the left side you can the the data model of the webservice response. The right side Output shows unknown. As I just want to map the response, you can edit the result on the right side like shown below:

mapResponse

As you can see, we will return a simple JSON response in which we map the conversionrate field to the webservice response field ConversionRateResult. Save it and we are ready to test the application. To make it easy for myself, I have created the conversionrate webservice using SoapUI by importing the WSDL and creating a Mock service. It is running on http://localhost:8005/mockConversionRateService as defined in the Web Service Consumer component.

Now right click the application and choose Run as–> Mule application. As you can see it will also start the APIkit console automatically. It shows the description of the API and an interface to make calls. I will just use a good old browser call like this: http://localhost:8081/api/convert?FromCurrency=EUR&ToCurrency=USD which result in

mockResponse

As you can see, it hits the SoapUI mock which returns a SOAP response which is processed by Mule which returns a JSON response.

restResponse

I was surprised how easy it was to create an API design first. The UI works nice and easy and everything is deployed nice and fast on the integrated Mule server. I have just scratched the surface here of Mule’s capabilities but I am liking what I am seeing.

Creating a REST service in Oracle Service Bus 12C

In this first REST post I will demonstrate how to make easily expose a REST service in the Service Bus 12C. I will not explain REST as quite some people have already written tons of stuff about this….Google is your friend :) . Exposing a service in a REST way using the new 12C release is quite simple. Lets try and expose the ConversionRateService we previously build as a REST service.

Right click the Pipeline you want to expose and select Expose as REST.

ExposeAsREST

A popup opens where you can define the name of the service and it’s resource path. In our case I will name it ConversionRateRestService and will set its resource path to /json. You can do this by pressing the little pencil on the right.

ResourcePath

The only thing we now have to do is set the operational bindings. Click the GetConversionRate operation below and click the pencil. Another popup opens where you can set the HTTP verb which will be GET in our case. Down below you can see the request parameters and the expression of how to use them.

Binding

Now click the Response tab to define in which form we want our data returned. De-select the XML box and select the JSON box as we want our service to return JSON instead of XML.

JSON

Then press OK twice and voila. You have exposed your service!

If you want you can also expose another REST service which will return XML. Follow the previous steps but you have to remember that you cannot have two proxy services with the same Endpoint URI. So what I did, I created 2 proxy services with a different URI…..for example /financial/conversionraterestservice/1.0/xml for the xml version and /financial/conversionraterestservice/1.0/json for the JSON version. When you do that, you can leave the Resource Path of the REST binding on /

Binding

This way you can easily expose your functionality in three ways: SOAP

ExposeAsSOAP

or REST with JSON

RESTWithJSON

or REST with XML

RESTWithXML

In the next post I will show how to consume a REST service using the 12C Service Bus