1 16 17 package org.springframework.web.servlet.view.jasperreports; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.util.HashMap ; 21 import java.util.Iterator ; 22 import java.util.Map ; 23 24 import javax.servlet.ServletOutputStream ; 25 import javax.servlet.http.HttpServletResponse ; 26 27 import net.sf.jasperreports.engine.JRExporter; 28 import net.sf.jasperreports.engine.JRExporterParameter; 29 import net.sf.jasperreports.engine.JasperPrint; 30 31 import org.springframework.ui.jasperreports.JasperReportsUtils; 32 import org.springframework.util.CollectionUtils; 33 import org.springframework.web.util.WebUtils; 34 35 49 public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasperReportsView { 50 51 54 private static final int OUTPUT_BYTE_ARRAY_INITIAL_SIZE = 4096; 55 56 57 61 protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) 62 throws Exception { 63 64 JRExporter exporter = createExporter(); 66 67 Map mergedExporterParameters = mergeExporterParameters(model); 69 if (!CollectionUtils.isEmpty(mergedExporterParameters)) { 70 exporter.setParameters(mergedExporterParameters); 71 } 72 73 if (useWriter()) { 74 76 String contentType = getContentType(); 78 String encoding = (String ) exporter.getParameter(JRExporterParameter.CHARACTER_ENCODING); 79 if (encoding != null) { 80 if (contentType != null && contentType.toLowerCase().indexOf(WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) { 82 contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding; 83 } 84 } 85 response.setContentType(contentType); 86 87 JasperReportsUtils.render(exporter, populatedReport, response.getWriter()); 89 } 90 91 else { 92 94 response.setContentType(getContentType()); 96 97 ByteArrayOutputStream baos = new ByteArrayOutputStream (OUTPUT_BYTE_ARRAY_INITIAL_SIZE); 100 JasperReportsUtils.render(exporter, populatedReport, baos); 101 102 response.setContentLength(baos.size()); 104 105 ServletOutputStream out = response.getOutputStream(); 107 baos.writeTo(out); 108 out.flush(); 109 } 110 } 111 112 117 protected Map mergeExporterParameters(Map model) { 118 Map mergedParameters = new HashMap (); 119 Map convertedExporterParameters = getConvertedExporterParameters(); 120 if (!CollectionUtils.isEmpty(convertedExporterParameters)) { 121 mergedParameters.putAll(convertedExporterParameters); 122 } 123 for (Iterator it = model.keySet().iterator(); it.hasNext();) { 124 Object key = it.next(); 125 if (key instanceof JRExporterParameter) { 126 Object value = model.get(key); 127 if (value instanceof String ) { 128 mergedParameters.put(key, value); 129 } 130 else { 131 if (logger.isWarnEnabled()) { 132 logger.warn("Ignoring exporter parameter [" + key + "]: value is not a String"); 133 } 134 } 135 } 136 } 137 return mergedParameters; 138 } 139 140 141 148 protected abstract JRExporter createExporter(); 149 150 157 protected abstract boolean useWriter(); 158 159 } 160 | Popular Tags |