KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/reports/LineReportServletAbstract.java,v 1.9 2004/10/24 13:47:30 hkollmann Exp $
3  * $Revision: 1.9 $
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 import org.apache.commons.beanutils.PropertyUtils;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30
31 import org.dbforms.util.Util;
32 import org.dbforms.util.external.FileUtil;
33
34 import java.io.BufferedReader JavaDoc;
35 import java.io.ByteArrayOutputStream JavaDoc;
36 import java.io.File JavaDoc;
37 import java.io.FileReader JavaDoc;
38 import java.io.OutputStream JavaDoc;
39
40 import javax.servlet.ServletContext JavaDoc;
41 import javax.servlet.ServletException JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44 import javax.servlet.http.HttpSession JavaDoc;
45
46 /**
47  * This servlet generates a comma separated values file (CSV). Data is read from
48  * the current dbForm, a Collection or a ResultSetVector The template file is in
49  * the reports directory with a .cr extension it consists of two lines of text,
50  * the first is a list of stirngs to use as header the second a list of comma
51  * separated field names. both lines must have the same number of elements.
52  * Normally the output file will use the first row as the headers. But if no
53  * header line is provided, then no headers are output and every row is data.
54  * usage: with a simple goto button: &lt;db:gotoButton destTable="web_parts"
55  * destination=" /reports/Artikel"/&gt; or for one record: &lt;db:gotoButton
56  * destTable="web_parts" keyToDestPos="currentRow"
57  * destination="/reports/Artikel" /&gt; Servlet mapping must be set to handle
58  * all /reports by this servlet!!! &lt;servlet/&gt;
59  * &lt;servlet-name/&gt;startreport&lt;/servlet-name/&gt;
60  * &lt;display-name/&gt;startreport&lt;/display-name/&gt;
61  * &lt;servlet-class/&gt;org.dbforms.StartReportServlet&lt;/servlet-class/&gt;
62  * &lt;/servlet&gt; &lt;servlet-mapping/&gt;
63  * &lt;servlet-name/&gt;startreport&lt;/servlet-name/&gt;
64  * &lt;url-pattern/&gt;/reports/&lt;/url-pattern/&gt; &lt;/servlet-mapping&gt;
65  * web.xml optional parameters reportdirs list of directories to search for
66  * report file reportMimeType mime type to send to browser Parameters
67  * filename=xyz.csv name the output file Support for grabbing data from a
68  * Collection or an existing ResultSetVector set session variable "jasper.input"
69  * to use a Collection object set session variable "jasper.rsv" to use a
70  * ResultSetVector object ex &ltc:set var="jasper.rsv" value="${rsv_xxxxx}"
71  * scope="session" /&gt
72  *
73  * @author Neal Katz
74  */

75 public abstract class LineReportServletAbstract extends ReportServletAbstract {
76     private static Log logCat = LogFactory
77             .getLog(LineReportServletAbstract.class);
78
79     protected abstract String JavaDoc getMimeType();
80
81     protected abstract String JavaDoc getFileExtension();
82
83     protected abstract void writeData(Object JavaDoc[] data) throws Exception JavaDoc;
84     protected abstract void openStream(OutputStream JavaDoc out) throws Exception JavaDoc;
85     protected abstract void closeStream(OutputStream JavaDoc out) throws Exception JavaDoc;
86
87     private static final String JavaDoc REPORTMIMETYPEPARAM = "reportMimeType";
88
89     private String JavaDoc mimeType = getMimeType();
90
91     private int rownum = 0;
92
93     public void init() throws ServletException JavaDoc {
94         super.init();
95         String JavaDoc value = getServletConfig().getInitParameter(REPORTMIMETYPEPARAM);
96         if (!Util.isNull(value)) {
97             mimeType = value;
98         }
99     }
100
101     protected String JavaDoc getReportFileExtension() {
102         return ".xr";
103     }
104
105     protected void writeHeader(String JavaDoc[] header) throws Exception JavaDoc {
106         writeData(header);
107     }
108
109     private Object JavaDoc getFieldValue(HttpServletRequest JavaDoc request,
110             JRDataSourceAbstract dataSource, String JavaDoc search) {
111         Object JavaDoc o = null;
112         search = search.replaceAll("__", ".");
113
114         if (search.startsWith("internal.")) {
115             search = search.substring(search.indexOf("internal."));
116             logCat.debug("Trying to find data for internal value: " + search);
117             o = getInternalValue(search);
118         } else if (search.startsWith("request.")) {
119             search = search.substring(search.indexOf("request."));
120             logCat.debug("Trying to find data for page context value: "
121                     + search);
122             o = getRequestValue(request, search);
123         } else if (search.startsWith("session.")) {
124             search = search.substring(search.indexOf("session."));
125             logCat.debug("Trying to find data for session value: " + search);
126             o = getSessionValue(request.getSession(), search);
127         } else {
128             logCat.debug("Trying to find data for field named: " + search);
129             o = dataSource.getFieldValue(search);
130         }
131         return o;
132
133     }
134
135     private Object JavaDoc getInternalValue(String JavaDoc search) {
136         Object JavaDoc obj = null;
137         try {
138             logCat.debug("Trying to find data for internal var : " + search);
139             if (search.equalsIgnoreCase("rownum")) {
140                 return new Integer JavaDoc(rownum);
141             }
142         } catch (Exception JavaDoc e) {
143             logCat.error("getInternalValue: " + e);
144         }
145
146         return obj;
147     }
148
149     private Object JavaDoc getRequestValue(HttpServletRequest JavaDoc request, String JavaDoc search) {
150         Object JavaDoc obj = null;
151         int pos;
152         try {
153             pos = search.indexOf(".");
154             if (pos == -1) {
155                 // simple type, 'search' is an object in the session
156
obj = request.getAttribute(search);
157             } else {
158                 // complex, 'search' is really a bean
159
// complex, 'search' is really a bean
160
String JavaDoc search_bean = search.substring(0, pos);
161                    search = search.substring(pos + 1);
162                    Object JavaDoc bean = request.getAttribute(search_bean);
163                    if (bean != null) {
164                       logCat.debug("calling PropertyUtils.getProperty " + search_bean
165                          + " " + search);
166                       obj = PropertyUtils.getProperty(bean, search);
167                    }
168             }
169         } catch (Exception JavaDoc e) {
170             logCat.error("getPageContextValue: " + e);
171         }
172
173         return obj;
174     }
175
176     private Object JavaDoc getSessionValue(HttpSession JavaDoc session, String JavaDoc search) {
177         Object JavaDoc obj = null;
178         int pos;
179         try {
180             pos = search.indexOf(".");
181             if (pos == -1) {
182                 // simple type, 'search' is an object in the session
183
obj = session.getAttribute(search);
184             } else {
185                    // complex, 'search' is really a bean
186
String JavaDoc search_bean = search.substring(0, pos);
187                    search = search.substring(pos + 1);
188                    Object JavaDoc bean = session.getAttribute(search_bean);
189                    if (bean != null) {
190                       logCat.debug("calling PropertyUtils.getProperty " + search_bean
191                          + " " + search);
192                       obj = PropertyUtils.getProperty(bean, search);
193                    }
194             }
195         } catch (Exception JavaDoc e) {
196             logCat.error("getSessionValue: " + e);
197         }
198
199         return obj;
200     }
201
202     private ReportWriter fillReport(HttpServletRequest JavaDoc request,
203             String JavaDoc[] header, String JavaDoc[] fields, JRDataSourceAbstract dataSource)
204             throws Exception JavaDoc {
205         ReportWriter res = new ReportWriter();
206         res.mimeType = mimeType;
207         res.data = new ByteArrayOutputStream JavaDoc();
208         res.fileName = getFileExtension();
209         openStream(res.data);
210         writeHeader(header);
211         // Write out the data
212
Object JavaDoc[] data = new Object JavaDoc[fields.length];
213         while (dataSource.next()) {
214             rownum++;
215             for (int i = 0; i < fields.length; i++) {
216                 data[i] = getFieldValue(request, dataSource, fields[i]);
217             }
218             writeData(data);
219         }
220         closeStream(res.data);
221         return res;
222     }
223
224     /**
225      * generates a report.
226      *
227      * @param reportFileFullName
228      * filename of report to process reportHTTPServletRequest
229      * generated by getReportFile! getReportFile should be called
230      * before fetching data, so that error handling of report not
231      * found e.g. could be processed first!
232      * @param dataSource
233      * data for the report
234      * @param context
235      * ServletContext
236      * @param request
237      * HTTPServletRequest
238      * @param response
239      * HTTPServletResponse
240      */

241     protected ReportWriter processReport(String JavaDoc reportFileFullName,
242             JRDataSourceAbstract dataSource, ServletContext JavaDoc context,
243             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
244
245         try {
246             File JavaDoc f = new File JavaDoc(reportFileFullName + getReportFileExtension());
247             BufferedReader JavaDoc in = new BufferedReader JavaDoc(new FileReader JavaDoc(f));
248             String JavaDoc line1 = in.readLine();
249             String JavaDoc line2 = in.readLine();
250             String JavaDoc fields = null;
251             String JavaDoc headers = null;
252             if (Util.isNull(line2)) {
253                 fields = line1;
254             } else {
255                 headers = line1;
256                 fields = line2;
257             }
258             if (Util.isNull(fields)) {
259                 logCat.error("no fields found");
260                 return null;
261             }
262             String JavaDoc[] reportFields = fields.split(",");
263             String JavaDoc[] headerFields;
264             if (headers != null) {
265                 headerFields = headers.split(",");
266             } else {
267                 headerFields = new String JavaDoc[] {};
268             }
269             if (reportFields.length != headerFields.length) {
270                 logCat.error("reportFields.length != headerFields.length");
271                 headerFields = reportFields;
272             }
273             if (reportFields.length == 0) {
274                 logCat.error("no fields found");
275                 return null;
276             }
277
278             ReportWriter res = fillReport(request, headerFields, reportFields,
279                     dataSource);
280             if (res != null) {
281                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
282                 buf.append(FileUtil.filename(reportFileFullName));
283                 buf.append(res.fileName);
284                 res.fileName = buf.toString();
285             }
286             return res;
287         } catch (Exception JavaDoc e) {
288             logCat.error("read report file", e);
289             handleException(request, response, e);
290             return null;
291         }
292     }
293     
294
295 }
296
Popular Tags