Monday, December 27, 2010

Feeling Groovy

For some reason I had to test a service through http. The parameters should have been passed in as http header values. As I prefer to use small and simple tools my first implementation was made as a bash script using curl to call the service. Although it worked perfectly it was hard to use, as the company prefers the proprietary OS, and users were forced to install cygwin.
Recently I was reading books (Programming Groovy and Groovy Recipes) about Groovy and recognized the potential in it. Using the JVM as a carrier makes the scripts available on all relevant platforms.
Actually it took some time to get the thing working, so I believe it might help others to check out my solution on curl in Groovy:
def curl(url, headers, fileName, outputFileName = 'out.log') {
 def connection = new URL(url).openConnection()
 connection.setRequestMethod(fileName ? 'POST' : 'GET')
 headers.each() { key, value ->
  connection.setRequestProperty(key ,value)
 }
 connection.doOutput = true
 if (fileName) {
  if (isPdf(fileName)) { // ***
   connection.outputStream << new File(fileName).readBytes()
   connection.outputStream.flush()
   connection.outputStream.close()
  } else {
   connection.outputStream.withWriter() { writer ->
    new File(fileName).eachByte() { writer.write it }
   }
  }
 }
 connection.connect()

 new File(outputFileName).withOutputStream{ out ->
  connection.content.eachByte() {out.write it}
 }

 connection.headerFields
}
The point is in the conditional statement marked with stars: according to the type of the file (binary or  text) I had to handle posted data different ways.

No comments:

Post a Comment