KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dinamica > AbstractPDFOutput


1 package dinamica;
2
3 import javax.servlet.*;
4 import javax.servlet.http.Cookie JavaDoc;
5 import java.io.BufferedInputStream JavaDoc;
6 import java.io.ByteArrayOutputStream JavaDoc;
7 import java.net.HttpURLConnection JavaDoc;
8 import java.net.URL JavaDoc;
9 import com.lowagie.text.*;
10 import com.lowagie.text.pdf.*;
11
12 /**
13  * Base class to produce PDF output modules (hand made reports)
14  * based on the powerful IText-PDF open source component.<br>
15  * This super class provides several common utility methods, including
16  * the abiity to auto-read the report header, footer and title from web.xml
17  * or config.xml, and to retrieve images from URLs (local or remotes), which is
18  * used to insert charts into the PDF document by reusing a server-side chart Action,
19  * or to insert another dinamically generated image, like a BarCode. The method to retrieve
20  * via HTTP is session sensitive, meaning that it can reuse the same session ID, which is
21  * a requirement when accessing local resources that are session-sensitive, like chart Actions.
22  * <br><br>
23  * In order to reuse this class, you must override the method createPDF(), you may use
24  * the default implementation as a code template. For more information look into
25  * the /source and /templates resources included with Dinamica distribution.
26  * <br><br>
27  * (c) 2004 Martin Cordova<br>
28  * This code is released under the LGPL license<br>
29  * Dinamica Framework - http://www.martincordova.com
30  * @author Martin Cordova (dinamica@martincordova.com)
31  * */

32 public class AbstractPDFOutput extends GenericOutput
33 {
34
35     /* (non-Javadoc)
36      * @see dinamica.GenericOutput#print(dinamica.GenericTransaction)
37      */

38     public void print(GenericTransaction data) throws Throwable JavaDoc
39     {
40         ByteArrayOutputStream JavaDoc buf = new ByteArrayOutputStream JavaDoc();
41         createPDF(data, buf);
42         getResponse().setContentLength(buf.size());
43         ServletOutputStream out = getResponse().getOutputStream();
44         buf.writeTo(out);
45         out.close();
46     }
47
48     protected void createPDF(GenericTransaction data, ByteArrayOutputStream JavaDoc buf) throws Throwable JavaDoc
49     {
50
51         //pdf objects
52
Document doc = new Document();
53         PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
54
55         //header
56
HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false);
57         header.setBorder(Rectangle.BOTTOM);
58         header.setAlignment(Rectangle.ALIGN_CENTER);
59         doc.setHeader(header);
60             
61         //footer
62
HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true);
63         footer.setBorder(Rectangle.TOP);
64         footer.setAlignment(Rectangle.ALIGN_RIGHT);
65         doc.setFooter(footer);
66             
67         //pagesize
68
doc.setPageSize(PageSize.LETTER);
69
70         doc.open();
71             
72             //title
73
Paragraph t = new Paragraph(getReportTitle(),new Font(Font.HELVETICA, 18f));
74             t.setAlignment(Rectangle.ALIGN_CENTER);
75             doc.add(t);
76             
77             //paragraph
78
Paragraph p = new Paragraph("Hello World");
79             p.setAlignment(Rectangle.ALIGN_CENTER);
80             doc.add(p);
81             
82         doc.close();
83         docWriter.close();
84         
85     }
86
87     /**
88      * Get default report header (parameter pdf-header) from web.xml (context-param) or current config.xml (custom element).
89      * Any subclass may override this method.
90      * @return Report header text or NULL
91      */

92     protected String JavaDoc getHeader()
93     {
94         
95         return getPDFConfigValue("pdf-header");
96
97     }
98     
99     /**
100      * Get default report footer (parameter pdf-footer) from web.xml (context-param) or current config.xml (custom element).
101      * Any subclass may override this method.
102      * @return Report footer text or NULL
103      */

104     protected String JavaDoc getFooter()
105     {
106         return getPDFConfigValue("pdf-footer") + " ";
107     }
108
109     /**
110      * Get default report title (parameter pdf-title) from web.xml (context-param) or current config.xml (custom element).
111      * Most of the time the report title should be defined in config.xml because it is
112      * specific to the report.
113      * Any subclass may override this method.
114      * @return Report title text or NULL
115      */

116     protected String JavaDoc getReportTitle()
117     {
118         return getPDFConfigValue("pdf-title");
119     }
120
121     /**
122      * Read a PDF-related config parameter. Will search first
123      * in the Action config.xml, then in web.xml file.
124      * @param param
125      * @return The corresponding value or NULL if not found.
126      */

