KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > http > HttpBLOBServlet


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.http;
34
35 import java.io.InputStream JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.FileNotFoundException JavaDoc;
38 import javax.servlet.*;
39 import javax.servlet.http.*;
40
41 import java.lang.System JavaDoc;
42 import java.util.StringTokenizer JavaDoc;
43 import java.util.Properties JavaDoc;
44
45 import java.sql.DriverManager JavaDoc;
46 import java.sql.SQLException JavaDoc;
47 import java.sql.Connection JavaDoc;
48 import java.sql.PreparedStatement JavaDoc;
49 import java.sql.ResultSet JavaDoc;
50
51 import com.knowgate.debug.DebugFile;
52 import com.knowgate.misc.Environment;
53
54 /**
55  * <p>Send LONGVARBINARY database field to HttpServletResponse OutputStream</p>
56  * @author Sergio Montoro ten
57  * @version 2.0
58  */

59
60 public class HttpBLOBServlet extends HttpServlet {
61
62  // -----------------------------------------------------------
63

64  private boolean isVoid(String JavaDoc sParam) {
65    if (null==sParam)
66      return true;
67    else
68      return (sParam.length()==0);
69  }
70
71  /**
72   * <p>Initialize Servlet Parameters</p>
73   * Take Database Driver, Conenction URL and User from /WEB-INF/web.xml.<br>
74   * If any parameter is not found then look it up at hipergate.cnf Properties
75   * file using Environment singleton.
76   * @throws ServletException
77   * @throws UnavailableException If jdbcDriverClassName parameter is not found
78   * and driver property at hipergate.cnf is not found or if jdbcURL parameter
79   * is not found and dburl property at hipergate.cnf is not found.
80   * @see com.knowgate.misc.Environment
81   */

82
83  public void init() throws ServletException {
84    ServletConfig config = getServletConfig();
85
86    jdbcDriverClassName = config.getInitParameter("jdbcDriverClassName");
87    jdbcURL = config.getInitParameter("jdbcURL");
88    dbUserName = config.getInitParameter("dbUserName");
89    dbUserPassword = config.getInitParameter("dbUserPassword");
90
91    if (isVoid(jdbcDriverClassName) || isVoid(jdbcURL) || isVoid(dbUserName) || isVoid(dbUserPassword)) {
92      Properties JavaDoc env = Environment.getProfile("hipergate");
93
94      if (isVoid(jdbcDriverClassName))
95        jdbcDriverClassName = env.getProperty("driver");
96
97      if (isVoid(jdbcURL))
98        jdbcURL = env.getProperty("dburl");
99
100      if (isVoid(dbUserName))
101        dbUserName = env.getProperty("dbuser");
102
103      if (isVoid(dbUserPassword))
104        dbUserPassword = env.getProperty("dbpassword");
105    }
106
107    if (jdbcDriverClassName == null || jdbcURL == null) {
108      throw new UnavailableException("Init params missing");
109    }
110  } // init()
111

112  // -----------------------------------------------------------
113

114  /**
115   * <p>Send LONGVARBINARY database field to HttpServletResponse OutputStream</p>
116   * @param nm_table Name of table holding longvarbinary field.
117   *
118   * @param response
119   * @throws IOException
120   * @throws FileNotFoundException
121   * @throws ServletException
122   */

123  public void doGet(HttpServletRequest request, HttpServletResponse response)
124     throws IOException JavaDoc, FileNotFoundException JavaDoc, ServletException
125     {
126     boolean bFound;
127     String JavaDoc sSQL;
128     Class JavaDoc oDriver;
129     Connection JavaDoc oConn = null;
130     PreparedStatement JavaDoc oStmt;
131     ResultSet JavaDoc oRSet;
132     InputStream JavaDoc oBlob = null;
133     int iOffset;
134     int iReaded;
135     int iPar;
136     StringTokenizer JavaDoc oStrTok;
137
138      if (DebugFile.trace) {
139        DebugFile.writeln("Begin HttpBLOBServlet().doGet");
140        DebugFile.incIdent();
141      }
142
143     try {
144       oDriver = Class.forName(jdbcDriverClassName);
145     }
146     catch (ClassNotFoundException JavaDoc ignore) {
147       oDriver = null;
148       if (DebugFile.trace) DebugFile.writeln("Class.forName(" + jdbcDriverClassName + ") : " + ignore.getMessage());
149       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database driver not found");
150     }
151
152     if (null==oDriver) return;
153
154     ServletOutputStream oOut = response.getOutputStream();
155
156     byte oBuffer[] = new byte[4004];
157
158     try {
159       if (DebugFile.trace) DebugFile.writeln("DriverManager.getConnection(" + jdbcURL + ",...)");
160
161       oConn = DriverManager.getConnection(jdbcURL,dbUserName,dbUserPassword);
162
163       if (DebugFile.trace) DebugFile.writeln("pk_field = " + (request.getParameter("pk_field")!=null ? request.getParameter("pk_field") : "null"));
164
165       oStrTok = new StringTokenizer JavaDoc(request.getParameter("pk_field"), ",");
166
167       sSQL = "";
168       while (oStrTok.hasMoreTokens()) {
169         sSQL += (sSQL.length()==0 ? " WHERE " : " AND ");
170         sSQL += oStrTok.nextToken() + "=?";
171       } // wend
172
sSQL = "SELECT " + request.getParameter("nm_field") + "," + request.getParameter("bin_field") + " FROM " + request.getParameter("nm_table") + sSQL;
173
174       if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")");
175
176       oStmt = oConn.prepareStatement (sSQL);
177
178       iPar = 0;
179       oStrTok = new StringTokenizer JavaDoc(request.getParameter("pk_value"), ",");
180       while (oStrTok.hasMoreTokens()) {
181         oStmt.setString(++iPar, oStrTok.nextToken());
182       }
183
184       if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeQuery()");
185
186       oRSet = oStmt.executeQuery();
187       bFound = oRSet.next();
188
189       String JavaDoc sFileName = null;
190
191       if (bFound) {
192
193         sFileName = oRSet.getString(1);
194
195         if (DebugFile.trace) {
196           DebugFile.writeln("response.setContentType(\"application/octet-stream\")");
197           DebugFile.writeln("response.setHeader(\"Content-Disposition\", \"inline; filename=\"" + sFileName + "\"");
198         }
199
200         // Send some basic http headers to support binary d/l.
201
response.setContentType("application/octet-stream");
202         response.setHeader("Content-Disposition", "inline; filename=\"" + sFileName + "\"");
203
204         if (DebugFile.trace)
205           DebugFile.writeln("ResultSet.getBinaryStream(2)");
206
207         oBlob = oRSet.getBinaryStream(2);
208         iOffset = 0;
209         do {
210           iReaded = oBlob.read(oBuffer, 0, 4000);
211           if (iReaded>0)
212             oOut.write(oBuffer, 0, iReaded);
213           iOffset += iReaded;
214         } while (4000==iReaded);
215
216         if (DebugFile.trace)
217           DebugFile.writeln("response.getOutputStream().flush()");
218
219         oOut.flush();
220         oBlob.close();
221         oBlob = null;
222       } // fi (bFound)
223

224       oRSet.close();
225
226       if (!bFound) {
227         if (DebugFile.trace) DebugFile.writeln("FileNotFoundException: Cannot find requested document");
228
229         response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot find requested document");
230       }
231
232       oConn.close();
233       oConn = null;
234     }
235     catch (SQLException JavaDoc e) {
236       bFound = false;
237       if (oBlob!=null) oBlob.close();
238
239       if (DebugFile.trace) DebugFile.writeln("SQLException: " + e.getMessage());
240
241       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
242     }
243     try { if(null!=oConn) if(!oConn.isClosed()) oConn.close(); } catch (SQLException JavaDoc e) { }
244
245     if (DebugFile.trace) {
246       DebugFile.decIdent();
247       DebugFile.writeln("End HttpBLOBServlet().doGet()");
248     }
249   } // doGet()
250

251   // **********************************************************
252
// * Variables privadas
253

254   private String JavaDoc jdbcDriverClassName;
255   private String JavaDoc jdbcURL;
256   private String JavaDoc dbUserName;
257   private String JavaDoc dbUserPassword;
258 }
Popular Tags