KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > servlets > reports > ReportServletAbstract


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/reports/ReportServletAbstract.java,v 1.8 2004/10/24 13:47:30 hkollmann Exp $
3  * $Revision: 1.8 $
4  * $Date: 2004/10/24 13:47:30 $
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.reports;
25
26
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import org.dbforms.config.DbFormsConfig;
32 import org.dbforms.config.DbFormsConfigRegistry;
33 import org.dbforms.config.ResultSetVector;
34 import org.dbforms.config.Table;
35
36 import org.dbforms.event.WebEvent;
37
38 import org.dbforms.taglib.DbFormTag;
39
40 import org.dbforms.util.MessageResourcesInternal;
41 import org.dbforms.util.PageContextBuffer;
42 import org.dbforms.util.ParseUtil;
43 import org.dbforms.util.Util;
44 import org.dbforms.util.external.FileUtil;
45
46 import java.io.IOException JavaDoc;
47 import java.io.PrintWriter JavaDoc;
48
49 import java.util.Collection JavaDoc;
50 import java.util.Iterator JavaDoc;
51 import java.util.Vector JavaDoc;
52
53 import javax.servlet.ServletContext JavaDoc;
54 import javax.servlet.ServletException JavaDoc;
55 import javax.servlet.ServletOutputStream JavaDoc;
56 import javax.servlet.http.HttpServlet JavaDoc;
57 import javax.servlet.http.HttpServletRequest JavaDoc;
58 import javax.servlet.http.HttpServletResponse JavaDoc;
59 import javax.servlet.jsp.PageContext JavaDoc;
60
61 /**
62  * This is the abstract base class for generating reports.
63  *
64  * @author Henner Kollmann
65  */

