001    package com.khubla.pragmatach.plugin.thymeleaf;
002    
003    import java.io.OutputStreamWriter;
004    import java.io.Writer;
005    import java.util.Map;
006    
007    import javax.servlet.http.HttpServletResponse;
008    
009    import org.thymeleaf.TemplateEngine;
010    import org.thymeleaf.context.Context;
011    import org.thymeleaf.templateresolver.ITemplateResolver;
012    
013    import com.khubla.pragmatach.framework.api.PragmatachException;
014    import com.khubla.pragmatach.framework.controller.impl.AbstractResponse;
015    
016    /**
017     * @author tome
018     */
019    public class ThymeleafResponse extends AbstractResponse {
020       /**
021        * template
022        */
023       private final String templateName;
024       /**
025        * context
026        */
027       private final Map<String, Object> context;
028       /**
029        * resolver
030        */
031       private final ITemplateResolver templateResolver;
032    
033       public ThymeleafResponse(Map<String, String> cacheHeaders, String templateName, Map<String, Object> context, ITemplateResolver templateResolver) {
034          super(cacheHeaders);
035          this.templateName = templateName;
036          this.context = context;
037          this.templateResolver = templateResolver;
038       }
039    
040       @Override
041       public String getContentType() throws PragmatachException {
042          return CONTENT_TYPE_HTML;
043       }
044    
045       @Override
046       public Map<String, String> getHeaders() throws PragmatachException {
047          return super.getCacheHeaders();
048       }
049    
050       @Override
051       public void render(HttpServletResponse httpServletResponse) throws PragmatachException {
052          try {
053             final Writer writer = new OutputStreamWriter(httpServletResponse.getOutputStream());
054             final TemplateEngine templateEngine = new TemplateEngine();
055             templateEngine.setTemplateResolver(templateResolver);
056             final Context ctx = new Context();
057             ctx.setVariables(context);
058             templateEngine.process(templateName, ctx, writer);
059             writer.flush();
060          } catch (final Exception e) {
061             throw new PragmatachException("Exception in render", e);
062          }
063       }
064    }