KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > ext > controller > ReportServer


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2003 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64 package com.jcorporate.expresso.ext.controller;
65
66 import com.jcorporate.expresso.core.controller.ControllerException;
67 import com.jcorporate.expresso.core.controller.ControllerRequest;
68 import com.jcorporate.expresso.core.controller.ControllerResponse;
69 import com.jcorporate.expresso.core.controller.ErrorCollection;
70 import com.jcorporate.expresso.core.controller.Input;
71 import com.jcorporate.expresso.core.controller.NonHandleableException;
72 import com.jcorporate.expresso.core.controller.ServletControllerRequest;
73 import com.jcorporate.expresso.core.controller.State;
74 import com.jcorporate.expresso.core.controller.Transition;
75 import com.jcorporate.expresso.core.db.DBException;
76 import com.jcorporate.expresso.core.dbobj.Schema;
77 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
78 import com.jcorporate.expresso.core.dbobj.ValidValue;
79 import com.jcorporate.expresso.ext.report.ExpressoReport;
80 import com.jcorporate.expresso.ext.report.MultiFormatReport;
81 import com.jcorporate.expresso.ext.report.ReportException;
82 import com.jcorporate.expresso.kernel.util.ClassLocator;
83 import com.jcorporate.expresso.services.dbobj.SchemaList;
84 import org.apache.log4j.Logger;
85
86 import javax.servlet.http.HttpServletResponse JavaDoc;
87 import java.util.Iterator JavaDoc;
88 import java.util.Vector JavaDoc;
89
90
91 /**
92  * Report server is a generic controller for dishing up reports. It does not
93  * have inherant Report security other than controller security. For
94  * additional features such as built-in JasperReports capabilities (and thus
95  * the ability to send output in CSV, XML, Excel, Html, or PDF formats], built
96  * in Report-by-report security and save on server features, consider
97  * JCorporate's eContent commercial content management framework. See <a
98  * HREF="http://www.jcorporate.com/econtent.html" target="_blank">
99  * http://www.jcorporate.com/econtent.html</a> for details.
100  * <p/>
101  * <p/>
102  * Todo items include saving the report to a file and then sending that file
103  * instead so that we can set the content length so items like the pdf files
104  * work work properly in IE.
105  * </p>
106  *
107  * @author Michael Rimov
108  */

