KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > servlets > JasperReportServlet


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/JasperReportServlet.java,v 1.6 2004/10/25 20:41:49 hkollmann Exp $
3  * $Revision: 1.6 $
4  * $Date: 2004/10/25 20:41:49 $
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.WebEvent;
43
44 import org.dbforms.servlets.reports.JRDataSourceAbstract;
45 import org.dbforms.servlets.reports.ReportParameter;
46 import org.dbforms.servlets.reports.ReportServletAbstract;
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 JavaDoc;
54 import java.io.File JavaDoc;
55
56 import java.sql.Connection JavaDoc;
57
58 import java.util.HashMap JavaDoc;
59 import java.util.Map JavaDoc;
60
61 import javax.servlet.ServletContext JavaDoc;
62 import javax.servlet.ServletException JavaDoc;
63 import javax.servlet.http.HttpServletRequest JavaDoc;
64 import javax.servlet.http.HttpServletResponse JavaDoc;
65
66
67
68 /**
69  * This servlet starts a JasperReport.
70  *
71  * @author Henner Kollmann
72  */

73 public class JasperReportServlet extends ReportServletAbstract {
74    /** DOCUMENT ME! */
75    private static Log logCat = LogFactory.getLog(JasperReportServlet.class
76                                                  .getName());
77    private static final String JavaDoc REPORTFILEEXTENSION = ".jrxml";
78
79    /** DOCUMENT ME! */
80    private static final String JavaDoc REPORTNAMEPARAM = "reportname";
81
82    /** DOCUMENT ME! */
83    private static final String JavaDoc REPORTTYPEPARAM = "reporttype";
84
85    /**
86     * DOCUMENT ME!
87     *
88     * @return DOCUMENT ME!
89     */

90    protected String JavaDoc getReportFileExtension() {
91       return REPORTFILEEXTENSION;
92    }
93
94
95    /**
96     * DOCUMENT ME!
97     *
98     * @param context DOCUMENT ME!
99     * @param reportFile DOCUMENT ME!
100     *
101     * @throws Exception DOCUMENT ME!
102     */

103    protected void compileReport(ServletContext JavaDoc context,
104                                 String JavaDoc reportFile)
105                          throws Exception JavaDoc {
106       logCat.info("=== user dir " + FileUtil.dirname(reportFile));
107       System.setProperty("user.dir", FileUtil.dirname(reportFile));
108
109       File JavaDoc dir = FileUtil.getFile(FileUtil.dirname(reportFile));
110       File JavaDoc[] list = dir.listFiles();
111
112       for (int i = 0; i < list.length; i++) {
113          String JavaDoc s = FileUtil.removeExtension(list[i].getPath());
114          String JavaDoc ext = "." + FileUtil.getExtension(list[i].getPath());
115
116          if (s.startsWith(reportFile) && (ext.equals(getReportFileExtension()))) {
117             File JavaDoc xmlFile = list[i];
118             File JavaDoc jasperFile = FileUtil.getFile(s + ".jasper");
119
120             if (!jasperFile.exists()
121                       || (xmlFile.lastModified() > jasperFile.lastModified())) {
122                compileJasper(context, xmlFile.getPath());
123             }
124          }
125       }
126    }
127
128
129    /**
130     * generates a report.
131     *
132     * @param reportFileFullName filename of report to process
133     * reportHTTPServletRequest generated by getReportFile!
134     * getReportFile should be called before fetching data, so that
135     * error handling of report not found e.g. could be processed first!
136     * @param dataSource data for the report
137     * @param context ServletContext
138     * @param request HTTPServletRequest
139     * @param response HTTPServletResponse
140     *
141     * @return DOCUMENT ME!
142     */

143    protected ReportWriter processReport(String JavaDoc reportFileFullName,
144                                         JRDataSourceAbstract dataSource,
145                                         ServletContext JavaDoc context,
146                                         HttpServletRequest JavaDoc request,
147                                         HttpServletResponse JavaDoc response) {
148       /*
149        * Grunikiewicz.philip@hydro.qc.ca 2004-01-14
150        *
151        * In order to correct problem with displaying dynamically generated PDF
152        * files in IE, I followed the suggestions provided in the iText library
153        * FAQ. This simply meant using a ByteArrayOutputStream and not a byte
154        * array as previously coded.
155        */

156       ReportWriter res = new ReportWriter();
157
158       try {
159          // generate parameter map
160
DbFormsConfig config = null;
161
162          try {
163             config = DbFormsConfigRegistry.instance()
164                                           .lookup();
165          } catch (Exception JavaDoc e) {
166             logCat.error("processReport", e);
167             throw new ServletException JavaDoc(e);
168          }
169
170          try {
171             // Fill the report with data
172
JasperPrint jPrint = null;
173             WebEvent webEvent = (WebEvent) request.getAttribute("webEvent");
174             Connection JavaDoc con = null;
175
176             if ((webEvent != null) && (webEvent.getTable() == null)) {
177                con = config.getConnection();
178             } else {
179                con = config.getConnection(getConnectionName(request));
180             }
181
182             try {
183                ReportParameter repParam = new ReportParameter(context, request,
184                                                               dataSource
185                                                               .getAttributes(),
186                                                               con,
187                                                               FileUtil.dirname(reportFileFullName)
188                                                               + File.separator);
189                Map JavaDoc map = new HashMap JavaDoc();
190                map.put("PARAM", repParam);
191                jPrint = JasperFillManager.fillReport(reportFileFullName
192                                                      + ".jasper", map,
193                                                      dataSource);
194             } catch (Exception JavaDoc e) {
195                logCat.error("processReport", e);
196             } finally {
197                SqlUtil.closeConnection(con);
198             }
199
200             if ((jPrint == null) || (jPrint.getPages()
201                                                  .size() == 0)) {
202                return null;
203             } else {
204                String JavaDoc outputFormat = ParseUtil.getParameter(request,
205                                                             JasperReportServlet.REPORTTYPEPARAM,
206                                                             "PDF");
207
208                // create the output stream
209
String JavaDoc fName = "";
210
211                if ("PDF".equals(outputFormat)) {
212                   res.mimeType = "application/pdf";
213                   res.data = exportToPDF(jPrint);
214                   fName = FileUtil.filename(reportFileFullName) + ".pdf";
215                } else if ("XLS".equals(outputFormat)) {
216                   res.mimeType = "application/msexcel";
217                   res.data = exportToXLS(jPrint);
218                   fName = FileUtil.filename(reportFileFullName) + ".xls";
219                } else if ("CSV".equalsIgnoreCase(outputFormat)) {
220                   res.mimeType = "text/comma-separated-values";
221                   res.data = exportToCSV(jPrint);
222                   fName = FileUtil.filename(reportFileFullName) + ".csv";
223                }
224
225                res.fileName = ParseUtil.getParameter(request, REPORTNAMEPARAM,
226                                                      fName);
227                jPrint = null;
228
229                return res;
230             }
231          } catch (JRException e) {
232             logCat.error("processReport", e);
233             handleException(request, response, e);
234
235             return null;
236          }
237       } catch (Exception JavaDoc e) {
238          handleException(request, response, e);
239
240          return null;
241       }
242    }
243
244
245    /**
246     * DOCUMENT ME!
247     *
248     * @param request DOCUMENT ME!
249     *
250     * @return DOCUMENT ME!
251     */

252    private static String JavaDoc getConnectionName(HttpServletRequest JavaDoc request) {
253       WebEvent webEvent = (WebEvent) request.getAttribute("webEvent");
254       String JavaDoc res = null;
255
256       if ((webEvent != null) && (webEvent.getTable()
257                                                .getId() != -1)) {
258          res = ParseUtil.getParameter(request,
259                                       "invname_" + webEvent.getTable().getId());
260       }
261
262       return res;
263    }
264
265
266    private void compileJasper(ServletContext JavaDoc context,
267                               String JavaDoc reportFile)
268                        throws Exception JavaDoc {
269       logCat.info("=== start to compile " + reportFile);
270
271       // Tomcat specific!! Other jsp engine may handle this different!!
272
String JavaDoc classpath = (String JavaDoc) context.getAttribute("org.apache.catalina.jsp_classpath");
273       logCat.info("=== used classpath " + classpath);
274       System.setProperty("jasper.reports.compile.class.path", classpath);
275
276       try {
277          JasperCompileManager.compileReportToFile(reportFile);
278       } catch (Exception JavaDoc e) {
279          logCat.error("compile", e);
280          throw e;
281       }
282    }
283
284
285    private ByteArrayOutputStream JavaDoc exportToCSV(JasperPrint jasperPrint)
286                                       throws JRException {
287       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
288       JRExporter exporter = new JRCsvExporter();
289       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
290       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
291       exporter.exportReport();
292
293       return baos;
294    }
295
296
297    private ByteArrayOutputStream JavaDoc exportToPDF(JasperPrint jasperPrint)
298                                       throws JRException {
299       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
300       JRExporter exporter = new JRPdfExporter();
301       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
302       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
303       exporter.exportReport();
304
305       return baos;
306    }
307
308
309    private ByteArrayOutputStream JavaDoc exportToXLS(JasperPrint jasperPrint)
310                                       throws JRException {
311       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
312       JRExporter exporter = new JRXlsExporter();
313       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
314       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
315       exporter.exportReport();
316
317       return baos;
318    }
319 }
320
Popular Tags