View Javadoc

1   /*
2    * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/JasperReportServlet.java,v 1.8 2005/11/30 20:31:18 hkollmann Exp $
3    * $Revision: 1.8 $
4    * $Date: 2005/11/30 20:31:18 $
5    *
6    * DbForms - a Rapid Application Development Framework
7    * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8    *
9    * This library is free software; you can redistribute it and/or
10   * modify it under the terms of the GNU Lesser General Public
11   * License as published by the Free Software Foundation; either
12   * version 2.1 of the License, or (at your option) any later version.
13   *
14   * This library is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17   * Lesser General Public License for more details.
18   *
19   * You should have received a copy of the GNU Lesser General Public
20   * License along with this library; if not, write to the Free Software
21   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22   */
23  
24  package org.dbforms.servlets;
25  
26  import net.sf.jasperreports.engine.JRException;
27  import net.sf.jasperreports.engine.JRExporter;
28  import net.sf.jasperreports.engine.JRExporterParameter;
29  import net.sf.jasperreports.engine.JasperCompileManager;
30  import net.sf.jasperreports.engine.JasperFillManager;
31  import net.sf.jasperreports.engine.JasperPrint;
32  import net.sf.jasperreports.engine.export.JRCsvExporter;
33  import net.sf.jasperreports.engine.export.JRPdfExporter;
34  import net.sf.jasperreports.engine.export.JRXlsExporter;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  
39  import org.dbforms.config.DbFormsConfig;
40  import org.dbforms.config.DbFormsConfigRegistry;
41  
42  import org.dbforms.event.AbstractWebEvent;
43  
44  import org.dbforms.servlets.reports.AbstractJRDataSource;
45  import org.dbforms.servlets.reports.ReportParameter;
46  import org.dbforms.servlets.reports.AbstractReportServlet;
47  import org.dbforms.servlets.reports.ReportWriter;
48  
49  import org.dbforms.util.ParseUtil;
50  import org.dbforms.util.SqlUtil;
51  import org.dbforms.util.external.FileUtil;
52  
53  import java.io.ByteArrayOutputStream;
54  import java.io.File;
55  
56  import java.sql.Connection;
57  
58  import java.util.HashMap;
59  import java.util.Map;
60  
61  import javax.servlet.ServletContext;
62  import javax.servlet.ServletException;
63  import javax.servlet.http.HttpServletRequest;
64  import javax.servlet.http.HttpServletResponse;
65  
66  
67  
68  /***
69   * This servlet starts a JasperReport.
70   *
71   * @author Henner Kollmann
72   */
73  public class JasperReportServlet extends AbstractReportServlet {
74     /*** DOCUMENT ME! */
75     private static Log logCat = LogFactory.getLog(JasperReportServlet.class
76                                                   .getName());
77     private static final String REPORTFILEEXTENSION = ".jrxml";
78  
79  
80     /*** DOCUMENT ME! */
81     private static final String REPORTTYPEPARAM = "reporttype";
82  
83     /***
84      * DOCUMENT ME!
85      *
86      * @return DOCUMENT ME!
87      */
88     protected String getReportFileExtension() {
89        return REPORTFILEEXTENSION;
90     }
91  
92  
93     /***
94      * DOCUMENT ME!
95      *
96      * @param context DOCUMENT ME!
97      * @param reportFile DOCUMENT ME!
98      *
99      * @throws Exception DOCUMENT ME!
100     */
101    protected void compileReport(ServletContext context,
102                                 String         reportFile)
103                          throws Exception {
104       logCat.info("=== user dir " + FileUtil.dirname(reportFile));
105       System.setProperty("user.dir", FileUtil.dirname(reportFile));
106 
107       File   dir  = FileUtil.getFile(FileUtil.dirname(reportFile));
108       File[] list = dir.listFiles();
109 
110       for (int i = 0; i < list.length; i++) {
111          String s   = FileUtil.removeExtension(list[i].getPath());
112          String ext = "." + FileUtil.getExtension(list[i].getPath());
113 
114          if (s.startsWith(reportFile) && (ext.equals(getReportFileExtension()))) {
115             File xmlFile    = list[i];
116             File jasperFile = FileUtil.getFile(s + ".jasper");
117 
118             if (!jasperFile.exists()
119                       || (xmlFile.lastModified() > jasperFile.lastModified())) {
120                compileJasper(context, xmlFile.getPath());
121             }
122          }
123       }
124    }
125 
126 
127    /***
128     * generates a report.
129     *
130     * @param reportFileFullName filename of report to process
131     *        reportHTTPServletRequest generated by getReportFile!
132     *        getReportFile should be called before fetching data, so that
133     *        error handling of report not found e.g. could be processed first!
134     * @param dataSource data for the report
135     * @param context ServletContext
136     * @param request HTTPServletRequest
137     * @param response HTTPServletResponse
138     *
139     * @return DOCUMENT ME!
140     */
141    protected ReportWriter processReport(String               reportFileFullName,
142                                         AbstractJRDataSource dataSource,
143                                         ServletContext       context,
144                                         HttpServletRequest   request,
145                                         HttpServletResponse  response) {
146       /*
147        * Grunikiewicz.philip@hydro.qc.ca 2004-01-14
148        *
149        * In order to correct problem with displaying dynamically generated PDF
150        * files in IE, I followed the suggestions provided in the iText library
151        * FAQ. This simply meant using a ByteArrayOutputStream and not a byte
152        * array as previously coded.
153        */
154       ReportWriter res = new ReportWriter();
155 
156       try {
157          // generate parameter map
158          DbFormsConfig config = null;
159 
160          try {
161             config = DbFormsConfigRegistry.instance()
162                                           .lookup();
163          } catch (Exception e) {
164             logCat.error("processReport", e);
165             throw new ServletException(e);
166          }
167 
168          try {
169             // Fill the report with data
170             JasperPrint jPrint   = null;
171             AbstractWebEvent    webEvent = (AbstractWebEvent) request.getAttribute("webEvent");
172             Connection  con      = null;
173 
174             if ((webEvent != null) && (webEvent.getTable() == null)) {
175                con = config.getConnection();
176             } else {
177                con = config.getConnection(getConnectionName(request));
178             }
179 
180             try {
181                ReportParameter repParam = new ReportParameter(context, request,
182                                                               dataSource
183                                                               .getAttributes(),
184                                                               con,
185                                                               FileUtil.dirname(reportFileFullName)
186                                                               + File.separator);
187                Map             map = new HashMap();
188                map.put("PARAM", repParam);
189                jPrint = JasperFillManager.fillReport(reportFileFullName
190                                                      + ".jasper", map,
191                                                      dataSource);
192             } catch (Exception e) {
193                logCat.error("processReport", e);
194             } finally {
195                SqlUtil.closeConnection(con);
196             }
197 
198             if ((jPrint == null) || (jPrint.getPages()
199                                                  .size() == 0)) {
200                return null;
201             } else {
202                String outputFormat = ParseUtil.getParameter(request,
203                                                             JasperReportServlet.REPORTTYPEPARAM,
204                                                             "PDF");
205 
206                if ("PDF".equals(outputFormat)) {
207                   res.mimeType = "application/pdf";
208                   res.data     = exportToPDF(jPrint);
209                   res.fileName = FileUtil.filename(reportFileFullName) + ".pdf";
210                } else if ("XLS".equals(outputFormat)) {
211                   res.mimeType = "application/msexcel";
212                   res.data     = exportToXLS(jPrint);
213                   res.fileName = FileUtil.filename(reportFileFullName) + ".xls";
214                } else if ("CSV".equalsIgnoreCase(outputFormat)) {
215                   res.mimeType = "text/comma-separated-values";
216                   res.data     = exportToCSV(jPrint);
217                   res.fileName = FileUtil.filename(reportFileFullName) + ".csv";
218                }
219                jPrint       = null;
220 
221                return res;
222             }
223          } catch (JRException e) {
224             logCat.error("processReport", e);
225             handleException(request, response, e);
226 
227             return null;
228          }
229       } catch (Exception e) {
230          handleException(request, response, e);
231 
232          return null;
233       }
234    }
235 
236 
237    /***
238     * DOCUMENT ME!
239     *
240     * @param request DOCUMENT ME!
241     *
242     * @return DOCUMENT ME!
243     */
244    private static String getConnectionName(HttpServletRequest request) {
245       AbstractWebEvent webEvent = (AbstractWebEvent) request.getAttribute("webEvent");
246       String   res = null;
247 
248       if ((webEvent != null) && (webEvent.getTable()
249                                                .getId() != -1)) {
250          res = ParseUtil.getParameter(request,
251                                       "invname_" + webEvent.getTable().getId());
252       }
253 
254       return res;
255    }
256 
257 
258    private void compileJasper(ServletContext context,
259                               String         reportFile)
260                        throws Exception {
261       logCat.info("=== start to compile " + reportFile);
262 
263       // Tomcat specific!! Other jsp engine may handle this different!!
264       String classpath = (String) context.getAttribute("org.apache.catalina.jsp_classpath");
265       logCat.info("=== used classpath " + classpath);
266       System.setProperty("jasper.reports.compile.class.path", classpath);
267 
268       try {
269          JasperCompileManager.compileReportToFile(reportFile);
270       } catch (Exception e) {
271          logCat.error("compile", e);
272          throw e;
273       }
274    }
275 
276 
277    private ByteArrayOutputStream exportToCSV(JasperPrint jasperPrint)
278                                       throws JRException {
279       ByteArrayOutputStream baos     = new ByteArrayOutputStream();
280       JRExporter            exporter = new JRCsvExporter();
281       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
282       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
283       exporter.exportReport();
284 
285       return baos;
286    }
287 
288 
289    private ByteArrayOutputStream exportToPDF(JasperPrint jasperPrint)
290                                       throws JRException {
291       ByteArrayOutputStream baos     = new ByteArrayOutputStream();
292       JRExporter            exporter = new JRPdfExporter();
293       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
294       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
295       exporter.exportReport();
296 
297       return baos;
298    }
299 
300 
301    private ByteArrayOutputStream exportToXLS(JasperPrint jasperPrint)
302                                       throws JRException {
303       ByteArrayOutputStream baos     = new ByteArrayOutputStream();
304       JRExporter            exporter = new JRXlsExporter();
305       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
306       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
307       exporter.exportReport();
308 
309       return baos;
310    }
311 }