KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > quadcap > app > dbimage > DbImageServlet


1 package com.quadcap.app.dbimage;
2
3 /* Copyright 2000 - 2003 Quadcap Software. All rights reserved.
4  *
5  * This software is distributed under the Quadcap Free Software License.
6  * This software may be used or modified for any purpose, personal or
7  * commercial. Open Source redistributions are permitted. Commercial
8  * redistribution of larger works derived from, or works which bundle
9  * this software requires a "Commercial Redistribution License"; see
10  * http://www.quadcap.com/purchase.
11  *
12  * Redistributions qualify as "Open Source" under one of the following terms:
13  *
14  * Redistributions are made at no charge beyond the reasonable cost of
15  * materials and delivery.
16  *
17  * Redistributions are accompanied by a copy of the Source Code or by an
18  * irrevocable offer to provide a copy of the Source Code for up to three
19  * years at the cost of materials and delivery. Such redistributions
20  * must allow further use, modification, and redistribution of the Source
21  * Code under substantially the same terms as this license.
22  *
23  * Redistributions of source code must retain the copyright notices as they
24  * appear in each source code file, these license terms, and the
25  * disclaimer/limitation of liability set forth as paragraph 6 below.
26  *
27  * Redistributions in binary form must reproduce this Copyright Notice,
28  * these license terms, and the disclaimer/limitation of liability set
29  * forth as paragraph 6 below, in the documentation and/or other materials
30  * provided with the distribution.
31  *
32  * The Software is provided on an "AS IS" basis. No warranty is
33  * provided that the Software is free of defects, or fit for a
34  * particular purpose.
35  *
36  * Limitation of Liability. Quadcap Software shall not be liable
37  * for any damages suffered by the Licensee or any third party resulting
38  * from use of the Software.
39  */

40
41 import java.io.ByteArrayOutputStream JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.io.InputStream JavaDoc;
44 import java.io.OutputStream JavaDoc;
45
46 import java.util.Enumeration JavaDoc;
47 import java.util.Properties JavaDoc;
48
49 import java.sql.Connection JavaDoc;
50 import java.sql.DatabaseMetaData JavaDoc;
51 import java.sql.DriverManager JavaDoc;
52 import java.sql.PreparedStatement JavaDoc;
53 import java.sql.ResultSet JavaDoc;
54 import java.sql.Statement JavaDoc;
55 import java.sql.SQLException JavaDoc;
56
57 import javax.servlet.ServletConfig JavaDoc;
58 import javax.servlet.ServletException JavaDoc;
59
60 import javax.servlet.http.HttpServlet JavaDoc;
61 import javax.servlet.http.HttpServletRequest JavaDoc;
62 import javax.servlet.http.HttpServletResponse JavaDoc;
63
64 // ---- image libraries
65
import java.awt.Image JavaDoc;
66 import java.awt.Graphics2D JavaDoc;
67 import java.awt.geom.AffineTransform JavaDoc;
68 import java.awt.image.BufferedImage JavaDoc;
69 import java.io.IOException JavaDoc;
70 import java.io.OutputStream JavaDoc;
71 import java.io.FileOutputStream JavaDoc;
72 import javax.swing.ImageIcon JavaDoc;
73 import com.sun.image.codec.jpeg.JPEGCodec;
74 import com.sun.image.codec.jpeg.JPEGImageEncoder;
75
76 /**
77  * This servlet fetches and returns images from the database.
78  *
79  * @author Stan Bailes
80  */

