2

I am using a Grails service closure to perform a async HTTP request to another web application. Using Grails 1.3.9, I am very limited here. The code runs inside a thread. It is called from a scheduled job and from several function calls. The error I get is below:

ERROR:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. 

CODE:

 Thread.start { def http = new HTTPBuilder(grailsApplication?.config?.smsConfig?.smsServiceAddress); try { http.request(POST) { body = bodyRequest; requestContentType = ContentType.JSON response.success = { resp -> println "SUCCESS! ${resp.status}" def user = RequestContextHolder.currentRequestAttributes().getSession().user if (user != null) { if (termin) { termin.withTransaction { try { // do desired action } catch (e) { println(e); } } } } } response.failure = { resp -> println "FAILURE request failed with status ${resp.status}, response body was [${resp.entity.content.text}]" System.out << resp } } } //here error is caught catch (e) { log.error "Error: " + e; } } 

I have tried adding this options to web.xml

 <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 

and also this to WebXmlConfig.groovy

 listener.add = true listener.classNames = ["org.springframework.web.context.request.RequestContextListener"] 

but both did not help

1 Answer 1

2

This is something that isn't well documented or can you send you spirals:

Try this:

/* * Fix for No thread-bound request found: Are you referring to request attributes */ def webRequest = RequestContextHolder.getRequestAttributes() if(!webRequest) { def servletContext = ServletContextHolder.getServletContext() def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) webRequest = grails.util.GrailsWebMockUtil.bindMockWebRequest(applicationContext) } 

You will need spring test in your build.gradle

 compile 'org.springframework:spring-test:2.5' 

There is a grails 2 branch so follow the same class in the other branch if it is grails 2

Sign up to request clarification or add additional context in comments.

1 Comment

This still works with ServiceUnitTest in Grails 5, I was able to use the session when unit testing a service, at least with WebUtils.retrieveGrailsWebRequest().session.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.