Categories
Groovy

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. 🙂

By Ken Kousen

I am a Java Champion and the author of the books "Kotlin Cookbook", (O'Reilly Media), "Modern Java Recipes" (O'Reilly Media), "Gradle Recipes for Android" (O'Reilly Media), and "Making Java Groovy" (Manning), as well as over a dozen video courses at Safari Books Online. I'm a regular member of the No Fluff, Just Stuff conference tour and have given talks all over the world. Through my company, Kousen IT, Inc, I've taught training courses to and worked with thousands of developers.

2 replies on “Easy SwingBuilder/RESTful web service demo”

Leave a Reply

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