The GroovyWS project provides to realize webservice producers and consumers in a simple manner. The following example shows how to implement a short hello world webservice with Groovy. The GroovyWS page describes how to install and run GroovyWS on a standard Groovy environment. The following examples works on this environment. Additionally I show how to start the GroovyWS example in combination with Maven and within the GroovyScriptEngine.
Groovy Webservice Class
This Groovy class represents a standard Groovy class, which takes a string parameter and returns an enriched string.
class HelloWebService {
public String sayHello(String myname) {
return "Hello my friend " + myname
}
}
Producer Implementation
First you have to create the WSServer object. After that you have to forward your Groovy webservice class and your favored URL to the setNode() method. Now you can start the webservice (embedded Jetty) with the start() method.
import groovyx.net.ws.WSServer
import groovy.HelloWebService
//server part
def server = new WSServer()
server.setNode("groovy.HelloWebService", "http://localhost:8080/HelloWebService")
server.start()
Consumer Implementation
You can access existing webservices with a proxy mechanism. First you create the WSClient object and forward the WSDL-URL to the constructor. After calling the initialize() method you can execute all webservice methods.
//client part
import groovyx.net.ws.WSClient
proxy = new WSClient("http://localhost:8080/HelloWebService?wsdl", this.class.classLoader)
proxy.initialize()
result = proxy.sayHello("Rafael Sobek")
println "Result is ${result}"
I copied the WSServer class after ClassNotFound-exceptions and fixed the class loader issue. Certainly you have to change your import.
//..
GroovyClassLoader gcl = new GroovyClassLoader(this.getClass().getClassLoader());
//after gcl
gcl.addClasspath("src/main/java");
Main Method for Execution
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class GroovyWSExample {
public static void main(String[] args) throws Exception {
GroovyScriptEngine gse = new GroovyScriptEngine(
"src/main/java", GroovyWSExample.class.getClassLoader());
Binding binding = new Binding();
//consumer and producer logic is in this groovy file
gse.run("groovywsscript.groovy", binding);
}
}
The United Coders Blog Article describes how to realize a webservice only in Java. You see it's more complex.
Nice introduction into GroovyWS. Because Groovy is fully integrated into Java you can also use JAX-WS and Groovy to realize simple but powerful Web Services. See:
Nice introduction into GroovyWS. Because Groovy is fully integrated into Java you can also use JAX-WS and Groovy to realize simple but powerful Web Services. See:
http://www.predic8.com/groovy-web-services-jax-ws.htm
for an example.