Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kenneth A. Kousen - Making Java Groovy - 2014.pdf
Скачиваний:
47
Добавлен:
19.03.2016
Размер:
15.36 Mб
Скачать

Other Groovy approaches

253

(continued)

3Structural links in the body are added through a special JAXB annotation.

4You can manage the parsing and response generation stages yourself by writing a provider class that implements MessageBodyReader and/or MessageBodyWriter.

Between the transitional links, the structural links with the JAXB serializer, and the Groovy JsonBuilder, hopefully you now have enough mechanisms to implement hypermedia links in any way your application requires. The choice of which to use is largely a matter of style, but there are some guidelines:

Structural links are contained in the response, so the client has to parse the response to get them.

Transitional links are in the HTTP headers. That gets them out of the response but forces the client to parse the HTTP response headers to retrieve them.

Custom links can be anything, so they must be clearly documented.

Examples of all three approaches can be found on the web.

9.6Other Groovy approaches

There are three other approaches in the Groovy ecosystem that I should mention for RESTful web services. Here I’ll specifically discuss groovlets, the Ratpack project, and Grails.

9.6.1Groovlets

Groovlets are discussed in chapter 10 on web applications as well as the simple example in chapter 2, but essentially they’re groovy scripts that receive HTTP requests and return HTTP responses. Groovlets contain many implicit variables, including request, response, session, and params (to hold input variables).

In a groovlet you can use the getMethod method on the request object to determine if the request is a GET, PUT, POST, or DELETE. Then you can build the response accordingly.

The book source code has a project in chapter 10 called SongService, which demonstrates how to use a groovlet. The service itself is a groovlet, which is shown in the following listing.

Listing 9.11 A groovlet that processes and produces XML

def dao = SongDAO.instance

switch (request.method) { case 'GET' :

if (params?.id) {

Implicit

MarkupBuilder

def s = dao.getSong(params.id)

html

html.song(id:s.id) {

 

 

 

www.it-ebooks.info

254

CHAPTER 9 RESTful web services

 

title s.title

 

artist s.artist

 

year s.year

 

}

 

} else {

 

def songs = dao.getAllSongs()

 

html.songs {

songs.each { s -> song(id:s.id) {

title s.title artist s.artist year s.year

}

}

}

}

break case 'POST' :

def data = new XmlSlurper().parse(request.reader) def s = new Song(id:data.@id,title:data.title,

artist:data.artist,year:data.year) def exists = dao.exists(s.id)

Converting request data to XML

if (!exists) { dao.addSong s

response.addHeader 'Location', "http://localhost:8080/GroovySongs/SongService.groovy?id=${s.id}" out.print "${s.title} added with id ${s.id}"

} else {

out.print "${s.title} already exists"

}

break

case 'DELETE' : dao.deleteSong params.id

out.print "${params.id} deleted" break

default:

print 'Only GET, POST, and DELETE supported'

}

The groovlet uses request.method in a switch statement to determine the correct implementation. Then it uses a built-in MarkupBuilder called html to produce XML, and an XmlSlurper to convert XML to song instances. Now that groovlets have a builtin JsonBuilder as well,22 JSON could easily be used instead.

This approach is pretty low-level, but it may be useful for quick-and-dirty implementations or if you need such detailed control.

22That’s my great contribution to Groovy—the implicit json object in groovlets, which I not only added, but with which I managed to break the build in the process. Sigh. If you’re interested, details can be found at http://mng.bz/5Vn6.

www.it-ebooks.info

Other Groovy approaches

255

9.6.2Ratpack

The second alternative is to look at the Ratpack project (https://github.com/ratpack/ ratpack). Ratpack is a Groovy project that follows the same ideas as the Sinatra23 project in the Ruby world. Ratpack is called a “micro” framework, in that you write simple Groovy scripts that govern how to handle individual requests.

For example, a simple Ratpack script looks like this:

get("/person/:personid") {

"This is the page for person ${urlparams.personid}"

}

post("/submit") {

// handle form submission here

}

put("/some-resource") { // create the resource

}

delete("/some-resource") { // delete the resource

}

The project shows a lot of promise, and Sinatra is very popular in the Ruby world, so it’s probably worth a look. The project has recently come under the control of Luke Daley, who is a major player in the Groovy world, so I expect significant improvements soon.

9.6.3Grails and REST

Finally, Grails has REST capabilities as well. For example, in a Grails application you can edit the URLMappings.groovy file as follows:

static mappings = { "/product/$id?"(resource:"product")

}

The result is that GET, POST, PUT, and DELETE requests for products will be directed to the show, save, update, and delete actions in the ProductController, respectively. Grails also automatically parses and generates XML and/or JSON, as desired.

There’s also a JAX-RS plugin available for Grails. At the moment it’s based on JAX-RS version 1, but the implementation can use either the Jersey reference implementation or Restlets. Of course, once again, nothing is said about hypermedia in either case, though anything you can do in Groovy you can, of course, do in Grails as well.

REST capabilities are a major design goal of Grails 3.0, so by then the situation will no doubt change.

23 Sinatra, Ratpack, get it? If nothing else, it’s a great name.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]