Easy SwingBuilder/RESTful web service demo

I’m teaching (yet) another Java Web Services class this week, and the subject of RESTful web services came up. When I talk to students about that, I often like to use the example of the Google Chart API.

(Whether that’s a truly RESTful web service or not depends on who you talk to. Google Chart only supports GET requests, so PUT, POST, and DELETE don’t enter into the discussion. It doesn’t have method names embedded in the URL parameters, though. Someone recently tweeted that the best thing about SOAP-based web services is that nobody argues about what is or isn’t truly SOAPful.)

If you check the main page for Google Chart, it starts with a nice, trivial, ‘Hello, World!’ example. I couldn’t resist demonstrating it to my class using Groovy.

import javax.swing.ImageIcon
import javax.swing.WindowConstants as WC
import java.awt.BorderLayout as BL
import groovy.swing.SwingBuilder

// Base url for Google chart
def base = 'http://chart.apis.google.com/chart?'

// Assemble the query string from a map
// 3D pie chart, 250x100 pixels, values 60,40, labels 'Hello','World'
def params = [cht:'p3',chs:'250x100',
url = base + params.collect { k,v -> "$k=$v" }.join('&')

// Display the result using Groovy's cool SwingBuilder
SwingBuilder.build() {
    frame(title:'Hello, World!', visible:true,
        defaultCloseOperation:WC.EXIT_ON_CLOSE) {
        label(icon:new ImageIcon(new URL(url)),

Accessing the URL returns a png image, which I wrap inside an ImageIcon, which I place inside a JLabel. The rest is hopefully clear. Executing the script gives the picture below:

Hello, World! image from Google Chart

The only other issue I had to deal with is that I was running inside a company, i.e., behind a proxy. Therefore, when I ran the script using the groovy command, I added -DproxyHost=... -DproxyPort=... in order to access Google Chart.

Pretty sweet.🙂

%d bloggers like this: