KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jfree > chart > servlet > ServletUtilities


1 /* ===========================================================
2  * JFreeChart : a free chart library for the Java(tm) platform
3  * ===========================================================
4  *
5  * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
6  *
7  * Project Info: http://www.jfree.org/jfreechart/index.html
8  *
9  * This library is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17  * License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this library; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
24  * in the United States and other countries.]
25  *
26  * ---------------------
27  * ServletUtilities.java
28  * ---------------------
29  * (C) Copyright 2002-2005, by Richard Atkinson and Contributors.
30  *
31  * Original Author: Richard Atkinson;
32  * Contributor(s): J?rgen Hoffman;
33  * David Gilbert (for Object Refinery Limited);
34  * Douglas Clayton;
35  *
36  * $Id: ServletUtilities.java,v 1.3 2005/03/28 19:53:47 mungady Exp $
37  *
38  * Changes
39  * -------
40  * 19-Aug-2002 : Version 1;
41  * 20-Apr-2003 : Added additional sendTempFile method to allow MIME type
42  * specification and modified original sendTempFile method to
43  * automatically set MIME type for JPEG and PNG files
44  * 23-Jun-2003 : Added additional sendTempFile method at the request of
45  * J?rgen Hoffman;
46  * 07-Jul-2003 : Added more header information to streamed images;
47  * 19-Aug-2003 : Forced images to be stored in the temporary directory defined
48  * by System property java.io.tmpdir, rather than default (RA);
49  * 24-Mar-2004 : Added temp filename prefix attribute (DG);
50  * 09-Mar-2005 : Added "one time" file option (DG);
51  *
52  */

53
54 package org.jfree.chart.servlet;
55
56 import java.io.BufferedInputStream JavaDoc;
57 import java.io.BufferedOutputStream JavaDoc;
58 import java.io.File JavaDoc;
59 import java.io.FileInputStream JavaDoc;
60 import java.io.FileNotFoundException JavaDoc;
61 import java.io.IOException JavaDoc;
62 import java.text.SimpleDateFormat JavaDoc;
63 import java.util.Date JavaDoc;
64 import java.util.TimeZone JavaDoc;
65
66 import javax.servlet.http.HttpServletResponse JavaDoc;
67 import javax.servlet.http.HttpSession JavaDoc;
68
69 import org.jfree.chart.ChartRenderingInfo;
70 import org.jfree.chart.ChartUtilities;
71 import org.jfree.chart.JFreeChart;
72
73 /**
74  * Utility class used for servlet related JFreeChart operations.
75  *
76  * @author Richard Atkinson
77  */

