Since working with, or creating WebServices is something webdevelopers will probably do regularly (or stumble upon in the very near future) I decided to have a look at Grails‘ support for SOAP.
First thing I wanted to see was how to expose a Grails service via Soap. Due to the excellent documentation at the Grails website this proved to be really simple:
- Setup
-
- download the XFire plugin here
- install the plugin by running “grails install-plugin /path/to/grails-XFire-x.x.x.zip” from the root of your project
- Create a service
-
- run “grails create-service Task” from the root of your project
-
Implement it and configure it for XFire remoting:
[groovy]
class TaskService {
static expose=['xfire'] // expose remotely using xfireboolean transactional = true
def String[] findTasksBySubject(String s) {
def c = Task.createCriteria()
def results = c{
like(“subject”, “%${s}%”)
}return results*.subject
}
}
[/groovy]- Notice the *. (spread-dot) operator? It collects results from call the consequent method on each item in the list, cool!
- Notice the Hibernate Criteria Builder, more info here
- Notice the ‘transactional’ propery, setting it to true results in all methods of a service are wrapped in a transaction.
- Start your application, and point your browser to: http://localhost:8080/ptodo/services/task?wsdl
which gives you the WSDL describing your service! - done!
Of course there is no point in having a WebService without a client… which is only 3 lines of Groovy away. From your favorite Groovy shell, run (after installing the SOAP libs):
[groovy]
groovy> import groovy.net.soap.SoapClient
groovy> def proxy = new SoapClient(“http://localhost:8080/ptodo/services/task?wsdl”)
groovy> proxy.findTasksBySubject(“XFire”)
groovy> go
===> [Check the XFire plugin]
[/groovy]
Almost instant gratification!
Thank you for the walk-through! The info and links are very helpful. I also never knew about that spread operator, you can imagine the ugly nested iterating contrivances I have been using. I am smarter now! Is that a groovy thing or a grails thing?
Thanks!
@perryn gordern the spread operator is a groovy thing: http://tinyurl.com/dneslp