109 public class ReportServer
110         extends com.jcorporate.expresso.core.controller.DBController {
111
112     /**
113      * The Log4j Logger
114      */

115     public static final transient Logger log = Logger.getLogger(ReportServer.class);
116
117     /**
118      * Creates an instance of ReportServer. Call setRequestingUid() and
119      * setDataContext() before using.
120      *
121      * @throws ControllerException upon initialization Exception
122      * @see com.jcorporate.expresso.core.dbobj.SecuredDBObject#SecuredDBObject
123      */

124     public ReportServer() throws ControllerException {
125         super();
126
127         State s = new State("prompt", "Prompt");
128         this.addState(s);
129         this.setInitialState("prompt");
130
131         s = new State("selectReport", "Select Report");
132         s.addRequiredParameter("SchemaClass");
133         this.addState(s);
134
135         s = new State("setParameters", "Set Report Parameters");
136         s.addRequiredParameter("ReportClass");
137         s.addOptionalParameter("ReportCode");
138         this.addState(s);
139
140         s = new State("processReport", "Process Report");
141         s.addRequiredParameter("ReportClass");
142         s.addOptionalParameter("ReportCode");
143         s.addOptionalParameter("ReportFormat");
144         this.addState(s);
145     }
146
147     /**
148      * Override of Controller.getTitle() to provide a meaningful name to this
149      * controller
150      *
151      * @return java.lang.String
152      */

153     public String JavaDoc getTitle() {
154         return "Expresso Report Server";
155     }
156
157     /**
158      * Instantiate an Expresso report based upon the 'ReportClass' parameter
159      * given in the ControllerRequest object
160      *
161      * @param request a ControllerRequest object with the 'ReportClass'
162      * parameter included.
163      * @return An ExpressoReport object fully instantiated
164      * @throws ControllerException upon instantiation exception
165      * @throws ClassNotFoundException for special handling by the calling
166      * object if the class was not found.
167      */

168     protected ExpressoReport instantiateReport(ControllerRequest request)
169             throws ControllerException, ClassNotFoundException JavaDoc {
170         String JavaDoc reportClass = request.getParameter("ReportClass");
171
172         ExpressoReport report = null;
173
174         try {
175             report = (ExpressoReport) ClassLocator.loadClass(reportClass)
176                     .newInstance();
177         } catch (IllegalAccessException JavaDoc ex) {
178             throw new ControllerException("No public default constructor found in class: " + reportClass,
179                     ex);
180         } catch (InstantiationException JavaDoc ex) {
181             throw new ControllerException("Unable to construct new instance of object: " + reportClass, ex);
182         } catch (ClassCastException JavaDoc ex) {
183             throw new ControllerException("Class Requested: " + reportClass +
184                     " was not an Expresso Report", ex);
185         }
186
187         return report;
188     }
189
190     /**
191      * Process the actual report.
192      *
193      * @param request The <code>ControllerRequest</code> object handed to us by
194      * the framework.
195      * @param response The <code>ControllerResponse</code> object handed to us
196      * by the framework.
197      * @throws ControllerException upon error
198      * @throws NonHandleableException upon fatal error
199      */

200     protected void runProcessReportState(ControllerRequest request,
201                                          ControllerResponse response)
202             throws ControllerException, NonHandleableException {
203         try {
204             ExpressoReport report = instantiateReport(request);
205             java.util.Map JavaDoc paramMap = new java.util.HashMap JavaDoc(request.getParameters());
206             report.setReportParameters(paramMap);
207             report.setDataContext(request.getDataContext());
208             report.setReportCode(request.getParameter("ReportCode"));
209
210             if (report instanceof MultiFormatReport) {
211                 ((MultiFormatReport) report).setReportFormat(request.getParameter("ReportFormat"));
212             }
213
214             if (!(request instanceof ServletControllerRequest)) {
215                 response.addError("To run the report, report server " +
216                         "must be run inside a Servlet environment");
217                 transition("prompt", request, response);
218
219                 return;
220             }
221
222             ServletControllerRequest scr = (ServletControllerRequest) request;
223             response.setCustomResponse(true);
224
225             HttpServletResponse JavaDoc servResponse = scr.getHttpServletResponse();
226
227             servResponse.setHeader("Content-Disposition",
228                     "inline;filename=" + "ExpressoReport." +
229                     report.getReportFileExtension());
230
231             servResponse.setContentType(report.getReportMimeType());
232
233             java.io.OutputStream JavaDoc os = servResponse.getOutputStream();
234             report.printReport(os);
235
236             return;
237         } catch (ClassNotFoundException JavaDoc ex) {
238             ErrorCollection errs = new ErrorCollection();
239             log.error("Error, class not found: ", ex);
240             errs.addError("Class specified not found");
241             response.saveErrors(errs);
242             transition("prompt", request, response);
243         } catch (ReportException ex) {
244             log.error("Report exception: ", ex);
245             throw new ControllerException("Error processing report", ex);
246         } catch (java.io.IOException JavaDoc ex) {
247             log.warn("IO Exception sending report", ex);
248         }
249     }
250
251     /**
252      * Runs the Prompt state
253      *
254      * @param request The <code>ControllerRequest</code> object handed to us by
255      * the framework.
256      * @param response The <code>ControllerResponse</code> object handed to us
257      * by the framework.
258      * @throws ControllerException upon error
259      * @throws NonHandleableException upon fatal error
260      */

261     protected void runPromptState(ControllerRequest request,
262                                   ControllerResponse response)
263             throws ControllerException, NonHandleableException {
264         try {
265             /* ..and a schema */
266             Input chooseSchema = new Input();
267             chooseSchema.setLabel("Choose Schema");
268             chooseSchema.setName("SchemaClass");
269
270             Vector JavaDoc v2 = new Vector JavaDoc(2);
271             v2.addElement(new ValidValue("com.jcorporate.expresso." +
272                     "core.ExpressoSchema", "General"));
273
274             SchemaList sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
275             sl.setDataContext(request.getDataContext());
276
277             SchemaList oneSchema = null;
278
279             for (Iterator JavaDoc e = sl.searchAndRetrieveList("Descrip").iterator();
280                  e.hasNext();) {
281                 oneSchema = (SchemaList) e.next();
282                 v2.addElement(new ValidValue(oneSchema.getField("SchemaClass"),
283                         oneSchema.getField("Descrip")));
284             }
285
286             chooseSchema.setValidValues(v2);
287             response.addInput(chooseSchema);
288
289             response.add(new Transition("selectReport", this));
290             response.setTitle("Expresso Report Server");
291         } catch (DBException ex) {
292             log.error("Database Error Prompting for Report Schemas", ex);
293             throw new ControllerException("Database Access Error", ex);
294         }
295     }
296
297     /**
298      * Runs the Prompt state
299      *
300      * @param request The <code>ControllerRequest</code> object handed to us by
301      * the framework.
302      * @param response The <code>ControllerResponse</code> object handed to us
303      * by the framework.
304      * @throws ControllerException upon error
305      * @throws NonHandleableException upon fatal error
306      */

307     protected void runSelectReportState(ControllerRequest request,
308                                         ControllerResponse response)
309             throws ControllerException, NonHandleableException {
310         ErrorCollection ec = request.getErrorCollection();
311
312         if ((ec != null) && (ec.getErrorCount() > 0)) {
313             response.saveErrors(ec);
314             transition("prompt", request, response);
315
316             return;
317         }
318
319         try {
320             //Check that the schema is indeed installed.
321
SchemaList mySchema = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
322             mySchema.setDataContext(request.getDataContext());
323
324             String JavaDoc schemaClass = com.jcorporate.expresso.core.ExpressoSchema.class.getName();
325             mySchema.setField("SchemaClass", request.getParameter("SchemaClass"));
326
327             if (mySchema.find()) {
328                 schemaClass = request.getParameter("SchemaClass");
329             } else if (!com.jcorporate.expresso.core.ExpressoSchema.class.getName()
330                     .equals(request.getParameter("SchemaClass"))) {
331                 if (ec == null) {
332                     ec = new ErrorCollection();
333                 }
334
335                 ec.addError("Schema class: " +
336                         request.getParameter("SchemaClass") +
337                         " is not installed on this system");
338                 response.saveErrors(ec);
339                 transition("prompt", request, response);
340
341                 return;
342             }
343
344             Schema schema = (Schema) ClassLocator.loadClass(schemaClass)
345                     .newInstance();
346             Vector JavaDoc v = schema.getReports();
347
348             if ((v == null) || (v.size() == 0)) {
349                 if (ec == null) {
350                     ec = new ErrorCollection();
351                 }
352
353                 ec.addError("The requested schema doesn't have any reports defined");
354                 response.saveErrors(ec);
355                 transition("prompt", request, response);
356
357                 return;
358             }
359
360             Vector JavaDoc vv = new Vector JavaDoc(v.size());
361
362             for (Iterator JavaDoc i = v.iterator(); i.hasNext();) {
363                 ExpressoReport oneReport = (ExpressoReport) i.next();
364                 vv.add(new ValidValue(((Object JavaDoc) oneReport).getClass().getName(),
365                         oneReport.getTitle()));
366             }
367
368             Input chooseReport = new Input("ReportClass", "Report To Use");
369             chooseReport.setValidValues(vv);
370             response.add(chooseReport);
371
372             Transition t = new Transition("process", "Continue",
373                     this.getClass(), "setParameters");
374             response.add(t);
375             response.setTitle("Expresso Report Server");
376         } catch (DBException ex) {
377             throw new ControllerException("Database access error", ex);
378         } catch (ClassCastException JavaDoc ex) {
379             throw new ControllerException("Class loaded was not a schema", ex);
380         } catch (ClassNotFoundException JavaDoc ex) {
381             ErrorCollection errs = new ErrorCollection();
382             log.error("Error, class not found: ", ex);
383             errs.addError("Class specified not found");
384             response.saveErrors(errs);
385             transition("prompt", request, response);
386         } catch (IllegalAccessException JavaDoc ex) {
387             throw new ControllerException("No public default constructor found in class",
388                     ex);
389         } catch (InstantiationException JavaDoc ex) {
390             throw new ControllerException("Unable to construct new instance of object",
391                     ex);
392         }
393     }
394
395     /**
396      * Selects the report output format, if it is a MultiFormatted Report, and
397      * if not, provide a few parameters.
398      *
399      * @param request The <code>ControllerRequest</code> object handed to us by
400      * the framework.
401      * @param response The <code>ControllerResponse</code> object handed to us
402      * by the framework.
403      * @throws ControllerException upon error
404      * @throws NonHandleableException upon fatal error
405      */

406     protected void runSetParametersState(ControllerRequest request,
407                                          ControllerResponse response)
408             throws ControllerException, NonHandleableException {
409         ErrorCollection ec = request.getErrorCollection();
410
411         if ((ec != null) && (ec.getErrorCount() > 0)) {
412             response.saveErrors(ec);
413             transition("selectReport", request, response);
414
415             return;
416         }
417
418         try {
419             ExpressoReport report = this.instantiateReport(request);
420             String JavaDoc reportClass = ((Object JavaDoc) report).getClass().getName();
421
422             java.util.List JavaDoc paramNames = report.getParameterNames();
423
424             if ((paramNames != null) && (paramNames.size() > 0)) {
425                 //List all parameters
426
for (Iterator JavaDoc i = paramNames.iterator(); i.hasNext();) {
427                     String JavaDoc oneParamName = (String JavaDoc) i.next();
428                     Input input = new Input(oneParamName, oneParamName);
429                     input.setDefaultValue(report.getDefaultValue(oneParamName));
430                     response.add(input);
431                 }
432             }
433
434             Input reportCode = new Input("ReportCode", "Report Code");
435             response.add(reportCode);
436
437             //Add the dropdowns for format type if available
438
if (report instanceof MultiFormatReport) {
439                 java.util.List JavaDoc l = ((MultiFormatReport) report).getReportFormats();
440                 Input reportFormats = new Input("ReportFormat",
441                         "Select Output Format");
442                 reportFormats.setValidValues(new Vector JavaDoc(l));
443             }
444
445             Transition t = new Transition("prompt", "Start Again",
446                     this.getClass(), "prompt");
447             response.add(t);
448             t = new Transition("process", "Process Report", this.getClass(),
449                     "processReport");
450             t.addParam("ReportClass", reportClass);
451             response.add(t);
452             response.setTitle("Expresso Report Server");
453         } catch (ClassNotFoundException JavaDoc ex) {
454             ErrorCollection errs = new ErrorCollection();
455             log.error("Error, class not found: ", ex);
456             errs.addError("Class specified not found");
457             response.saveErrors(errs);
458             transition("prompt", request, response);
459         }
460     }
461 }
462
Popular Tags