66 public abstract class ReportServletAbstract extends HttpServlet JavaDoc {
67
68     private static Log logCat = LogFactory.getLog(ReportServletAbstract.class
69             .getName());
70
71     private static final String JavaDoc REPORTCONFIGDIR = "reportdirs";
72
73     private String JavaDoc[] reportdirs;
74
75     /**
76      * Basic servlet method, answers requests from the browser.
77      *
78      * @param request
79      * HTTPServletRequest
80      * @param response
81      * HTTPServletResponse
82      *
83      * @throws ServletException
84      * if there is a servlet problem.
85      * @throws IOException
86      * if there is an I/O problem.
87      */

88     public final void doGet(HttpServletRequest JavaDoc request,
89             HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
90         process(request, response);
91     }
92
93     /**
94      * Basic servlet method, answers requests fromt the browser.
95      *
96      * @param request
97      * HTTPServletRequest
98      * @param response
99      * HTTPServletResponse
100      *
101      * @throws ServletException
102      * if there is a servlet problem.
103      * @throws IOException
104      * if there is an I/O problem.
105      */

106     public final void doPost(HttpServletRequest JavaDoc request,
107             HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
108         process(request, response);
109     }
110
111     /**
112      * Initialize this servlet.
113      *
114      * @exception ServletException
115      * if we cannot configure ourselves correctly
116      */

117     public void init() throws ServletException JavaDoc {
118         String JavaDoc value = getServletConfig().getInitParameter(REPORTCONFIGDIR);
119         if (value == null) {
120             value = "WEB-INF/reports/";
121         }
122         reportdirs = StringUtils.split(value, ',');
123     }
124
125     /**
126      * generates a report.
127      *
128      * @param reportFileFullName
129      * filename of report to process reportHTTPServletRequest
130      * generated by getReportFile! getReportFile should be called
131      * before fetching data, so that error handling of report not
132      * found e.g. could be processed first!
133      * @param dataSource
134      * data for the report
135      * @param context
136      * ServletContext
137      * @param request
138      * HTTPServletRequest
139      * @param response
140      * HTTPServletResponse
141      */

142     protected abstract ReportWriter processReport(String JavaDoc reportFileFullName,
143             JRDataSourceAbstract dataSource, ServletContext JavaDoc context,
144             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response);
145
146     protected abstract String JavaDoc getReportFileExtension();
147
148     protected final void handleException(HttpServletRequest JavaDoc request,
149             HttpServletResponse JavaDoc response, Exception JavaDoc e) {
150         sendErrorMessage(request, response, MessageResourcesInternal
151                 .getMessage("dbforms.reports.exception", request.getLocale(),
152                         new String JavaDoc[] { e.getMessage() }));
153     }
154
155     private final void handleNoData(HttpServletRequest JavaDoc request,
156             HttpServletResponse JavaDoc response) {
157         sendErrorMessage(request, response, MessageResourcesInternal
158                 .getMessage("dbforms.reports.nodata", request.getLocale()));
159     }
160
161     private final void sendErrorMessage(HttpServletRequest JavaDoc request,
162             HttpServletResponse JavaDoc response, String JavaDoc message) {
163         try {
164             Vector errors = (Vector) request.getAttribute("errors");
165             errors.add(new Exception JavaDoc(message));
166
167             String JavaDoc fue = ParseUtil.getParameter(request, "source");
168             String JavaDoc contextPath = request.getContextPath();
169
170             if (!Util.isNull(fue)) {
171                 fue = fue.substring(contextPath.length());
172             }
173
174             if (Util.isNull(fue)) {
175                 sendErrorMessageText(response, message);
176             } else {
177                 request.getRequestDispatcher(fue).forward(request, response);
178             }
179         } catch (Exception JavaDoc ex) {
180             logCat.error("sendErrorMessage", ex);
181             sendErrorMessageText(response, message);
182         }
183     }
184
185     protected void compileReport(ServletContext JavaDoc context,
186             String JavaDoc reportFile) throws Exception JavaDoc {
187     };
188
189     /**
190      * generates a report from request. Tries to get data from DbForms.
191      *
192      * @param request
193      * HTTPServletRequest
194      * @param response
195      * HTTPServletResponse
196      */

197     protected void process(HttpServletRequest JavaDoc request,
198             HttpServletResponse JavaDoc response) {
199         // create report name
200
try {
201             String JavaDoc reportFile = getReportFileFullName(request.getPathInfo(),
202                     getServletContext(), request, response);
203
204             if (!Util.isNull(reportFile)) {
205                 compileReport(getServletContext(), reportFile);
206                 JRDataSourceAbstract dataSource = getDataForReport(request, response);
207                 if (!response.isCommitted()) {
208                     if (dataSource == null) {
209                         handleNoData(request, response);
210                     } else {
211                         ReportWriter res = processReport(reportFile,
212                                 dataSource, getServletContext(), request,
213                                 response);
214                         if (!response.isCommitted()) {
215                             if (res == null) {
216                                 handleNoOutput(request, response);
217                             } else {
218                                 processOutput(res, request, response);
219                             }
220                         }
221                     }
222                 }
223             }
224         } catch (Exception JavaDoc e) {
225             logCat.error("process", e);
226             handleException(request, response, e);
227         }
228     }
229
230     private void processOutput(ReportWriter out, HttpServletRequest JavaDoc request,
231             HttpServletResponse JavaDoc response) throws Exception JavaDoc {
232         if ((out.data == null) && (out.data.size() == 0)) {
233             handleNoOutput(request, response);
234             return;
235         }
236         response.setHeader("Expires", "0");
237         response.setHeader("Cache-Control",
238                 "must-revalidate, post-check=0, pre-check=0");
239         response.setHeader("Pragma", "public");
240         if (!Util.isNull(out.fileName)) {
241             response.setHeader("Content-disposition", "inline; filename="
242                     + out.fileName);
243         }
244         if (!Util.isNull(out.mimeType)) {
245             response.setContentType(out.mimeType);
246         }
247         // Send the output stream to the client
248
response.setContentLength(out.data.size());
249         ServletOutputStream JavaDoc outputStream = response.getOutputStream();
250         try {
251             out.data.writeTo(outputStream);
252             outputStream.flush();
253         } finally {
254             outputStream.close();
255         }
256     }
257
258     private String JavaDoc getReportFileFullName(String JavaDoc reportFileName,
259             ServletContext JavaDoc context, HttpServletRequest JavaDoc request,
260             HttpServletResponse JavaDoc response) {
261         String JavaDoc reportFile = null;
262         
263         try {
264             boolean found = false;
265             for (int i = 0; i < reportdirs.length; i++) {
266                 reportFile = context
267                         .getRealPath(reportdirs[i] + reportFileName) ;
268                 String JavaDoc testName = reportFile + getReportFileExtension();
269                 if (FileUtil.fileExists(testName)) {
270                     found = true;
271                     break;
272                 }
273             }
274             if (!found) {
275                 handleNoReport(request, response);
276                 reportFile = null;
277             }
278         } catch (Exception JavaDoc e) {
279             handleException(request, response, e);
280         }
281
282         return reportFile;
283     }
284
285     private void handleNoReport(HttpServletRequest JavaDoc request,
286             HttpServletResponse JavaDoc response) {
287         sendErrorMessage(request, response, MessageResourcesInternal
288                 .getMessage("dbforms.reports.noreport", request.getLocale(),
289                         new String JavaDoc[] { request.getPathInfo() }));
290     }
291
292     /**
293      * get a JRDataSource for report data. Source can be a Collection, an rsv,
294      * or dbform if session variable "jasper.input" is set, it must point to a
295      * Collection object if session variable "jasper.rsv" is set, it must point
296      * to a ResultSetVector object otherwise the enclosing dbform is used for
297      * data
298      *
299      * @param context
300      * @param request
301      * @param response
302      *
303      * @return
304      */

305     private JRDataSourceAbstract getDataForReport(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
306         JRDataSourceAbstract dataSource = null;
307         Table table = null;
308         ResultSetVector rsv = null;
309
310         try {
311             // is the datasource a Collection ?
312
Object JavaDoc input = request.getAttribute("jasper.input");
313             if (input == null)
314                 input = request.getSession().getAttribute("jasper.input");
315             if ((input != null) && (input instanceof Collection JavaDoc)) {
316                 Iterator JavaDoc iter = ((Collection JavaDoc) input).iterator();
317                 dataSource = new JRDataSourceIter(null, iter);
318                 return dataSource;
319             }
320
321             // check if we are using a ResultSetVector passed by user
322
rsv = (ResultSetVector) request.getAttribute("jasper.rsv");
323             if (rsv == null)
324                 rsv = (ResultSetVector) request.getSession().getAttribute("jasper.rsv");
325             if (rsv != null) {
326                 logCat.info("get resultsetvector rsv= " + rsv.size());
327                 if (rsv.size() == 0) {
328                     handleNoData(request, response);
329                 } else {
330                     dataSource = new JRDataSourceRSV(rsv.getAttributes(), rsv);
331                 }
332                 return dataSource;
333             }
334
335             PageContext JavaDoc pageContext = new PageContextBuffer();
336             pageContext
337                     .initialize(this, request, response, null, true, 0, true);
338
339             // Create form to get the resultsetvector
340
WebEvent webEvent = (WebEvent) request.getAttribute("webEvent");
341             table = webEvent.getTable();
342
343             if (table == null) {
344                 logCat.error("table==null");
345             }
346
347             if ((webEvent != null) && (table != null) && (table.getId() != -1)) {
348                 // Generate DataSource for JasperReports from call to DbForm
349
DbFormsConfig config = null;
350
351                 try {
352                     config = DbFormsConfigRegistry.instance().lookup();
353                 } catch (Exception JavaDoc e) {
354                     logCat.error(e);
355                     throw new ServletException JavaDoc(e);
356                 }
357
358                 String JavaDoc tableName = config.getTable(webEvent.getTable().getId())
359                         .getName();
360
361                 // Simulate call to DbFormTag to get resultsetvector
362
DbFormTag form = new DbFormTag();
363                 form.setPageContext(pageContext);
364                 form.setTableName(tableName);
365
366                 String JavaDoc maxRows = ParseUtil
367                         .getParameter(request, "MaxRows", "*");
368                 form.setMaxRows(maxRows);
369                 form.setFollowUp("");
370                 form.setAutoUpdate("false");
371
372                 // set the source attribute to the requestURI.
373
// So the form will think that the source is equal to the target
374
// and will use order constraints
375
// Source must be saved and restored - we need it e.g. in error
376
// processing again!
377
String JavaDoc saveSource = (String JavaDoc) request.getAttribute("source");
378                 String JavaDoc refSource = request.getRequestURI();
379
380                 if (request.getQueryString() != null) {
381                     refSource += ("?" + request.getQueryString());
382                 }
383
384                 request.setAttribute("source", refSource);
385                 form.doStartTag();
386                 request.setAttribute("source", saveSource);
387
388                 rsv = form.getResultSetVector();
389                 logCat.info("get resultsetvector rsv= " + rsv.size());
390
391                 if (rsv.size() == 0) {
392                     handleNoData(request, response);
393                 } else {
394                     dataSource = new JRDataSourceRSV(rsv.getAttributes(), rsv);
395                 }
396
397                 form.doFinally();
398             }
399         } catch (Exception JavaDoc e) {
400             logCat.error(e);
401         }
402
403         return dataSource;
404     }
405
406     private void sendErrorMessageText(HttpServletResponse JavaDoc response,
407             String JavaDoc message) {
408         try {
409             PrintWriter JavaDoc out = response.getWriter();
410             response.setContentType("text/html");
411             out.println("<html><body><h1>ERROR</h1><p>");
412             out.println(message);
413             out.println("</p></body></html>");
414             out.flush();
415             out.close();
416         } catch (IOException JavaDoc ioe2) {
417             logCat.error("sendErrorMessageText", ioe2);
418         }
419     }
420
421     private void handleNoOutput(HttpServletRequest JavaDoc request,
422             HttpServletResponse JavaDoc response) {
423         sendErrorMessage(request, response, MessageResourcesInternal
424                 .getMessage("dbforms.reports.nooutput", request.getLocale()));
425     }
426
427 }
428
Popular Tags