Share this blog!

A simple RESTful web service to get currency exchange rates in JAX-RS

In this post, we went through a simple hello world application in JAX-RS and now we're going to widen our circle a wee bit to add some calculations and read @PathParam's.


1. Create a web application


Just like the last time, create a new project, choose Java Web and Web Application from the list, select a server (I chose Glass Fish) and create the project. 

2. Add the logic 


Now let's add a class that will be responsible for calculating the rates when the currencies are passed as parameters. For this, I used a package named exchangerate in which I created the CurrencyCalculator class with the following code.


public class CurrencyCalculator {

    private HashMap<String, Double> rates;

    public CurrencyCalculator() {
        this.rates = new HashMap();
        this.rates.put("USD", 1.0); //using USD as the base
        this.rates.put("EUR", 0.933);
        this.rates.put("LKR", 149.132);
        this.rates.put("AUD", 1.345);
        this.rates.put("YEN", 114.123);
    }

    public double getExchangeRate(String from, String to) {
        if (rates.containsKey(from) && rates.containsKey(to)) {
            double toVal = rates.get(to);
            double fromVal = rates.get(from);
            double rate = toVal / fromVal;
            return rate;
        }
        return 0;
    }
}

3. Add the REST service

Now it's time to write the service that will connect the user to the above logic. Just like the last time, right click on the project, select New→RESTful Web Services from Patterns. Select Simple Root Resource define the path and MIME type. 


4. Add PathParams to the service

Our goal is to match a URL like rates/USD/LKR to the above class's getExchangeRate("USD", "LKR")

rates/USD/LKR  →  getExchangeRate(USD,LKR);

For this we will have to use @PathParam annotations.

The following format is used to decode the path as a parameter to a method.

@Path("myPath")
public class ClassName {

    @GET
    @Path("{name}")
    @Produces(MediaType.TEXT_PLAIN)

    public String methodName(@PathParam("name") String name) {
        return "passed value: " + name;
    }

}

The result of the above would be:

myPath/sachithra  →  "passed value: sachithra"


5. Bind logic and path 

Using the above format, let's use an instance of the CurrencyCalculator and bind a path with 2 segments to a method with 2 parameters. 

@Path("rates")
public class ExchangeRate {

    private final CurrencyCalculator rates;

    public ExchangeRate() {
        rates = new CurrencyCalculator();
    }

    @GET
    @Path("{from}/{to}")
    @Produces(MediaType.TEXT_PLAIN)
    public String getRates(@PathParam("from") String from, @PathParam("to") String to) {
        double value = rates.getExchangeRate(from, to);
        String resultText = "";
        if (value != 0) {
            resultText = "1 " + from + " is eqdual to " + value + " " + to;
        } else {
            resultText = "Sorry, the currencies you defined are invalid or not yet implemented.";
        }
        return resultText;
    }

}

6. Run the service

Deploy and run the project and try out the results by using paths (eg: http://localhost:8080/ExchangeRate/webresources/rates/USD/LKR).


The complete implementation of the two classes can be found on this gist.

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment