Sunday, October 10, 2010

Java Currency Converter using Yahoo Finance API – Currency Matrix – Visual Presentation

On this post we constructed a class that can get currency information from Yahoo Finance API. We saw how we can easily construct a neat currency matrix that summarizes currency information for several currencies.
Let’s see how we can visualize the currency matrix using a Java JSP and AJAX. The currency matrix will have the following properties:
  • The currency matrix will be show as an HTML table.
  • Currency information will be refreshed every 2 seconds.
  • If currency rate is increased the updated value will be marked in greed, if currency rate is decreased the updated value will be marked in red.
  • We will some popular currencies on our currency matrix. These currencies can be easily changed to have more/less/other currencies.
Since we would like to refresh currency information every 2 seconds (or any other fixed interval), and we don’t want the whole screen to be refreshed, only our currency matrix, we will need to use AJAX. We will use JSON in order to pass currency information from server to the client. JSON is a textual way of representing data.
The file that generates the JSON currency data is called: “currency_json.jsp”. It does the following things:
Let’s see how the file “currency_json.jsp” looks like:
<%
  YahooCurrencyConverter ycc = new YahooCurrencyConverter();
  String[] currencies = new String[]{"USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "MXN", "ILS"};
  CurrencyPair[][] currencyPairs = ycc.getConversionMatrix(currencies);
  int size = currencyPairs.length;
  JSONArray currencyArray = new JSONArray();
  for (int i = 0; i < size; i++) {
    JSONArray currencyRow = new JSONArray();
    for (int j = 0; j < size; j++)
    {
      CurrencyPair currencyPair = currencyPairs[i][j];
      currencyRow.add(currencyPair != null ? currencyPair.getPrice() : null);
    }
    currencyArray.add(currencyRow);
  }
  out.print(currencyArray.toJSONString());
%>
<%@ page import="com.bashan.currency.currency.CurrencyPair" %>
<%@ page import="com.bashan.currency.currency.YahooCurrencyConverter" %>
<%@ page import="org.json.simple.JSONArray" %>
<%@ page contentType="application/json;charset=UTF-8" language="java" %>
Note, that this code converts the data to JSON using the open source project named: json simple.

Let’s move the the main file: “currency.jsp”. This file does the following things:
  • Make an AJAX request to the “currency_json.jsp” file in order to get the latest currency matrix information.
  • When AJAX response is completed, get the JSON data received from server and build the currency matrix table. During the process of constructing the currency matrix, compare the currency data to the previous data. If there was a change in the currency, paint the table cell in red or green depending if currency raised or dropped.
Note, that in order to make the JSON AJAX request, we use MooTools JavaScript library. MooTools is a great and concat JavaScript framework, quite simplar to jQuery.
Let’s look at the “currency.jsp” code:
<%@ page import="org.json.simple.JSONArray" %>
<%!
 
  private static String[] currencies = new String[]{"USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "MXN", "ILS"};
  private static JSONArray currencyArray = new JSONArray();
 
  static {
    for (int i = 0; i < currencies.length; i++) {
      currencyArray.add(currencies[i]);
    }
  } 
 
%>
<html>
<head>
<title>Currency Exchange Rates</title>
<link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<h1>Currency Exchange Rates</h1>
<table id="tableCurrency" class="tableBorder" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td class="tdBorder" style="font-weight:bold; text-align:center;">Currencies</td>
<%
  for (String currency : currencies) {
%>
<td style="font-weight:bold; text-align:center;" class="tdBorder"><%= currency %></td>
<%
  }
%>
</tr>
</thead>
<tbody id="tableBodyCurrency">
<tr>
<td class="tdBorder" colspan="<%= currencies.length + 1 %>">
Loading currencies data...
</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="js/mootools.js"></script>
<body>
<script type="text/javascript">
 
  var currencyCodes = <%= currencyArray.toJSONString() %>;
  var oldCurrencies = null;
 
  function getJSON()
  {
    var jsonRequest = new Request.JSON({url: "currency_json.jsp",
    onComplete: function(currencies) {
    if (typeof(currencies) == "undefined")
    {
      return;
    } 
 
    var table = $("tableBodyCurrency");
    var data = "";
    for (var i = 0; i < currencies.length; i++)
    {
      data = data + "<tr><td style='font-weight:bold; text-align:center;' class='tdBorder'>" + currencyCodes[i] + "</td>";
      var currencyRow = currencies[i];
      for (var j = 0; j < currencyRow.length; j++)
      {
        var currency = currencyRow[j];
        if (oldCurrencies == null || currency == null)
        {
          data = data + "<td class='tdBorder' style='text-align:center;'>" + (currency != null ? currency : "&nbsp;") + "</td>";
        }
        else
        {
          var oldCurrency = oldCurrencies[i][j];
          if (currency > oldCurrency)
          {
            data = data + "<td style='background-color:green; text-align:center;n' class='tdBorder'>" + currency + "</td>";
          }
          else if (currency < oldCurrency)
          {
            data = data + "<td style='background-color:red; text-align:center;' class='tdBorder'>" + currency + "</td>";
          }
          else
          {
            data = data + "<td class='tdBorder' style='text-align:center;'>" + currency + "</td>";
          }
        }
      }
      
      data = data + "</tr>";
    }
   
    table.set('html', data);
    oldCurrencies = currencies;
  }}).get();
}
 
window.addEvent('domready', function() {
getJSON();
getJSON.periodical(2000);
 
});
</script>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Also note, that the we use a style shit file named: “css.css” to make the table a bit nicer.
Now, let’s have a look how the currency matrix looks like when the page is first loaded:

And after we receive currency information, we can see the full matrix. Some of the cells are painted in green or red, indicating if currency increased or decreased:



You can see the currency matrix in action by simply dropping the currency.war file on Tomcat webapps folder. The war file also contains the java source files.

No comments:

Post a Comment