001 package com.khubla.pragmatach.plugin.velocity; 002 003 import java.io.ByteArrayInputStream; 004 import java.io.Reader; 005 import java.io.StringReader; 006 import java.io.StringWriter; 007 import java.io.Writer; 008 import java.util.Map; 009 010 import javax.servlet.http.HttpServletResponse; 011 012 import org.apache.commons.io.IOUtils; 013 import org.apache.velocity.VelocityContext; 014 import org.apache.velocity.app.VelocityEngine; 015 016 import com.khubla.pragmatach.framework.api.PragmatachException; 017 import com.khubla.pragmatach.framework.controller.impl.AbstractResponse; 018 019 /** 020 * @author tome 021 */ 022 public class VelocityResponse extends AbstractResponse { 023 /** 024 * template 025 */ 026 private final String template; 027 /** 028 * templatename 029 */ 030 private final String templateName; 031 /** 032 * context 033 */ 034 private final Map<String, Object> context; 035 /** 036 * velocity 037 */ 038 private final VelocityEngine velocityEngine = new VelocityEngine(); 039 040 public VelocityResponse(Map<String, String> cacheHeaders, String templateName, String template, Map<String, Object> context) { 041 super(cacheHeaders); 042 this.template = template; 043 this.context = context; 044 this.templateName = templateName; 045 } 046 047 @Override 048 public String getContentType() throws PragmatachException { 049 return CONTENT_TYPE_HTML; 050 } 051 052 @Override 053 public Map<String, String> getHeaders() throws PragmatachException { 054 return super.getCacheHeaders(); 055 } 056 057 @Override 058 public void render(HttpServletResponse httpServletResponse) throws PragmatachException { 059 try { 060 final VelocityContext velocityContext = new VelocityContext(context); 061 final Reader reader = new StringReader(template); 062 final Writer writer = new StringWriter(); 063 velocityEngine.evaluate(velocityContext, writer, templateName, reader); 064 final ByteArrayInputStream bais = new ByteArrayInputStream(writer.toString().getBytes()); 065 IOUtils.copy(bais, httpServletResponse.getOutputStream()); 066 } catch (final Exception e) { 067 throw new PragmatachException("Exception in render", e); 068 } 069 } 070 }