View Javadoc

1   /*
2    * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/servlets/FileServlet.java,v 1.29 2006/03/18 16:01:07 hkollmann Exp $
3    * $Revision: 1.29 $
4    * $Date: 2006/03/18 16:01:07 $
5    *
6    * DbForms - a Rapid Application Development Framework
7    * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8    *
9    * This library is free software; you can redistribute it and/or
10   * modify it under the terms of the GNU Lesser General Public
11   * License as published by the Free Software Foundation; either
12   * version 2.1 of the License, or (at your option) any later version.
13   *
14   * This library is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17   * Lesser General Public License for more details.
18   *
19   * You should have received a copy of the GNU Lesser General Public
20   * License along with this library; if not, write to the Free Software
21   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22   */
23  
24  package org.dbforms.servlets;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  import org.dbforms.servlets.base.AbstractServletBase;
30  
31  import org.dbforms.config.DbFormsConfig;
32  import org.dbforms.config.DbFormsConfigRegistry;
33  import org.dbforms.config.Field;
34  import org.dbforms.config.FieldTypes;
35  import org.dbforms.config.Table;
36  
37  import org.dbforms.util.SqlUtil;
38  import org.dbforms.util.StringUtil;
39  import org.dbforms.util.Util;
40  import org.dbforms.util.FileHolder;
41  
42  import java.io.IOException;
43  import java.io.InputStream;
44  
45  import java.sql.Connection;
46  import java.sql.PreparedStatement;
47  import java.sql.ResultSet;
48  import java.sql.SQLException;
49  
50  import javax.servlet.ServletException;
51  import javax.servlet.ServletOutputStream;
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.http.HttpServletResponse;
54  
55  /***
56   * #fixme - add appropriate exception-handling..
57   * 
58   * @author joe peer
59   */
60  public class FileServlet extends AbstractServletBase {
61  	// logging category for this class
62  	private static Log logCat = LogFactory.getLog(FileServlet.class.getName());
63  
64  	/***
65  	 * Process the HTTP Get request
66  	 * 
67  	 * @param request
68  	 *            Description of the Parameter
69  	 * @param response
70  	 *            Description of the Parameter
71  	 * 
72  	 * @exception ServletException
73  	 *                Description of the Exception
74  	 * @exception IOException
75  	 *                Description of the Exception
76  	 */
77  	public void process(HttpServletRequest request, HttpServletResponse response)
78  			throws ServletException, IOException {
79  
80  		// take Config-Object from application context - this object should have
81  		// been
82  		// initalized by Config-Servlet on Webapp/server-startup!
83  		DbFormsConfig config = null;
84  		try {
85  			config = DbFormsConfigRegistry.instance().lookup();
86  		} catch (Exception e) {
87  			logCat.error(e);
88  			throw new ServletException(e);
89  		}
90  
91  		try {
92  			String tf = request.getParameter("tf");
93  			String keyValuesStr = request.getParameter("keyval");
94  			if (!Util.isNull(keyValuesStr) && !("null".equals(keyValuesStr))) {
95  
96  				int tableId = Integer.parseInt(StringUtil.getEmbeddedString(tf,
97  						0, '_'));
98  				Table table = config.getTable(tableId);
99  				int fieldId = Integer.parseInt(StringUtil.getEmbeddedString(tf,
100 						1, '_'));
101 				Field field = table.getField(fieldId);
102 
103 				StringBuffer queryBuf = new StringBuffer();
104 				String dbConnectionName = request.getParameter("invname_"
105 						+ tableId);
106 				Connection con = config.getConnection(dbConnectionName);
107 
108 				// JPeer 03/2004 - optional parameter
109 				String nameField = request.getParameter("nf");
110 
111 				InputStream is = null;
112 				String fileName = null;
113 
114 				queryBuf.append("SELECT ");
115 				queryBuf.append(field.getName());
116 
117 				if (nameField != null) {
118 					queryBuf.append(", ");
119 					queryBuf.append(nameField);
120 				}
121 
122 				queryBuf.append(" FROM ");
123 				queryBuf.append(table.getQueryFrom());
124 				queryBuf.append(" WHERE ");
125 				queryBuf.append(table.getWhereClauseForKeyFields(keyValuesStr));
126 
127 				// example: SELECT imageNameField FROM myTable WHERE myTable.key
128 				// = ?
129 				logCat.info("::doGet - query is [" + queryBuf + "]");
130 
131 				PreparedStatement ps = con
132 						.prepareStatement(queryBuf.toString());
133 				table.populateWhereClauseWithKeyFields(keyValuesStr, ps, 1);
134 
135 				ResultSet rs = ps.executeQuery();
136 
137 				if (rs.next()) {
138 					// use the filesystem;
139 					if (field.getType() == FieldTypes.DISKBLOB) {
140 						fileName = rs.getString(1);
141 						String directory = field.getDirectory();
142 						try {
143 							directory = DbFormsConfigRegistry.instance().lookup().replaceVariables(directory);
144 						} catch (Exception ex) {
145 							logCat
146 									.error(
147 											"::doGet  - error replacing REALPATH on diskblob directory",
148 											ex);
149 						}
150 						is = SqlUtil.readDiskBlob(fileName, directory, request
151 								.getParameter("defaultValue"));
152 					}
153 					// use the rdbms;
154 					else if (field.getType() == FieldTypes.BLOB) {
155 						// if no fileholder is used (new BLOB model)
156 						if (nameField != null) {
157 							fileName = rs.getString(2);
158 							is = SqlUtil.readDbFieldBlob(rs);
159 						} else {
160 							FileHolder fh = SqlUtil.readFileHolderBlob(rs);
161 							is = fh.getInputStreamFromBuffer();
162 							fileName = fh.getFileName();
163 						}
164 					}
165 				} else {
166 					logCat.info("::doGet - we have got no result using query "
167 							+ queryBuf);
168 				}
169 
170 				if (is != null) {
171 					writeToClient(request, response, fileName, is);
172 				}
173 
174 				SqlUtil.closeConnection(con);
175 			}
176 		} catch (SQLException sqle) {
177 			logCat.error("::doGet - SQL exception", sqle);
178 		}
179 	}
180 
181 	/***
182 	 * Write the content of the input file to the client.
183 	 * 
184 	 * @param request
185 	 *            DOCUMENT ME!
186 	 * @param response
187 	 *            Description of the Parameter
188 	 * @param fileName
189 	 *            Description of the Parameter
190 	 * @param is
191 	 *            Description of the Parameter
192 	 * 
193 	 * @exception IOException
194 	 *                Description of the Exception
195 	 */
196 	private void writeToClient(HttpServletRequest request,
197 			HttpServletResponse response, String fileName, InputStream is)
198 			throws IOException {
199 		String contentType = request.getSession().getServletContext()
200 				.getMimeType(fileName);
201 		logCat.info("::writeToClient- writing to client:" + fileName + " ct="
202 				+ contentType);
203 
204 		if (!Util.isNull(contentType)) {
205 			response.setContentType(contentType);
206 		}
207 
208 		response.setHeader("Cache-control", "private"); // w/o this MSIE fails
209 
210 		// to "Open" the file
211 		response.setHeader("Content-Disposition", "attachment; fileName=\""
212 				+ fileName + "\"");
213 
214 		ServletOutputStream out = response.getOutputStream();
215 		byte[] b = new byte[1024];
216 		int read;
217 
218 		while ((read = is.read(b)) != -1)
219 			out.write(b, 0, read);
220 
221 		out.close();
222 	}
223 }