Archive for the ‘groovy’ tag
Quick WebService Client in Groovy
Writing WebService client in Groovy is simple.
import groovy.net.soap.SoapClient
def proxy = new SoapClient("http://localhost:7777/path/to/endpoint?WSDL")
def result = proxy.sayHello("Subhash")
println result
sayHello() is the operation name.
More details here. See the Installation part, you need to put the Groovy SOAP Jar in ${user.home}/.groovy/lib.
Beautiful Closures
One of the irritating things when writing code in Java is when managing files or database resources. We have to write so much redundant code:
File f = new File("/etc/passwd");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(f));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
}
catch(IOException ex){
...
}
finally{
if(br != null){
try{
br.close();
}
catch(IOException ex){
...
}
}
}
So much redundancy is ground for human errors. Issues like these are beautifully solved using programming concept called Closures. For example, in the newly released 2.6 version of Python, the same would be written as:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
In the above code, even when an exception is raised during file read, the file is gracefully closed when the control exits with block. A similar example in Groovy:
File f = new File("/etc/passwd")
f.eachLine{
line ->
println line
}
Martin Fowler has written a short introduction to Closures.