KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > jpivot > jboss > portlet > PrintTable


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) 2005 SHERMAN WOOD.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  */

11 package com.tonbeller.jpivot.jboss.portlet;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.StringWriter JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.Map JavaDoc;
20
21 import javax.portlet.ActionResponse;
22 import javax.portlet.PortletException;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.servlet.http.HttpSession JavaDoc;
26 import javax.xml.transform.Transformer JavaDoc;
27 import javax.xml.transform.dom.DOMSource JavaDoc;
28 import javax.xml.transform.stream.StreamResult JavaDoc;
29
30 import org.apache.fop.apps.Driver;
31 import org.apache.fop.apps.FOPException;
32 import org.apache.log4j.Logger;
33 import org.jboss.portal.server.WindowContext;
34 import org.jboss.portlet.JBossActionResponse;
35 import org.w3c.dom.Document JavaDoc;
36 import org.xml.sax.InputSource JavaDoc;
37
38 import com.tonbeller.jpivot.chart.ChartComponent;
39 import com.tonbeller.jpivot.print.PrintComponent;
40 import com.tonbeller.jpivot.table.TableComponent;
41 import com.tonbeller.wcf.component.RendererParameters;
42 import com.tonbeller.wcf.controller.RequestContext;
43 import com.tonbeller.wcf.controller.RequestContextFactoryFinder;
44 import com.tonbeller.wcf.utils.XmlUtils;
45
46 /**
47  * @author swood
48  */

