Search code examples
springthymeleafopenhtmltopdf

Instantiate IWebContext inside JmsListener in Spring


I have a Spring app running as a rest api.

Let's assume that at some point, a message with some info is generated and stored in a AWS SQS queue.

When JMSListener is called, Im trying to generate a pdf report with thymeleaf and openhtmltopdf. I'm having troubles while instantiating IWebContext because it needs HttpServletRequest, HttpServletResponse, and Locale as params. Locale is not a problem as I could include it as a part of the SQS message, but I'm stuck with REQ and RES.

Code i'm using:

IWebContext ctx = new WebContext(¿REQUEST?, ¿RESPONSE?, servletContext, locale, mapParams);
String processedHtml = templateEngine.process(template, ctx);

try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    PdfRendererBuilder builder = new PdfRendererBuilder();
    builder.useSVGDrawer(new BatikSVGDrawer());
    builder.useFastMode();
    builder.withHtmlContent(processedHtml, baseUrl);
    builder.toStream(bos);
    builder.run();
    return bos.toByteArray();
} catch (Exception e) {
    logger.error("xxx");
}

As it is being called inside @JmsListener(destination = "${aws.sqs.queue.name}") annotated method, I cannot use none of the following options:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

Because:

RequestContextHolder.getRequestAttributes()

is always null.

Thanks and regards.


Solution

  • I don't think you should be using an IWebContext for this. Instead, just use org.thymeleaf.context.Context.