Wednesday, July 30, 2008

REST with Grails

Development Environment: Java: 1.5.0_16; Java HotSpot(TM) Client VM 1.5.0_16-b02 System: Linux version 2.6.18-53.el5 running on i386; UTF-8; en_US (nb) NetBeans IDE Dev (Build 200807040101) + Groovy and Grails plugin - created a grails project - created a domain class with name Game
class Game {
    String title
    String publisher
}
- used generate all to generate the view and controller - modifed Bootstrap.groovy to add sample data
class BootStrap {
     def init = { servletContext ->
         new Game(title:"game1",publisher:"pub1").save()
         new Game(title:"game2",publisher:"pub1").save()
         new Game(title:"game3",publisher:"pub2").save()
         new Game(title:"game4",publisher:"pub2").save()
     }
     def destroy = {
     }
} 
- run the app and test it - modify URLMappings.groovy
class UrlMappings {
    static mappings = {\
        "/ws/game/$id?"(controller:"game"){
            action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]
        }
    }
}
- modify GameController.groovy show method
def show = {
    if(params.id && Game.exists(params.id)) {
        def g = Game.get(params.id)
        render g as XML
    }
    else {
        def all = Game.list()
        render all as XML
    }
}
- the method can be tested with this client
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
def url = "http://localhost:8080/GameTrax/ws/game/${args[0]}"
def method = new GetMethod(url)
def client = new HttpClient()
def statusCode = client.executeMethod(method)
println "STATUS CODE:$statusCode"
def stream = method.getResponseBodyAsStream()
println "--- START RESPONSE BODY --- "
System.out << stream
println "\n--- END RESPONSE BODY ---"
stream.close()
method.releaseConnection()
- modify GameController.groovy save method
def save = {
    def game = new Game(params['game'])
    if(game.save())
        render game as XML
    else{
        def myerrors = game.errors.allErrors.collect { g.message(error:it) }
        render(contentType:"text/xml") {
            errors {
                for(err in myerrors) {
                    error(err)
                }
            }
        }
    }        
}
- you can test the method with the client below:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
def url = "http://localhost:8080/GameTrax/ws/game"
def method = new PostMethod(url)
def client = new HttpClient()
def payload = """
<game>
  <title>newgame</title>
  <publisher>newpublisher</publisher>
</game>
"""
method.addRequestHeader("Content-Type","text/xml")
method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
method.setRequestEntity(new StringRequestEntity(payload))
def statusCode = client.executeMethod(method)
println "STATUS CODE:$statusCode"
def stream = method.getResponseBodyAsStream()
println "--- START RESPONSE BODY --- "
System.out << stream
println "\n--- END RESPONSE BODY ---"
stream.close()
method.releaseConnection()

No comments:

Post a Comment