Java Reference
In-Depth Information
Groovy, if a closure is the last argument to a method it can be placed outside the par-
entheses, and here I'm using optional parentheses. Of course, there's no method called
games
in
MarkupBuilder
. That makes it a pretended method, and the builder inter-
cepts that method call and creates a node out of it. In a
MarkupBuilder
that means it
will ultimately create an XML element called
games
. The closure syntax implies that the
next elements will be child elements of
games
.
Inside the closure the code iterates over each contained result, assigning it to the dummy
variable
g
. For each
GameResult g
, the builder creates an element called
game
. The
parentheses on
game
imply that
game
will contain attributes. In this case, each
game
has
an
outcome
, a
lat
, and a
lng
.
Here's the output of the
MarkupBuilder
:
<games>
<game outcome='Boston Red Sox 4, Colorado Rockies 3'
lat='39.7564956' lng='-104.9940163' />
</games>
If there had been a dozen games that day there would a
<game>
element for each one of
them. The bottom line is that in Groovy, generating XML is about as easy as parsing it.
Server-side processing with groovlets
To drive the whole system I need a server-side component that receives the needed date
and calls the
GetGameData
class to retrieve the games, which are then returned in XML
form. Groovy has a component known as a
groovlet
to make that all easy.
A groovlet is a script that is executed by a class called
groovy.servlet.GroovyServlet
.ThisclassispartoftheGroovystandardlibrary.
Likeanyservlet,itneedstobedeclaredintheweb.xmldeploymentdescriptorforawebap-
plication and mapped to a particular URL pattern. In this case I chose the pattern *.groovy.
Here's the excerpt from the deployment descriptor:
<servlet>
<servlet-name>GroovyServlet</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GroovyServlet</servlet-name>