I've created a groovlet that will act as a sort of HTTP proxy. It accepts GET requests and then makes web service calls based on the URL provided in the request.
Here's the code I've got so far:
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0')
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
String url = params.url
def http = new HTTPBuilder(url)
http.request(GET, TEXT) {
response.success = { resp, reader ->
println reader
}
response.'404' = { resp ->
println 'not found!'
}
}
I've got the Groovy HTTPBuilder JAR file in the WEB-INF/lib
folder of the groovlet. However, the code isn't working as it should. (I also tried putting the folder in $TOMCAT_HOME/common/lib
with the same results as below.)
When I run the code exactly as it is above, the page comes back completely blank.
If I remove just the @Grab
line at the top (since the JAR should theoretically be in the classpath already), I get a nasty error from Tomcat (I'm running it on 5.5, but I get roughly the same behavior on 6):
HTTP Status 500 - GroovyServlet Error: script: '/proxy.groovy': Script processing failed.startup failed: General error during semantic analysis: Type org.apache.http.client.methods.HttpRequestBase not present java.lang.TypeNotPresentException: Type org.apache.http.client.methods.HttpRequestBase not present...
That is then followed by the stack trace.
What is wrong with my groovlet?
Two things.
First, it seems that Groovlets can't use Grape (the @Grab
command). That's why the groovlet fails silently when this line is present.
Second, the http-builder
module also depends on about 19 other packages (including the org.apache.http.client.methods.HttpRequestBase
that is referenced in the error message). You can find these packages in the ~/.groovy/grapes
folder.
If you want to find all the dependencies, delete the Grapes directory. Then run a script locally that uses that @Grab
command. Once the script has finished executing, you can look in the Grapes directory and see everything it downloaded.
When I did it, I got the following list of packages:
antlr
asm
commons-beanutils
commons-codec
commons-collections
commons-lang
commons-logging
net.sf.ezmorph
net.sf.json-lib
net.sourceforge.nekohtml
org.apache
org.apache.commons
org.apache.httpcomponents
org.codehaus.groovy
org.codehaus.groovy.modules.http-builder
xerces
So if you want to use HttpBuilder in a groovlet, you'll need to get all those dependencies in WEB-INF/lib or your Tomcat common/lib directory.
On the other hand, if you don't need anything terribly fancy, you can use the Groovy URL object. See some examples here.