Richard Perfect a Solution Architect for Fronde in Wellington, New Zealand. In his spare time when the commitments of family and two small, dearly loved children permit he is an avid gamer and can often be found within the virtual worlds of World of Warcraft. He has also recently launched a blog and web application at www.the-decision-wall.com. Richard has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

JavaScript Charts for Java Developers

03.01.2013
| 7340 views |
  • submit to reddit

In this article I would like to show how JavaScript charting libraries can be hooked up to server-side Java code. Many Java developers don't like dealing with JS. I know I was one of them. But now I've seen the light and undergone somewhat of a conversion. 

Over the years JavaScript hasn't gone away and has only become more important as other browser based technologies have fallen by the wayside like Flash, Silverlight and Applets. A comment that is sure to trigger comments :-)

There are dozens and dozens of JS Charting Libraries but for the purposes of this article I'm going to to use Google Charts. The approach outlined in this article can can easily be applied to other charting libraries.

You can get started with Google charts without writing any server side code by following this link for the parent website and this link to a starter tutorial which is pretty much copy & paste to get started.

One thing to be aware of with Google Charts, is that according to the license you are not allowed to download and host the JS yourself, so your solution will only work when the browser has access to the Internet. See this link. There used to be an API limit, but that applied to similar but different API call Google Image Charts which has now be depecrated.

The example project is available here on BitBucket.

If your Maven environment is all setup and working you should be able to just do the following from the command line to build and run the Jetty server.

mvn jetty:run

If you don't have Maven then it shouldn't be too hard to use you favourite Web Framework, include the sample code and the three Jersey jar files as decribed in the pom.xml.

Once the Jetty server has started the demo pages are available at;

http://localhost:8080/ 

Technique

You could just print all of the data into the Html page when your Java Web Framework rendered the page like ExampleOne, but that's not very interactive so in this approach I'm going to show you how to respond to user input on the browser and then update the chart with new data from the server.

If you want the chart to respond to the user then you'll need AJAX of some kind to make the background request to get the data and then update the chart.

The high level sequence of events is;

  1. The Select component fires an event, or the page is drawn
  2. JQuery performs the AJAX request to make a REST call against the server
  3. JAX-RS/Jersey on the Java server to responds to the REST call and returns a Json response.
  4. Google Charts draws the chart

Here are some of the highlights from the code and an explanation of what they are doing.

This bit of code listens for a change value event on the Select component and triggers the whole sequence of events when the user selects something from the combo-box.

$(document).ready(function(){
    $("#startingYearSelect").change(function() {
        drawChart();
    });
});

The $() syntax is a JQuery selector to find the element that we want to interrogate. "#startingYearSelect" tells JQuery that we want to find the element by the HTML ID attribute. If it had been ".something" then JQuery would have looked for all elements that matched the "something" CSS class. There are many other JQuery selectors, but these are the two you will probably use most often.

This bit of the code is JQuery to read the current value out of the "select" combo-box.

// Get the current value of the select box 
var startingYear = $("#startingYearSelect").val();

JQuery is also used to retrieve the Json data from the server using an AJAX request.

var jsonData = $.ajax({
    url: "/rest/ExampleTwoResource/" + startingYear,
    dataType: "json",
    async: false
}).responseText;

You can execute this URL yourself from the browser with;

http://localhost:8080/rest/ExampleTwoResource/1980

The URL is processed on the server by the Jersey REST class;

@Path("/ExampleTwoResource/{startingYear}")
public class ExampleTwoResource {

@GET
@Produces({MediaType.APPLICATION_JSON})
public Object[] getMethod(@PathParam("startingYear") Integer startingYear) {
   System.out.println("ExampleTwoResource: startingYear = " + startingYear);
   ...
}
}

This method will return an answer of something like;

[["Year","Sales","Expenses"],["1980",14100,8300],["1981",5400,7700],["1982",11300,11600],["1983",6000,5300]]

Just to make this a little clearer, think of this data as a table of rows and columns. The column headers are the data series labels and the rows are the values for each column on the x-axis.

[
 ["Year", "Sales","Expenses"],
 ["1980", 14100,   8300],
 ["1981", 5400,    7700],
 ["1982", 11300,   11600],
 ["1983", 6000,    5300]
]

Back on the browser the Json data that we get is then converted into a JavaScript object

// jsonData is just a String, flip it into a JS object
var jsObject = jQuery.parseJSON(jsonData);
And then we draw the Chart...


// Specify some options about how the chart is to be drawn
var chartOptions = {
  title: "Company Performance",
  hAxis: {title: "Year"},
};

// This is where we want to put the chart
var chartDiv = document.getElementById("chart_div");

// Create the Chart
var chart = new google.visualization.ColumnChart(chartDiv);

// Ask the Chart to draw itself with these data and options
chart.draw(chartData, chartOptions);
Published at DZone with permission of its author, Richard Perfect.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)