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.

[sourcecode language=”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, 250×100 pixels, values 60,40, labels ‘Hello’,’World’
def params = [cht:’p3′,chs:’250×100′,
chd:’t:60,40′,chl:’Hello|World’]
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)),
constraints:BL.CENTER)
}.pack()
}
[/sourcecode]
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. 🙂

2 responses to “Easy SwingBuilder/RESTful web service demo”

  1. wow! amazing! thanks for the post!

  2. This is cool .. I have developed a RESTful testing tool using griffon.. just for fun

    Try it and may be you could suggest improvements …

    http://code.google.com/p/firetester/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Stuff I've learned recently...

Subscribe now to keep reading and get access to the full archive.

Continue reading