Request Mocking to use groovyPagesTemplateEngine in backend threads

27 / Dec / 2010 by Vivek Krishna 5 comments

We have a setup where a backend thread, fired by the Spring Events, does some processing, generates a PDF and emails the result to the user.
The code we were using to generate the HTML from a GSP to be converted to a PDF using iText was as follows :

def webRequest = RequestContextHolder.getRequestAttributes()
def originalOut = webRequest.out
try {
def sw = new StringWriter()
def pw = new PrintWriter(sw)
webRequest.out = pw
return sw.toString()
} finally {
webRequest.out = originalOut

There was the obvious fallibility of this code that there was no Current Request associated with the backend thread!

After doing some googling around it, I came across a few threads and posts which talked about Request Mocking, which has been used in Grails Template Engine Plugin.  We overcame this by using the code snippet given below to mock the web request

def webRequest = RequestContextHolder.getRequestAttributes()
if(!webRequest) {
def servletContext  = ServletContextHolder.getServletContext()
def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
webRequest = grails.util.GrailsWebUtil.bindMockWebRequest(applicationContext)

However, things didn’t end there. This code broke while working on a WAR environment. The problem was that the MockWebRequest class was part of the “org.springframework:org.springframework.test:3.0.3.RELEASE” jar and had to be included in the BuildConfig.groovy as



runtime ‘org.springframework:org.springframework.test:3.0.3.RELEASE’



Ensure that the line




is not commented in BuildConfig.groovy

We were working on Grails 1.3.4


Hope this helps.


comments (5)

  1. Devajit Sonowal

    Thanks Vivek,
    I have been struggling for last two days. Finally your post resolved my problem.

  2. Anuj Aneja

    Thanks Vivek, for such a nice blog it cover every small detail which is highly appreciable. It helps me a lot.

  3. Vivek Krishna

    Hi Sohel,

    What I meant was that we use iText to convert static HTML to PDF. Here, the static HTML was generated using GSPs so that we could change the values in those documents. Hope that clears your doubt.

  4. sohel

    generate the HTML from a GSP to be converted to a PDF using iText :
    Actually what you have done here is not clear to me. Can you please describe this in details.


Leave a Reply

Your email address will not be published. Required fields are marked *