127     protected String JavaDoc getPDFConfigValue(String JavaDoc param)
128     {
129         String JavaDoc value = null;
130         try
131         {
132             value = getConfig().getConfigValue(param);
133             if (value==null || value.trim().equals(""))
134             {
135                 value = getContext().getInitParameter(param);
136             }
137         }
138         catch (Throwable JavaDoc e)
139         {
140             value = getContext().getInitParameter(param);
141             if (value==null)
142                 value = "";
143         }
144         return value;
145     }
146
147     /**
148      * Return byte array with the content of a remote binary resource
149      * accessed via HTTP(S).
150      * @param url URL of the resource
151      * @param sessionID Session ID
152      * @param logStdout If TRUE will print trace log to System.out.
153      * @return Byte array with the content of the file
154      * @throws Throwable In case of any HTTP error of if the data cannot
155      * be read for any reason.
156      */

157     protected byte[] getImage(String JavaDoc url, String JavaDoc sessionID, boolean logStdout) throws Throwable JavaDoc
158     {
159
160         HttpURLConnection JavaDoc urlc = null;
161         BufferedInputStream JavaDoc bin = null;
162         final int bufferSize = 10240;
163         byte[] buffer = null;
164         URL JavaDoc page = new URL JavaDoc(url);
165         ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
166             
167         if (logStdout)
168             System.err.println("Waiting for reply...:" + url);
169
170         try
171         {
172             urlc = (HttpURLConnection JavaDoc)page.openConnection();
173             urlc.setUseCaches(false);
174             urlc.addRequestProperty("Cookie", "JSESSIONID=" + sessionID);
175             
176             if (logStdout)
177             {
178                 System.err.println("Content-type = " + urlc.getContentType());
179                 System.err.println("Content-length = " + urlc.getContentLength());
180                 System.err.println("Response-code = " + urlc.getResponseCode());
181                 System.err.println("Response-message = " + urlc.getResponseMessage());
182             }
183             
184             int retCode = urlc.getResponseCode();
185             String JavaDoc retMsg = urlc.getResponseMessage();
186             if (retCode>=400)
187                 throw new Throwable JavaDoc("HTTP Error: " + retCode + " - " + retMsg + " - URL:" + url);
188                             
189             int size = urlc.getContentLength();
190             if (size > 0)
191                 buffer = new byte[size];
192             else
193                 buffer = new byte[bufferSize];
194             
195             bin = new BufferedInputStream JavaDoc(urlc.getInputStream(), buffer.length);
196                                                
197             int bytesRead = 0;
198             do
199             {
200                 bytesRead = bin.read(buffer);
201                 if (bytesRead > 0)
202                     bout.write(buffer, 0, bytesRead);
203             } while (bytesRead != -1);
204             
205             if (logStdout)
206             {
207                 System.err.println("Connection closed.");
208             }
209             
210             return bout.toByteArray();
211             
212         }
213         catch (Throwable JavaDoc e)
214         {
215             throw e;
216         }
217         finally
218         {
219             if (bin != null)
220                 bin.close();
221                 
222             if (urlc != null)
223                 urlc.disconnect();
224         }
225
226     }
227
228     /**
229      * Retrieve the session ID from the request headers
230      * looking for a cookie named JSESSIONID. This method was
231      * implemented because some Servers (WepSphere 5.1) won't
232      * return the real cookie value when the HttpSession.getId()
233      * method is invoked, which causes big trouble when retrieving an
234      * image from an Action using HTTP and the session ID. This problem
235      * was discovered while testing PDF reports with charts on WAS 5.1, it
236      * is specific to WAS 5.1, but this method works well with all tested
237      * servlet engines, including Resin 2.x.
238      * @return The session ID as stored in the cookie header, or NULL if it can find the cookie.
239      * @throws Throwable
240      */

241     protected String JavaDoc getSessionID()
242     {
243         String JavaDoc value = null;
244         Cookie JavaDoc c[] = getRequest().getCookies();
245         for (int i=0;i<c.length;i++)
246         {
247             if (c[i].getName().equals("JSESSIONID"))
248             {
249                 value = c[i].getValue();
250                 break;
251             }
252         }
253         return value;
254     }
255
256     /**
257      * Return byte array with the content of a remote binary resource
258      * accessed via HTTP(S) - a Cookie header (JSESSIONID) with the current
259      * session ID will be added to the request headers
260      * @param url URL of the resource
261      * @param logStdout If TRUE will print trace log to System.err.
262      * @return Byte array with the content of the file
263      * @throws Throwable In case of any HTTP error of if the data cannot
264      * be read for any reason.
265      */

266     protected byte[] getImage(String JavaDoc url, boolean logStdout) throws Throwable JavaDoc
267     {
268         String JavaDoc sID = getSessionID();
269         return getImage(url, sID, logStdout);
270     }
271
272 }
273
Popular Tags