78 public class ServletUtilities {
79
80     /** The filename prefix. */
81     private static String JavaDoc tempFilePrefix = "jfreechart-";
82     
83     /** A prefix for "one time" charts. */
84     private static String JavaDoc tempOneTimeFilePrefix = "jfreechart-onetime-";
85     
86     /**
87      * Returns the prefix for the temporary file names generated by this class.
88      *
89      * @return The prefix (never <code>null</code>).
90      */

91     public static String JavaDoc getTempFilePrefix() {
92         return ServletUtilities.tempFilePrefix;
93     }
94     
95     /**
96      * Sets the prefix for the temporary file names generated by this class.
97      *
98      * @param prefix the prefix (<code>null</code> not permitted).
99      */

100     public static void setTempFilePrefix(String JavaDoc prefix) {
101         if (prefix == null) {
102             throw new IllegalArgumentException JavaDoc("Null 'prefix' argument.");
103         }
104         ServletUtilities.tempFilePrefix = prefix;
105     }
106     
107     /**
108      * Returns the prefix for "one time" temporary file names generated by
109      * this class.
110      *
111      * @return The prefix.
112      */

113     public static String JavaDoc getTempOneTimeFilePrefix() {
114         return ServletUtilities.tempOneTimeFilePrefix;
115     }
116     
117     /**
118      * Sets the prefix for the "one time" temporary file names generated by
119      * this class.
120      *
121      * @param prefix the prefix (<code>null</code> not permitted).
122      */

123     public static void setTempOneTimeFilePrefix(String JavaDoc prefix) {
124         if (prefix == null) {
125             throw new IllegalArgumentException JavaDoc("Null 'prefix' argument.");
126         }
127         ServletUtilities.tempOneTimeFilePrefix = prefix;
128     }
129     
130     /**
131      * Saves the chart as a PNG format file in the temporary directory.
132      *
133      * @param chart the JFreeChart to be saved.
134      * @param width the width of the chart.
135      * @param height the height of the chart.
136      * @param session the HttpSession of the client (if <code>null</code>, the
137      * temporary file is marked as "one-time" and deleted by
138      * the {@link DisplayChart} servlet right after it is
139      * streamed to the client).
140      *
141      * @return The filename of the chart saved in the temporary directory.
142      *
143      * @throws IOException if there is a problem saving the file.
144      */

145     public static String JavaDoc saveChartAsPNG(JFreeChart chart, int width, int height,
146                                         HttpSession JavaDoc session)
147             throws IOException JavaDoc {
148
149         return ServletUtilities.saveChartAsPNG(
150             chart, width, height, null, session
151         );
152         
153     }
154
155     /**
156      * Saves the chart as a PNG format file in the temporary directory and
157      * populates the {@link ChartRenderingInfo} object which can be used to
158      * generate an HTML image map.
159      *
160      * @param chart the chart to be saved (<code>null</code> not permitted).
161      * @param width the width of the chart.
162      * @param height the height of the chart.
163      * @param info the ChartRenderingInfo object to be populated
164      * (<code>null</code> permitted).
165      * @param session the HttpSession of the client (if <code>null</code>, the
166      * temporary file is marked as "one-time" and deleted by
167      * the {@link DisplayChart} servlet right after it is
168      * streamed to the client).
169      *
170      * @return The filename of the chart saved in the temporary directory.
171      *
172      * @throws IOException if there is a problem saving the file.
173      */

174     public static String JavaDoc saveChartAsPNG(JFreeChart chart, int width, int height,
175                                         ChartRenderingInfo info,
176                                         HttpSession JavaDoc session)
177             throws IOException JavaDoc {
178
179         if (chart == null) {
180             throw new IllegalArgumentException JavaDoc("Null 'chart' argument.");
181         }
182         ServletUtilities.createTempDir();
183         String JavaDoc prefix = ServletUtilities.tempFilePrefix;
184         if (session == null) {
185             prefix = ServletUtilities.tempOneTimeFilePrefix;
186         }
187         File JavaDoc tempFile = File.createTempFile(
188             prefix, ".png", new File JavaDoc(System.getProperty("java.io.tmpdir"))
189         );
190         ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
191         if (session != null) {
192             ServletUtilities.registerChartForDeletion(tempFile, session);
193         }
194         return tempFile.getName();
195
196     }
197
198     /**
199      * Saves the chart as a JPEG format file in the temporary directory.
200      *
201      * @param chart the JFreeChart to be saved.
202      * @param width the width of the chart.
203      * @param height the height of the chart.
204      * @param session the HttpSession of the client (if <code>null</code>, the
205      * temporary file is marked as "one-time" and deleted by
206      * the {@link DisplayChart} servlet right after it is
207      * streamed to the client).
208      *
209      * @return The filename of the chart saved in the temporary directory.
210      *
211      * @throws IOException if there is a problem saving the file.
212      */

213     public static String JavaDoc saveChartAsJPEG(JFreeChart chart, int width,
214                                          int height, HttpSession JavaDoc session)
215             throws IOException JavaDoc {
216
217         return ServletUtilities.saveChartAsJPEG(
218             chart, width, height, null, session
219         );
220         
221     }
222
223     /**
224      * Saves the chart as a JPEG format file in the temporary directory and
225      * populates the ChartRenderingInfo object which can be used to generate
226      * an HTML image map.
227      *
228      * @param chart the chart to be saved (<code>null</code> not permitted).
229      * @param width the width of the chart
230      * @param height the height of the chart
231      * @param info the ChartRenderingInfo object to be populated
232      * @param session the HttpSession of the client (if <code>null</code>, the
233      * temporary file is marked as "one-time" and deleted by
234      * the {@link DisplayChart} servlet right after it is
235      * streamed to the client).
236      *
237      * @return The filename of the chart saved in the temporary directory
238      *
239      * @throws IOException if there is a problem saving the file.
240      */

241     public static String JavaDoc saveChartAsJPEG(JFreeChart chart, int width,
242                                          int height, ChartRenderingInfo info,
243                                          HttpSession JavaDoc session)
244             throws IOException JavaDoc {
245
246         if (chart == null) {
247             throw new IllegalArgumentException JavaDoc("Null 'chart' argument.");
248         }
249         
250         ServletUtilities.createTempDir();
251         String JavaDoc prefix = ServletUtilities.tempFilePrefix;
252         if (session == null) {
253             prefix = ServletUtilities.tempOneTimeFilePrefix;
254         }
255         File JavaDoc tempFile = File.createTempFile(
256             prefix, ".jpeg", new File JavaDoc(System.getProperty("java.io.tmpdir"))
257         );
258         ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
259         if (session != null) {
260             ServletUtilities.registerChartForDeletion(tempFile, session);
261         }
262         return tempFile.getName();
263
264     }
265
266     /**
267      * Creates the temporary directory if it does not exist. Throws a
268      * <code>RuntimeException</code> if the temporary directory is
269      * <code>null</code>. Uses the system property <code>java.io.tmpdir</code>
270      * as the temporary directory. This sounds like a strange thing to do but
271      * my temporary directory was not created on my default Tomcat 4.0.3
272      * installation. Could save some questions on the forum if it is created
273      * when not present.
274      */

275     protected static void createTempDir() {
276         String JavaDoc tempDirName = System.getProperty("java.io.tmpdir");
277         if (tempDirName == null) {
278             throw new RuntimeException JavaDoc(
279                 "Temporary directory system property (java.io.tmpdir) is null."
280             );
281         }
282
283         // create the temporary directory if it doesn't exist
284
File JavaDoc tempDir = new File JavaDoc(tempDirName);
285         if (!tempDir.exists()) {
286             tempDir.mkdirs();
287         }
288     }
289
290     /**
291      * Adds a {@link ChartDeleter} object to the session object with the name
292      * <code>JFreeChart_Deleter</code> if there is not already one bound to the
293      * session and adds the filename to the list of charts to be deleted.
294      *
295      * @param tempFile the file to be deleted.
296      * @param session the HTTP session of the client.
297      */

298     protected static void registerChartForDeletion(File JavaDoc tempFile,
299                                                    HttpSession JavaDoc session) {
300
301         // Add chart to deletion list in session
302
if (session != null) {
303             ChartDeleter chartDeleter
304                 = (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
305             if (chartDeleter == null) {
306                 chartDeleter = new ChartDeleter();
307                 session.setAttribute("JFreeChart_Deleter", chartDeleter);
308             }
309             chartDeleter.addChart(tempFile.getName());
310         }
311         else {
312             System.out.println("Session is null - chart will not be deleted");
313         }
314     }
315
316     /**
317      * Binary streams the specified file in the temporary directory to the
318      * HTTP response in 1KB chunks.
319      *
320      * @param filename the name of the file in the temporary directory.
321      * @param response the HTTP response object.
322      *
323      * @throws IOException if there is an I/O problem.
324      */

325     public static void sendTempFile(String JavaDoc filename,
326                                     HttpServletResponse JavaDoc response)
327         throws IOException JavaDoc {
328
329         File JavaDoc file = new File JavaDoc(System.getProperty("java.io.tmpdir"), filename);
330         ServletUtilities.sendTempFile(file, response);
331     }
332
333     /**
334      * Binary streams the specified file to the HTTP response in 1KB chunks.
335      *
336      * @param file the file to be streamed.
337      * @param response the HTTP response object.
338      *
339      * @throws IOException if there is an I/O problem.
340      */

341     public static void sendTempFile(File JavaDoc file, HttpServletResponse JavaDoc response)
342             throws IOException JavaDoc {
343
344         String JavaDoc mimeType = null;
345         String JavaDoc filename = file.getName();
346         if (filename.length() > 5) {
347             if (filename.substring(filename.length() - 5,
348                     filename.length()).equals(".jpeg")) {
349                 mimeType = "image/jpeg";
350             }
351             else if (filename.substring(filename.length() - 4,
352                     filename.length()).equals(".png")) {
353                 mimeType = "image/png";
354             }
355         }
356         ServletUtilities.sendTempFile(file, response, mimeType);
357     }
358
359     /**
360      * Binary streams the specified file to the HTTP response in 1KB chunks.
361      *
362      * @param file the file to be streamed.
363      * @param response the HTTP response object.
364      * @param mimeType the mime type of the file, null allowed.
365      *
366      * @throws IOException if there is an I/O problem.
367      */

368     public static void sendTempFile(File JavaDoc file, HttpServletResponse JavaDoc response,
369                                     String JavaDoc mimeType) throws IOException JavaDoc {
370
371         if (file.exists()) {
372             BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(
373                 new FileInputStream JavaDoc(file)
374             );
375
376             // Set HTTP headers
377
if (mimeType != null) {
378                 response.setHeader("Content-Type", mimeType);
379             }
380             response.setHeader("Content-Length", String.valueOf(file.length()));
381             SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(
382                 "EEE, dd MMM yyyy HH:mm:ss z"
383             );
384             sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
385             response.setHeader(
386                 "Last-Modified", sdf.format(new Date JavaDoc(file.lastModified()))
387             );
388
389             BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc(
390                 response.getOutputStream()
391             );
392             byte[] input = new byte[1024];
393             boolean eof = false;
394             while (!eof) {
395                 int length = bis.read(input);
396                 if (length == -1) {
397                     eof = true;
398                 }
399                 else {
400                     bos.write(input, 0, length);
401                 }
402             }
403             bos.flush();
404             bis.close();
405             bos.close();
406         }
407         else {
408             throw new FileNotFoundException JavaDoc(file.getAbsolutePath());
409         }
410         return;
411     }
412
413     /**
414      * Perform a search/replace operation on a String
415      * There are String methods to do this since (JDK 1.4)
416      *
417      * @param inputString the String to have the search/replace operation.
418      * @param searchString the search String.
419      * @param replaceString the replace String.
420      *
421      * @return The String with the replacements made.
422      */

423     public static String JavaDoc searchReplace(String JavaDoc inputString,
424                                        String JavaDoc searchString,
425                                        String JavaDoc replaceString) {
426
427         int i = inputString.indexOf(searchString);
428         if (i == -1) {
429             return inputString;
430         }
431
432         String JavaDoc r = "";
433         r += inputString.substring(0, i) + replaceString;
434         if (i + searchString.length() < inputString.length()) {
435             r += searchReplace(
436                 inputString.substring(i + searchString.length()),
437                 searchString, replaceString
438             );
439         }
440
441         return r;
442     }
443
444 }
445
Popular Tags