DEV Community

Yegor Voronyansky
Yegor Voronyansky

Posted on

Write Simple Spring Boot for get currency rate

Within the framework of this article, we will develop an application for receiving exchange rates from the central bank of Russia. The main technologies we will be using will be Java, Spring Boot, Docker, Vue

  1. Let's start by choosing the required method in the API of the central bank, which is allowed to get the current rates 
  2. Next, let's add WSDL processing to the application so that we don't have to do it by hand 
  3. We use Spring WebServices so that our application can skillfully request data from the API 
  4. Add Swagger to the application 
  5. Add some Vue frontend 
  6. Connect Docker  The first thing we need is, of course, to create an application - this can be done using the Spring Initializr or through IntelliJ IDEA.

The API method we'll be using from the central bank is called GetCursOnDateXML. Below you can see its description.

In order not to describe the structure of requests and responses from the API ourselves, we will use plugins that will help turn WSDL into POJO. Listing pom.xml
Let's check that the plugin really works and the classes we need are created - screen.

        </vmArgs> <wsdlDirectory>${basedir}/src/main/resources/</wsdlDirectory>  
 <wsdlFiles> <wsdlFile>${basedir}/src/main/resources/dailyinfo.wsdl</wsdlFile>     </wsdlFiles> 
Enter fullscreen mode Exit fullscreen mode

Now let's add a web service that will be responsible for executing the request and response. Listing of creating a web service.

public class CBRService extends WebServiceTemplate {

     private String cbrApiUrl;     

     public List<ValuteCursOnDate> getCurrenciesFromCbr() throws DatatypeConfigurationException {
        final GetCursOnDateXML getCursOnDateXML = new GetCursOnDateXML();
        GregorianCalendar cal = new GregorianCalendar(); 
        cal.setTime(new Date());
        XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        GetCursOnDateXmlResponse response = (GetCursOnDateXmlResponse) marshalSendAndReceive(cbrApiUrl, getCursOnDateXML);
        if (response == null) {   
          throw new IllegalStateException("Could not get response from CBR Service");        
        final List<ValuteCursOnDate> courses = response.getGetCursOnDateXmlResult().getValuteData();
        courses.forEach(course -> course.setName(course.getName().trim()));
        return courses;    
    public ValuteCursOnDate getCurrencyFromCbr(String currencyCode) throws DatatypeConfigurationException {
        return getCurrenciesFromCbr()
             .filter(currency -> currencyCode.equals(currency.getChCode()))
             .findFirst().orElseThrow(() -> new RuntimeException("Could not find currency"));    
Enter fullscreen mode Exit fullscreen mode

Great, the MVP of the application is almost complete. Now let's add REST controllers so that we can send the received data from the third-party API outside. We will have one controller and two entry points - receiving all currencies, and receiving a specific currency at the moment.

@RequestMapping(value = "/api")
public class CurrencyController {
     private final CurrencyService currencyService;
     private final CBRService cbrService;

     @PostMapping(value = "/getCurrencyFromCbr")
     public List<ValuteCursOnDate> crbCurrencies() throws DatatypeConfigurationException {
        return cbrService.getCurrenciesFromCbr();
     @PostMapping(value = "/getCurrencyFromCbr/{currency}")     public ValuteCursOnDate crbOn(@PathVariable String currency) throws DatatypeConfigurationException {
        return cbrService.getCurrencyFromCbr(currency);
Enter fullscreen mode Exit fullscreen mode

Let's add Swagger to our application so that all consumers of our API know the contracts for interacting with the system.In order to add Swagger, you need to add one dependency and write the configuration code. Let's check that Swagger actually works. However, we need a complete UI. To do this, let's add another dependency and make sure that everything worked correctly.

Enter fullscreen mode Exit fullscreen mode

We have an API, but at the moment we can display currencies only in JSON form. Let's add a little frontend in Vue.

  <div class="container">
    <div class="row">
      <div class="col-2">
      <div class="col-8">
        <h1>Currency Rate</h1>
        <span>на {{ today }}</span>
        <table class="table">
          <thead class="table-striped table-bordered">
              <th scope="col">Name</th>
              <th scope="col">Nominal</th>
              <th scope="col">Rate</th>
              <th scope="col">Digital code</th>
              <th scope="col">Alphabet code</th>
            <tr v-for="currency in currencies" :key="">
              <td scope="row">{{ }}</td>
              <td scope="row">{{ currency.nominal }}</td>
              <td scope="row">{{ currency.course }}</td>
              <td scope="row">{{ currency.code }}</td>
              <td scope="row">{{ currency.chCode }}</td>
      <div class="col"></div>

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import CurrencyService from '@/service/CurrencyService'
export default {
  data() {
    return {
      currencies: [],
      today: new Date()
  created() {
      .then(response => {
        this.currencies =
      .catch(error => {
Enter fullscreen mode Exit fullscreen mode

Now, we should add service instance for interact with our backend.

import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'http://localhost:9091',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'

export default {
  getCurrencies() {
Enter fullscreen mode Exit fullscreen mode

We'll also add Docker for our convenience. Our Dockerfile will look like this

FROM adoptopenjdk/openjdk11:latestARG JAR_FILE=/backend/target/*.jar
COPY ${JAR_FILE} /backend/currency-rate-vue-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","/backend/currency-rate-vue-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

And last, but not least let's write unit test - for check that our app works correctly

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ru.rbs.currency_vue.dto.CurrencyCreationResponse;
import ru.rbs.currency_vue.model.Currency;
import ru.rbs.currency_vue.model.CurrencyCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import static;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

class CurrencyControllerTest {

    private MockMvc mockMvc;

    private ObjectMapper objectMapper;

    public void testWhenWeAskAboutAllCurrenciesShouldCheckThatAllArePresent() throws Exception {

    public void testWhenWeAskAboutCurrencyShouldCheckThatIsPresent() throws Exception {
                .andExpect(jsonPath("$.name").value("Доллар США"))

Enter fullscreen mode Exit fullscreen mode
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.rbs.currency_vue.dto.ValuteCursOnDate;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;

class CBRServiceTest {

    private CBRService cbrService;

    public void testWhenWeTryToGetAllCurrenciesCollectionsShouldBeNotEmpty() throws Exception {
        List<ValuteCursOnDate> cursOnDateList = cbrService.getCurrenciesFromCbr();

    public void testWhenWeTryToGetOnlyOneCurrenciesShouldCheckThatWeCanGetIt() throws Exception {
        ValuteCursOnDate rubCursOnDate = cbrService.getCurrencyFromCbr("USD");
Enter fullscreen mode Exit fullscreen mode

That's all for me, I hope you liked the article Write comments and subscribe

Oldest comments (0)