View Javadoc

1   /*
2    * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/util/SqlUtil.java,v 1.35 2005/11/03 09:57:07 hkollmann Exp $
3    * $Revision: 1.35 $
4    * $Date: 2005/11/03 09:57: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.util;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  import java.io.File;
30  import java.io.FileInputStream;
31  import java.io.FileNotFoundException;
32  import java.io.IOException;
33  import java.io.InputStream;
34  import java.io.ObjectInputStream;
35  
36  import java.sql.Blob;
37  import java.sql.Connection;
38  import java.sql.ResultSet;
39  import java.sql.SQLException;
40  
41  import org.dbforms.util.external.FileUtil;
42  /***
43   * <p>
44   * this utility-class provides convenience methods for SQL related tasks
45   * </p>
46   * 
47   * @author Joe Peer
48   * @author Eric Pugh
49   */
50  public class SqlUtil {
51      // logging category for this class
52      private static Log logCat = LogFactory.getLog(SqlUtil.class.getName());
53  
54      /***
55       * Close the input connection
56       * 
57       * @param con
58       *            the connection to close
59       */
60      public static final void closeConnection(Connection con) {
61          if (con != null) {
62              try {
63                  SqlUtil.logCat.debug("About to close connection - " + con);
64                  con.close();
65                  SqlUtil.logCat.debug("Connection closed");
66              } catch (SQLException e) {
67                  SqlUtil
68                          .logSqlException(e,
69                                  "::closeConnection - cannot close the input connection");
70              }
71          }
72      }
73  
74      /***
75       * Log the SQLException stacktrace (adding the input description to the
76       * first log statement) and do the same for all the nested exceptions.
77       * 
78       * @param e
79       *            the SQL exception to log
80       * @param desc
81       *            the exception description
82       */
83      public static final void logSqlException(SQLException e, String desc) {
84          int i = 0;
85          String excDesc = "::logSqlExceptionSQL - main SQL exception";
86  
87          // adding the input description to the main log statement;
88          if (!Util.isNull(desc)) {
89              excDesc += (" [" + desc + "]");
90          }
91  
92          SqlUtil.logCat.error(excDesc, e);
93  
94          while ((e = e.getNextException()) != null)
95              SqlUtil.logCat.error("::logSqlException - nested Exception ("
96                      + (i++) + ")", e);
97      }
98  
99      /***
100      * Log the SQLException stacktrace and do the same for all the nested
101      * exceptions.
102      * 
103      * @param e
104      *            the SQL exception to log
105      */
106     public static final void logSqlException(SQLException e) {
107         SqlUtil.logSqlException(e, null);
108     }
109 
110     /***
111      * Read the database field and write to the client its content
112      * 
113      * @param rs
114      *            Description of the Parameter
115      * @param fileName
116      *            is the filename or NULL in the classic (Fileholder-based) BLOB
117      *            handling
118      * @exception IOException
119      *                Description of the Exception
120      * @exception SQLException
121      *                Description of the Exception
122      */
123     public static FileHolder readFileHolderBlob(ResultSet rs)
124             throws IOException, SQLException {
125         logCat.info("READING FILEHOLDER");
126         Object o = rs.getObject(1);
127         if (o == null) {
128             logCat.warn("::readDbFieldBlob - blob null, no response sent");
129             return null;
130         }
131         logCat.info("o instanceof ..." + o.getClass().getName());
132         // if the object the JDBC driver returns to us implements
133         // the java.sql.Blob interface, then we use the BLOB object
134         // which wraps the binary stream of our FileHolder:
135         try {
136             if (o instanceof java.sql.Blob) {
137                 Blob blob = rs.getBlob(1);
138                 ObjectInputStream ois = new ObjectInputStream(blob
139                         .getBinaryStream());
140                 FileHolder fh = (FileHolder) ois.readObject();
141                 return fh;
142             }
143             // otherwise we are aquiring the stream directly:
144             else {
145                 // old ("classic") mode
146                 InputStream blobIS = rs.getBinaryStream(1);
147                 ObjectInputStream ois = new ObjectInputStream(blobIS);
148                 FileHolder fh = (FileHolder) ois.readObject();
149                 return fh;
150             }
151         } catch (ClassNotFoundException cnfe) {
152             logCat.error("::readDbFieldBlob - class not found", cnfe);
153             throw new IOException("error:" + cnfe.toString());
154         }
155 
156     }
157 
158     /***
159      * Read the database field and write to the client its content
160      * 
161      * @param rs
162      *            Description of the Parameter
163      * @param fileName
164      *            is the filename or NULL in the classic (Fileholder-based) BLOB
165      *            handling
166      * @exception IOException
167      *                Description of the Exception
168      * @exception SQLException
169      *                Description of the Exception
170      */
171     public static InputStream readDbFieldBlob(ResultSet rs) throws IOException,
172             SQLException {
173         logCat.info("READING BLOB");
174         Object o = rs.getObject(1);
175         if (o == null) {
176             logCat.warn("::readDbFieldBlob - blob null, no response sent");
177             return null;
178         }
179         logCat.info("o instanceof ..." + o.getClass().getName());
180         // if the object the JDBC driver returns to us implements
181         // the java.sql.Blob interface, then we use the BLOB object
182         // which wraps the binary stream of our FileHolder:
183         if (o instanceof java.sql.Blob) {
184             return ((Blob) o).getBinaryStream();
185         }
186         // otherwise we are aquiring the stream directly:
187         else {
188             // new mode
189             return rs.getBinaryStream(1);
190         }
191     }
192 
193     /***
194      * Read the blob field from the filesystem and write to the client its
195      * content.
196      * 
197      * @param fileName
198      *            Description of the Parameter
199      * @param directory
200      *            Description of the Parameter
201      * @param defVal
202      *            Default value of the file tag
203      * @exception FileNotFoundException
204      *                Description of the Exception
205      * @exception IOException
206      *                Description of the Exception
207      */
208     public static FileInputStream readDiskBlob(String fileName,
209             String directory, String defVal) throws FileNotFoundException,
210             IOException {
211         logCat.info(new StringBuffer("READING DISKBLOB\n  directory = [")
212                 .append(directory).append("]\n").append("  fileName = [")
213                 .append(fileName).append("]\n").append("  defaultValue = [")
214                 .append(defVal).append("]\n").toString());
215 
216         if (Util.isNull(fileName)) {
217             if ((fileName = defVal) != null) {
218                 logCat
219                         .info("::readDiskBlob - database data is null; use the default value ["
220                                 + fileName + "]");
221                	fileName = fileName.replace('/', File.separatorChar);
222                	fileName = fileName.replace('//', File.separatorChar);
223                 String s = FileUtil.dirname(fileName);
224                 if (!Util.isNull(s)) {
225                 	directory = s;
226                 	fileName = FileUtil.removePath(fileName);
227                 }
228             }
229         }
230 
231         // directory or fileName can be null!
232         //if ((directory != null) && (fileName != null))
233         if (fileName != null) {
234             fileName = fileName.trim();
235             File file = new File(directory, fileName);
236             if (file.exists()) {
237                 logCat.info("::readDiskBlob - file found ["
238                         + file.getAbsoluteFile() + "]");
239                 return new FileInputStream(file);
240             } else {
241                 logCat.error("::readDiskBlob - file ["
242                         + (directory + "/" + fileName) + "] not found");
243 
244                 return null;
245             }
246         } else {
247             logCat
248                     .warn("::readDiskBlob - file name or directory value is null");
249 
250             return null;
251         }
252     }
253 }