KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > jpivot > print > PrintServlet


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  */

11 package com.tonbeller.jpivot.print;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.OutputStream JavaDoc;
17 import java.io.PrintWriter JavaDoc;
18 import java.io.StringWriter JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Map JavaDoc;
22 import java.io.File JavaDoc;
23
24 import org.apache.log4j.Logger;
25
26 import javax.servlet.ServletConfig JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import javax.servlet.http.HttpServlet JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32 import javax.xml.transform.Transformer JavaDoc;
33 import javax.xml.transform.dom.DOMSource JavaDoc;
34 import javax.xml.transform.stream.StreamResult JavaDoc;
35
36 import org.apache.fop.apps.Driver;
37 import org.apache.fop.apps.FOPException;
38 import org.apache.fop.configuration.Configuration;
39 import org.apache.fop.apps.Options;
40 import org.w3c.dom.Document JavaDoc;
41 import org.xml.sax.InputSource JavaDoc;
42
43 import com.tonbeller.jpivot.chart.ChartComponent;
44 import com.tonbeller.jpivot.table.TableComponent;
45 import com.tonbeller.wcf.component.RendererParameters;
46 import com.tonbeller.wcf.controller.RequestContext;
47 import com.tonbeller.wcf.controller.RequestContextFactoryFinder;
48 import com.tonbeller.wcf.utils.XmlUtils;
49 /**
50  *
51  * @author arosselet
52  * @version
53  */

54
55 public class PrintServlet extends HttpServlet JavaDoc {
56   private static Logger logger = Logger.getLogger(PrintServlet.class);
57   private static final int XML = 0;
58   private static final int PDF = 1;
59   String JavaDoc basePath;
60   String JavaDoc filename;
61
62   /** Initializes the servlet.
63    */

64   public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
65     super.init(config);
66     try {
67       // set base FOP FONT directory. The font config stuff will be looked for here
68
Configuration.put("fontBaseDir", config.getServletContext().getRealPath("/WEB-INF/jpivot/print/"));
69       // get the physical path for the config file
70
String JavaDoc fopConfigPath = config.getServletContext().getRealPath("/WEB-INF/jpivot/print/userconfig.xml");
71       // load the user proerties, contining the CustomFont font.
72
new Options(new File JavaDoc(fopConfigPath));
73
74     } catch (FOPException e) {
75       e.printStackTrace();
76       logger.info("FOP user config file not loaded");
77     } catch (Exception JavaDoc e) {
78       e.printStackTrace();
79       logger.info("FOP user config file not loaded");
80     }
81   }
82
83   /** Destroys the servlet.
84    */

85   public void destroy() {
86
87   }
88
89   /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
90    * @param request servlet request
91    * @param response servlet response
92    */

