Monday, December 15, 2008

Incorporating Google Charts into a Spring MVC application

The last blog post on interactively building charts with Clojure generated quite a bit of interest. As a continuation of the chart theme, I will describe how to incorporate professional quality charts into a Spring MVC web application by leveraging charts4j.

The Google Chart API potentially provides developers a lightweight mechanism to incorporate static and dynamic charts into a web application. Dealing with the Google Chart API directly, however, is tedious and error prone. Fortunately, charts4j, a lightweight wrapper to the Google Chart API, makes incorporating charts into your Spring web application much easier. To see examples of all the charts that can be generated with charts4j, see the chart gallery here.

See here to download the example code that this post describes. What follows below assumes some familiarity with how to build a Spring MVC web application.

To incorporate Google Charts into your Spring application, you will first need the standard Spring MVC infrastructure:

  • 8 Spring framework jars and friends: commons-logging-api-1.1.jar, jstl.jar, spring-beans.jar, spring-context.jar, spring-core.jar, spring-web.jar, spring-webmvc.jar, standard.jar. Put these jars in the WEB-INF/lib directory.
  • 3 Spring and servlet XML configuration files: applicationContext.xml, frontController-servlet.xml, web.xml. Put these XML files in the WEB-INF directory.

Plus, you will need to write one Spring Controller, one JSP. And most importantly, also grab the charts4j jar and put it in WEB-INF/lib.

Here is the controller code:
public class ChartController {
    public ModelAndView indexHandler() {
        //Your really great chart.
        final Plot plot = Plots.newPlot(Data.newData(0, 66.6, 33.3, 100));
        final LineChart chart = GCharts.newLineChart(plot);
        chart.setTitle("My Really Great Chart");
        //Passing the chart to the JSP for rendering.
        return new ModelAndView().addObject("url", chart.toURLString());      


Note that I am making use of the newer style annotation based Spring MVC controllers. Also, the line

final Plot plot = Plots.newPlot(Data.newData(0, 66.6, 33.3, 100));

has static, hard coded data, but the real power of this mechanism comes into play when the application dynamically generates data. For example, perhaps you would like to display up-to-date stock price or weather data from your database in your web application.

In addition, here is the JSP code:
<%@ taglib prefix="c" uri=""%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Your great chart</title>
<img src="${url}" alt="Chart" />

The only noteworthy lines of code in the JSP are highlighted. To display the chart in the JSP, use an HTML <img> tag with the URL generated in the controller: <img src="${url}" alt="Chart" />Also note that I am using the JSTL EL to access the URL string.

Deploy your web application and that is it. You are done.

The strength of this solution is its small footprint and low impact on your code base. To generate nice charts in your Spring MVC application, all you need is one 160 kb charts4j jar, an
Internet connection, a bit of charting code and you are done. No need for special graphics libraries, extra servlet infrastructure, etc. There are many more chart examples with code samples here.

Finally, the Google Chart API and charts4j will satisfy many Java application charting requirements, but there are three reasons why you may not wish to choose this technology:

  1. No Internet connection, no Google Charts. Your application must be connected to the Internet because the charts are ultimately rendered by the Google Chart API.
  2. There is no security with these charts. Your data will be sent as clear text over the Internet, and it would be trivial for someone to intercept this information.
  3. If you have lots of data, roughly speaking, more than 2000 data points, you should try to sample your data less frequently, and use the simple encoding scheme. If this is not a possibility, this technology may not be right for you.

This blog post has shown you how to incorporate charts4j in your Spring MVC web application, but there is no reason why you cannot also incorporate charts4j in any Java application environment, as long as the three requirements above are met. Moreover, this design pattern of generating charts in the servlet layer and rendering the chart URL in the JSP will work for any Java web application environment (e.g Struts, etc.)

Tuesday, December 2, 2008

Interactive Charting with Clojure

I stumbled upon the Clojure programming language a few months ago when I was trolling around the Internet for topics relating to Java threading and concurrency. This Lisp and Scheme derived dynamic language runs on the JVM and has the ability to invoke Java APIs via the Clojure special form syntax. One of Clojure's main features is its strong support for concurrent programming, taking advantage of its bias toward immutability, and leveraging its own notion of software transactional memory in addition to invoking the java.util.concurrent API and the forthcoming fork-join framework.

At any rate, Clojure is dynamic and thus has an interactive shell or REPL. Because you can invoke Java APIs from the REPL, I thought it would be a fun exercise to leverage charts4j to build charts interactively. I created the charts above and below fairly easily, certainly much easier than in a Java main program because Clojure's dynamic environment provides instant feedback. You can find the Clojure script that generated these images here.

Simply load it with the following command: (load-file "charting.clj"), setting your path appropriately, of course. You will also need the charts4j jar in your Clojure classpath. Moreover, you must be connected to the Internet for this script to run, as the charts are ultimately rendered by the Google Chart API. It will play a slide show, and can be a starting point for generating your own charts interactively. It should be straightforward to generate all the charts available in charts4j by using that script as an example. One last important note about the charting.clj script; it works with the latest Clojure SVN revision as of the day of this blog post, but this language is still young, and the Clojure authors are still fiddling with the syntax. Therefore, I also provide a "charting-20080916.clj" that works with the official latest release.

If there is enough interest, I may write a Clojure library that would make this interactive charting environment a bit easier to use, for instance by predefining more chart functions. This library could even be combined into a Clojure tutorial as programmers often respond to visual cues and eye candy as they are hacking away at code.

For the Clojure experts out there, I would welcome feedback on my Clojure code.