49 public class PrintTable {
50     private static Logger logger = Logger.getLogger(PrintTable.class);
51     public static final int XLS = 0;
52     public static final int PDF = 1;
53     
54     /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
55      * @param request servlet request
56      * @param response servlet response
57      * @throws PortletException
58      */

59     
60     public static void processRequest(
61             HttpServletRequest JavaDoc request,
62             HttpServletResponse JavaDoc response,
63             WindowContext windowCtx,
64             ActionResponse portletResponse) throws PortletException {
65         if (request.getParameter("cube") == null || request.getParameter("type") == null){
66             return;
67         }
68         
69         try {
70
71             RequestContext context = RequestContextFactoryFinder.createContext(request,response,true);
72             
73             String JavaDoc xslUri = null;
74             
75             int type = Integer.parseInt(request.getParameter("type"));
76             String JavaDoc contentType = null;
77             
78             switch (type){
79                 case XLS:
80                     xslUri="/WEB-INF/jpivot/table/xls_mdxtable.xsl";
81                     RendererParameters.setParameter(context.getRequest(), "mode","excel","request");
82                     contentType = "application/vnd.ms-excel";
83                     // filename = "xls_export.xls";
84
break;
85                 case PDF:
86                     xslUri="/WEB-INF/jpivot/table/fo_mdxtable.xsl";
87                     RendererParameters.setParameter(context.getRequest(), "mode","print","request");
88                     contentType = "application/pdf";
89                     // filename = "xls_export.pdf";
90
break;
91                 default:
92                     return;
93             }
94             // get references to needed elements
95
String JavaDoc tableRef = "table"+request.getParameter("cube");
96             String JavaDoc chartRef = "chart"+request.getParameter("cube");
97             String JavaDoc printRef = "print"+request.getParameter("cube");
98             
99             // get TableComponent
100
TableComponent table = (TableComponent) context.getModelReference(tableRef);
101             // only proceed if table component exists
102

103             if (table == null) {
104                 return;
105             }
106             // add parameters from printConfig
107
PrintComponent printConfig = (PrintComponent) context.getModelReference(printRef);
108             
109             Map JavaDoc parameters = new HashMap JavaDoc();
110
111             if (printConfig != null) {
112                 if (printConfig.isSetTableWidth()) {
113                     parameters.put(printConfig.PRINT_TABLE_WIDTH, new Double JavaDoc(printConfig.getTableWidth()));
114                 }
115                 if (printConfig.getReportTitle().trim().length()!=0){
116                     parameters.put(printConfig.PRINT_TITLE, printConfig.getReportTitle().trim());
117                 }
118                 parameters.put(printConfig.PRINT_PAGE_ORIENTATION, printConfig.getPageOrientation());
119                 parameters.put(printConfig.PRINT_PAPER_TYPE, printConfig.getPaperType());
120                 if (printConfig.getPaperType().equals("custom")){
121                     parameters.put(printConfig.PRINT_PAGE_WIDTH, new Double JavaDoc(printConfig.getPageWidth()));
122                     parameters.put(printConfig.PRINT_PAGE_HEIGHT, new Double JavaDoc(printConfig.getPageHeight()));
123                 }
124                 parameters.put(printConfig.PRINT_CHART_PAGEBREAK, new Boolean JavaDoc(printConfig.isChartPageBreak()));
125
126             }
127             
128             // add parameters and image from chart if visible
129
ChartComponent chart = (ChartComponent)request.getSession().getAttribute(chartRef);
130             if (chart != null && chart.isVisible() ) {
131                 
132                 String JavaDoc host = request.getServerName();
133                 int port = request.getServerPort();
134                 
135                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
136                 sb.append("http://")
137                     .append(host)
138                     .append(":")
139                     .append(port)
140                     .append(chart.getGraphURL(context));
141                 String JavaDoc chartURL = sb.toString();
142                 
143                 logger.debug("image is: " + chartURL);
144                 parameters.put("chartimage", chartURL);
145
146                 parameters.put("chartheight", new Integer JavaDoc(chart.getChartHeight()));
147                 parameters.put("chartwidth", new Integer JavaDoc(chart.getChartWidth()));
148             }
149             
150             parameters.put("context", context.getRequest().getContextPath());
151             
152             // Some FOP-PDF versions require a complete URL, not a path
153
//parameters.put("contextUrl", createContextURLValue(context));
154

155             // Render the table to get the XML result
156
table.setDirty(true);
157             Document JavaDoc document = table.render(context);
158             table.setDirty(true);
159             
160             DOMSource JavaDoc source = new DOMSource JavaDoc(document);
161             
162             // set up for the xml transformation
163
HttpSession JavaDoc session = request.getSession();
164             Transformer JavaDoc transformer = XmlUtils.getTransformer(session, xslUri, true);
165             for (Iterator JavaDoc it = parameters.keySet().iterator(); it.hasNext();) {
166                 String JavaDoc name = (String JavaDoc) it.next();
167                 Object JavaDoc value = parameters.get(name);
168                 transformer.setParameter(name, value);
169             }
170             StringWriter JavaDoc sw = new StringWriter JavaDoc();
171             StreamResult JavaDoc result = new StreamResult JavaDoc(sw);
172             //do transform
173
transformer.transform(source, result);
174             sw.flush();
175             
176             // This will only work in JBoss
177
JBossActionResponse responseImpl = (JBossActionResponse) portletResponse;
178             
179             // if this is XLS, then we are done, so output xls file.
180
if (type == XLS){
181                 logger.info("Creating XLS");
182                 //org.jboss.portal.server.output.Result portletResult = new org.jboss.portal.server.output.StreamResult(windowCtx, contentType, sw.toString().getBytes());
183
//responseImpl.setResult(portletResult);
184
responseImpl.sendBytes(contentType, sw.toString().getBytes());
185                 RendererParameters.removeParameter(context.getRequest(), "mode","excel","request");
186                 // process FO to PDF
187
} else {
188                 // if this is PDF, then need to generate PDF from the FO xml
189
logger.info("Creating PDF!");
190                 ByteArrayInputStream JavaDoc bain = new ByteArrayInputStream JavaDoc(sw.toString().getBytes("UTF-8"));
191                 ByteArrayOutputStream JavaDoc baout = new ByteArrayOutputStream JavaDoc(16384);
192                 convertFO2PDF(bain,baout);
193                 final byte[] content = baout.toByteArray();
194                 //org.jboss.portal.server.output.Result portletResult = new org.jboss.portal.server.output.StreamResult(windowCtx, contentType, content);
195
//responseImpl.setResult(portletResult);
196
responseImpl.sendBytes(contentType, content);
197                 RendererParameters.removeParameter(context.getRequest(), "mode","print","request");
198             }
199         } catch (Exception JavaDoc e){
200             throw new PortletException(e);
201         }
202     }
203     
204     /**
205      * converts FO xml into PDF using the FOP processor
206      */

207     public static void convertFO2PDF(ByteArrayInputStream JavaDoc bain,ByteArrayOutputStream JavaDoc baout) throws IOException JavaDoc,FOPException {
208         
209         logger.debug("Construct driver");
210         Driver driver = new Driver();
211         
212         logger.debug("Setup Renderer (output format)");
213         driver.setRenderer(Driver.RENDER_PDF);
214         
215         try {
216             driver.setOutputStream(baout);
217             logger.debug("Setup input");
218             driver.setInputSource(new InputSource JavaDoc(bain));
219             
220             logger.debug("Process FO");
221             driver.run();
222             logger.debug("PDF file generation completed");
223         } catch (Exception JavaDoc e){
224             logger.error(e);
225         }
226     }
227
228 }
229
Popular Tags