93
94   protected void processRequest(RequestContext context) throws ServletException JavaDoc, IOException JavaDoc {
95     HttpServletRequest JavaDoc request = context.getRequest();
96     HttpServletResponse JavaDoc response = context.getResponse();
97     if (request.getParameter("cube") != null && request.getParameter("type") != null) {
98       try {
99         String JavaDoc xslUri = null;
100         int type = Integer.parseInt(request.getParameter("type"));
101         switch (type) {
102         case XML:
103           xslUri = "/WEB-INF/jpivot/table/xls_mdxtable.xsl";
104           RendererParameters.setParameter(context.getRequest(), "mode", "excel", "request");
105           response.setContentType("application/vnd.ms-excel");
106           filename = "xls_export.xls";
107           break;
108         case PDF:
109           xslUri = "/WEB-INF/jpivot/table/fo_mdxtable.xsl";
110           RendererParameters.setParameter(context.getRequest(), "mode", "print", "request");
111           response.setContentType("application/pdf");
112           filename = "xls_export.pdf";
113           break;
114         }
115         if (xslUri != null) {
116           boolean xslCache = true;
117           // get references to needed elements
118
String JavaDoc tableRef = "table" + request.getParameter("cube");
119           String JavaDoc chartRef = "chart" + request.getParameter("cube");
120           String JavaDoc printRef = "print" + request.getParameter("cube");
121
122           Map JavaDoc parameters = new HashMap JavaDoc();
123
124           OutputStream JavaDoc outStream = response.getOutputStream();
125           PrintWriter JavaDoc out = new PrintWriter JavaDoc(outStream);
126           HttpSession JavaDoc session = request.getSession();
127           // set up filename for download.
128
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
129
130           // get TableComponent
131
TableComponent table = (TableComponent) context.getModelReference(tableRef);
132           // only proceed if table component exists
133
if (table != null) {
134             // add parameters from printConfig
135
PrintComponent printConfig = (PrintComponent) context.getModelReference(printRef);
136             if (printConfig != null) {
137               if (printConfig.isSetTableWidth()) {
138                 parameters.put(printConfig.PRINT_TABLE_WIDTH, new Double JavaDoc(printConfig.getTableWidth()));
139               }
140               if (printConfig.getReportTitle().trim().length() != 0) {
141                 parameters.put(printConfig.PRINT_TITLE, printConfig.getReportTitle().trim());
142               }
143               parameters.put(printConfig.PRINT_PAGE_ORIENTATION, printConfig.getPageOrientation());
144               parameters.put(printConfig.PRINT_PAPER_TYPE, printConfig.getPaperType());
145               if (printConfig.getPaperType().equals("custom")) {
146                 parameters.put(printConfig.PRINT_PAGE_WIDTH, new Double JavaDoc(printConfig.getPageWidth()));
147                 parameters.put(printConfig.PRINT_PAGE_HEIGHT, new Double JavaDoc(printConfig.getPageHeight()));
148               }
149               parameters.put(printConfig.PRINT_CHART_PAGEBREAK, new Boolean JavaDoc(printConfig.isChartPageBreak()));
150
151             }
152
153             // add parameters and image from chart if visible
154
ChartComponent chart = (ChartComponent) request.getSession().getAttribute(chartRef);
155             if (chart != null && chart.isVisible()) {
156
157               String JavaDoc host = request.getServerName();
158               int port = request.getServerPort();
159               String JavaDoc location = request.getContextPath();
160               String JavaDoc scheme = request.getScheme();
161
162               String JavaDoc chartServlet = scheme + "://" + host + ":" + port + location + "/GetChart";
163               parameters.put("chartimage", chartServlet + "?filename=" + chart.getFilename());
164               parameters.put("chartheight", new Integer JavaDoc(chart.getChartHeight()));
165               parameters.put("chartwidth", new Integer JavaDoc(chart.getChartWidth()));
166             }
167
168             //parameters.put("message",table.getReportTitle());
169
// add "context" and "renderId" to parameter map
170

171             //parameters.put("renderId", renderId);
172
parameters.put("context", context.getRequest().getContextPath());
173
174             // Some FOP-PDF versions require a complete URL, not a path
175
//parameters.put("contextUrl", createContextURLValue(context));
176

177             table.setDirty(true);
178             Document JavaDoc document = table.render(context);
179             table.setDirty(true);
180
181             DOMSource JavaDoc source = new DOMSource JavaDoc(document);
182             // set up xml transformation
183
Transformer JavaDoc transformer = XmlUtils.getTransformer(session, xslUri, xslCache);
184             for (Iterator JavaDoc it = parameters.keySet().iterator(); it.hasNext();) {
185               String JavaDoc name = (String JavaDoc) it.next();
186               Object JavaDoc value = parameters.get(name);
187               transformer.setParameter(name, value);
188             }
189             StringWriter JavaDoc sw = new StringWriter JavaDoc();
190             StreamResult JavaDoc result = new StreamResult JavaDoc(sw);
191             //do transform
192
transformer.transform(source, result);
193             sw.flush();
194
195             // if thisis XML, then we are done, so output xml file.
196
if (type == XML) {
197               System.out.println("Writing XLS");
198               response.setContentLength(sw.toString().length());
199               out.write(sw.toString());
200               RendererParameters.removeParameter(context.getRequest(), "mode", "excel", "request");
201               // process FO to PDF
202
} else {
203               // if this is PDF, then need to generate PDF from the FO xml
204
System.out.println("Creating PDF!");
205               try {
206                 ByteArrayInputStream JavaDoc bain = new ByteArrayInputStream JavaDoc(sw.toString().getBytes("UTF-8"));
207                 ByteArrayOutputStream JavaDoc baout = new ByteArrayOutputStream JavaDoc(16384);
208                 convertFO2PDF(bain, baout);
209                 final byte[] content = baout.toByteArray();
210                 response.setContentLength(content.length);
211                 outStream.write(content);
212                 RendererParameters.removeParameter(context.getRequest(), "mode", "print", "request");
213                 //convertXML2PDF(document.toString(), xslUri, outStream);
214
} catch (Exception JavaDoc e) {
215                 e.printStackTrace();
216               }
217             }
218             //close output streams
219
out.flush();
220             out.close();
221             outStream.flush();
222           }
223         }
224       } catch (Exception JavaDoc e) {
225         e.printStackTrace();
226       }
227     }
228   }
229
230   /**
231    * converts FO xml into PDF using the FOP processor
232    */

233   public void convertFO2PDF(ByteArrayInputStream JavaDoc bain, ByteArrayOutputStream JavaDoc baout) throws IOException JavaDoc, FOPException {
234
235     System.out.println("Construct driver");
236     Driver driver = new Driver();
237
238     System.out.println("Setup Renderer (output format)");
239     driver.setRenderer(Driver.RENDER_PDF);
240
241     try {
242       driver.setOutputStream(baout);
243       System.out.println("Setup input");
244       try {
245         driver.setInputSource(new InputSource JavaDoc(bain));
246
247         System.out.println("Process FO");
248         driver.run();
249         System.out.println("PDF file generation completed");
250       } finally {
251       }
252     } finally {
253     }
254   }
255
256   /** Handles the HTTP <code>GET</code> method.
257    * @param request servlet request
258    * @param response servlet response
259    */

260   protected void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
261     doPost(request, response);
262   }
263
264   /** Handles the HTTP <code>POST</code> method.
265    * @param request servlet request
266    * @param response servlet response
267    */

268   protected void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
269     RequestContext context = RequestContextFactoryFinder.createContext(request, response, true);
270     try {
271       processRequest(context);
272     } finally {
273       context.invalidate();
274     }
275   }
276
277   /** Returns a short description of the servlet.
278    */

279   public String JavaDoc getServletInfo() {
280     return "Export OLAP table";
281   }
282
283 }
284
Popular Tags