81 public class DbImageServlet extends HttpServlet JavaDoc {
82     String JavaDoc url = null;
83     
84     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
85         super.init(config);
86         try {
87             url = config.getInitParameter("jdbc.url");
88             if (url == null) {
89                 throw new ServletException JavaDoc("No jdbc.url property");
90             } else {
91                 String JavaDoc driver = "com.quadcap.jdbc.JdbcDriver";
92                 String JavaDoc d = config.getInitParameter("jdbc.driver");
93                 if (d != null) driver = d;
94                 Class.forName(driver);
95             }
96             config.getServletContext().setAttribute("servlet", this);
97
98             Connection JavaDoc conn = getConnection();
99             Statement JavaDoc stmt = conn.createStatement();
100             try {
101                 DatabaseMetaData JavaDoc dbmeta = conn.getMetaData();
102                 ResultSet JavaDoc rs = dbmeta.getTables(null, null, "images", null);
103                 if (!rs.next()) {
104                     stmt.execute(
105                         "create table images(" +
106                         " name varchar(99999), " +
107                         " maxDim int, " +
108                         " data blob," +
109                         " size int)");
110                     stmt.execute(
111                         "create unique index images1 on images(name, maxDim)");
112                 }
113                 rs.close();
114             } finally {
115                 stmt.close();
116                 conn.close();
117             }
118
119         } catch (Exception JavaDoc e) {
120             e.printStackTrace(System.err);
121             throw new ServletException JavaDoc(e);
122         }
123     }
124
125     public Connection JavaDoc getConnection() throws SQLException JavaDoc {
126         Properties JavaDoc p = new Properties JavaDoc();
127         p.put("create", "true");
128         return DriverManager.getConnection(url, p);
129     }
130     
131     byte[] resizeImage(byte[] imageBytes, int maxDim) throws IOException JavaDoc {
132         ImageIcon JavaDoc inImage = new ImageIcon JavaDoc(imageBytes);
133         
134         // Determine the scale.
135
double scale = (double)maxDim/(double)inImage.getIconHeight();
136
137         if (inImage.getIconWidth() > inImage.getIconHeight()) {
138             scale = (double)maxDim/(double)inImage.getIconWidth();
139         }
140
141         // Determine size of new image.
142
// One of them hould equal maxDim.
143
int scaledW = (int)(scale*inImage.getIconWidth());
144         int scaledH = (int)(scale*inImage.getIconHeight());
145
146         // Create an image buffer in which to paint on.
147
BufferedImage JavaDoc outImage = new BufferedImage JavaDoc(scaledW, scaledH,
148                                                    BufferedImage.TYPE_INT_RGB);
149             
150         // Set the scale.
151
AffineTransform JavaDoc tx = new AffineTransform JavaDoc();
152
153         // If the image is smaller than the desired image size,
154
// don't bother scaling.
155
if (scale < 1.0d) {
156             tx.scale(scale, scale);
157         }
158
159         // Paint image.
160
Graphics2D JavaDoc g2d = outImage.createGraphics();
161         g2d.drawImage(inImage.getImage(), tx, null);
162         g2d.dispose();
163
164         // JPEG-encode the image and write the response
165
ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
166         JPEGImageEncoder encoder =
167             JPEGCodec.createJPEGEncoder(os);
168         encoder.encode(outImage);
169
170         return os.toByteArray();
171     }
172
173     void sendImage(byte[] image, HttpServletResponse JavaDoc response)
174         throws ServletException JavaDoc, IOException JavaDoc
175     {
176         OutputStream JavaDoc os = response.getOutputStream();
177         response.setContentLength(image.length);
178         os.write(image);
179     }
180
181     void storeImage(Connection JavaDoc conn, byte[] image, String JavaDoc name, int dim)
182         throws SQLException JavaDoc
183     {
184         PreparedStatement JavaDoc p = conn.prepareStatement(
185             "insert into images(?,?,?,?)");
186         p.clearParameters();
187         p.setString(1, name);
188         p.setInt(2, image.length);
189         p.setBytes(3, image);
190         p.setInt(4, dim);
191         p.executeUpdate();
192         p.close();
193     }
194
195     public void doGet(HttpServletRequest JavaDoc request,
196                       HttpServletResponse JavaDoc response)
197         throws ServletException JavaDoc
198     {
199         String JavaDoc s = request.getServletPath();
200         response.setContentType(getServletContext().getMimeType(s));
201         Connection JavaDoc conn;
202         try {
203             conn = getConnection();
204         } catch (SQLException JavaDoc ex) {
205             throw new ServletException JavaDoc(ex);
206         }
207         int dim = -1;
208         String JavaDoc mdim = request.getParameter("maxDim");
209         if (mdim != null) {
210             dim = Integer.parseInt(mdim);
211         }
212         try {
213             Statement JavaDoc stmt = conn.createStatement();
214             if (dim <= 0) {
215                 ResultSet JavaDoc rs = stmt.executeQuery(
216                     "select data from images where name = '" + s +
217                     "' and maxDim <= 0");
218                 if (rs.next()) {
219                     byte[] image = rs.getBytes(1);
220                     rs.close();
221                     sendImage(image, response);
222                 } else {
223                     rs.close();
224                     // not found
225
}
226             } else {
227                 ResultSet JavaDoc rs = stmt.executeQuery(
228                     "select data from images where name ='" + s +
229                     "' and maxDim = " + dim);
230                 if (rs.next()) {
231                     byte[] image = rs.getBytes(1);
232                     rs.close();
233                     sendImage(image, response);
234                 } else {
235                     rs.close();
236                     rs = stmt.executeQuery(
237                         "select data, size from images where name = '" + s +
238                         "' and maxDim <= 0");
239                     if (rs.next()) {
240                         byte[] image = rs.getBytes(1);
241                         rs.close();
242                         byte[] resized = resizeImage(image, dim);
243                         storeImage(conn, resized, s, dim);
244                         sendImage(resized, response);
245                     } else {
246                         // not found
247
rs.close();
248                     }
249                 }
250             }
251         } catch (Throwable JavaDoc t) {
252             throw new ServletException JavaDoc(t);
253         } finally {
254             try {
255                 conn.close();
256             } catch (Throwable JavaDoc t) {
257                 throw new ServletException JavaDoc(t);
258             }
259         }
260     }
261
262 }
263
Popular Tags