Main Page   Namespace List   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members  

DbTool.java

Go to the documentation of this file.
00001 package net.threebit.utils.sosc;
00002 
00003 /*
00004         Copyright 2003 Shawn Deleurme
00005         Copyright 2003 Kevin O'Donnell
00006 
00007         This program is free software; you can redistribute it and/or modify
00008         it under the terms of the GNU General Public License as published by
00009         the Free Software Foundation; either version 2 of the License, or
00010         (at your option) any later version.
00011 
00012         This program is distributed in the hope that it will be useful,
00013         but WITHOUT ANY WARRANTY; without even the implied warranty of
00014         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015         GNU General Public License for more details.
00016 
00017         You should have received a copy of the GNU General Public License
00018         along with this program; if not, write to the Free Software
00019         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00020 */
00021 
00022 import java.io.*;
00023 import java.sql.*;
00024 import java.util.*;
00025 
00029 public class DbTool {
00030 
00031         protected Connection connection;
00032         private String className;
00033         private String url;
00034         private String userName;
00035         private String password;
00036         private boolean connectionIsPrivate = true;
00037 
00041         public DbTool (String className, String url, String userName, String password) throws Exception {
00042                 setConnection(className, url, userName, password);
00043         }
00044 
00048         public DbTool (Connection connection) throws Exception {
00049                 setConnection(connection);
00050         }
00051 
00055         private void setConnection (Connection connection) throws SQLException {
00056                 if (this.connection != null) {
00057                         this.connection.close();
00058                 }
00059                 this.connection = connection;
00060         }
00061 
00065         private void setConnection (String className, String url, String userName, String password) throws Exception {
00066                 this.className = className;
00067                 this.url = url;
00068                 this.userName = userName;
00069                 this.password = password;
00070                 Class.forName(className);
00071                 setConnection(DriverManager.getConnection(url,userName,password));
00072         }
00073 
00077         public Connection getConnection() throws Exception {
00078                 // Once a connection has left the house, it isn't closed on finalization
00079                 connectionIsPrivate = false;
00080                 return connection;
00081         }
00082 
00086         public String getUserName() {
00087                 return userName;
00088         }
00089 
00090 
00091         public void close () throws Exception {
00092                 connection.close(); 
00093         }
00094 
00095         public void rollback () throws Exception {
00096                 connection.rollback(); 
00097         }
00098 
00099         public void commit () throws Exception {
00100                 connection.commit (); 
00101         }
00102 
00103         public void setAutoCommit( boolean autocommit ) throws Exception {
00104                 // connection.setTransactionIsolation( Connection.TRANSACTION_SERIALIZABLE );           
00105                 connection.setAutoCommit( autocommit ); 
00106         }
00114   public /*static*/ String q (Object o) {
00115                 if (o == null) { return "''"; }
00116                 String field = o.toString() ; 
00117     if (field.length() == 0) { return "''"; }
00118 
00119     if (field.indexOf('\'')>-1) {
00120       // a single quote was found, replace all single quotes with double single quotes.
00121       char[] origin= new char[field.length()];
00122       field.getChars(0,field.length(),origin,0);
00123       int numApostrophes=0;
00124       for (int f=0;f<origin.length; f++) {
00125         if (origin[f]=='\'') numApostrophes++;
00126       }
00127       char[] parsed= new char[numApostrophes+origin.length];
00128       int index=0;
00129       for (int f=0;f<origin.length; f++) {
00130         if (origin[f]=='\'') {
00131           parsed[index++]=origin[f];
00132         };
00133         parsed[index++]=origin[f];
00134       }
00135       field = new String(parsed);
00136     }
00137     return "'"+field+"'"; // no single quotes were found, just return string surrounded by single quotes
00138   }
00139 
00143         public String quote (String s) throws SQLException {
00144                 // special case.
00145                 if (s == null) return null;
00146 
00147                 // SQL quote it.
00148                 return "'" + s.replaceAll("'","''") + "'";
00149         }
00150 
00154         public String getString (String sql) throws Exception { return ""+getObject(sql); }
00155 
00159         public int getInt (String sql) throws Exception { return Integer.valueOf(getString(sql)).intValue(); }
00160 
00164         public double getDouble (String sql) throws Exception { return Double.valueOf(getString(sql)).doubleValue(); }
00165 
00169         public long getLong (String sql) throws Exception { return Long.valueOf(getString(sql)).longValue(); }
00170 
00174         public Object getObject (String sql) throws Exception {
00175                 ResultSet r = query(sql);
00176                 if (! r.first()) { 
00177                         r.getStatement().close();
00178                         throw new Exception("ResultSet does not contain at least 1 row.\n"+sql); 
00179                 }
00180                 Object o = r.getObject(1);
00181                 r.getStatement().close();
00182                 return o;
00183         }
00184 
00190         public ResultSet query (String sql) throws Exception {
00191                 if (connection == null) { throw new Exception("No connection has been set"); }
00192 
00193                 Statement statement = null;
00194                 try {
00195                         statement = connection.createStatement();
00196 
00197                         // We do not call executeQuery() because if we are calling a stored procedure
00198                         // and it updates rows internally, then executeUpdate() will throw an exception.
00199                         statement.execute(sql);
00200 
00201                         // Get the first result set; if it is null then continue into the result set search loop
00202                         ResultSet result = statement.getResultSet();
00203                         if (result != null) {
00204                                 return result;
00205                         }
00206 
00207                         // Go hunting for the first non-null result set.
00208                         while (statement.getMoreResults()) {
00209                                 result = statement.getResultSet();
00210                                 if (result != null) {
00211                                         return result;
00212                                 }
00213                         }
00214 
00215                         // Close then throw.
00216                         statement.close();
00217                         throw new Exception("A non-null result set could not be found.");
00218 
00219                 } catch (Exception e) {
00220                         throw new Exception("Error occured while executing sql:\n"+sql+"\n"+e.getMessage(),e);
00221                 }
00222         }
00223 
00227         public void update (String sql) throws Exception {
00228                 if (connection == null) { throw new Exception("No connection has been set"); }
00229                 Statement statement = null;
00230                 try {
00231                         statement = connection.createStatement();
00232                         statement.executeUpdate(sql);
00233                 }
00234                 catch (Exception e) {
00235                         throw new Exception("Error occured while executing sql:\n"+sql+"\n"+e.getMessage(),e);
00236                 }
00237                 finally {
00238                         try { if (statement != null) { statement.close(); } } catch (Exception e) { e.printStackTrace(); }
00239                 }
00240         }
00241 
00245         public Statement createStatement() throws Exception {
00246                 if (connection == null) { throw new Exception("No connection has been set"); }
00247                 return connection.createStatement();
00248         }
00249 
00257         public String inClause (Collection c, boolean quoted) throws Exception {
00258                 if (c == null || c.size() == 0) { return "(null)"; }
00259                 StringBuffer sb = new StringBuffer();
00260                 sb.append("(");
00261                 for (Iterator i = c.iterator(); i.hasNext(); ) {
00262                         Object item = i.next();
00263                         if (item == null) {
00264                                 sb.append("null");
00265                         }
00266                         else if (quoted) {
00267                                 sb.append(quote(item.toString()));
00268                         }
00269                         else {
00270                                 sb.append(item.toString());
00271                         }
00272                         sb.append(",");
00273                 }
00274                 sb.deleteCharAt( sb.length()-1 );
00275                 sb.append(")");
00276                 return sb.toString();
00277         }
00278 
00282         public int rowCount (ResultSet r) throws Exception {
00283                 int rowCount = 0;
00284                 r.beforeFirst();
00285                 while (r.next()) { rowCount++; }
00286                 r.beforeFirst();
00287                 return rowCount;
00288         }
00289 
00293         public static Map toMap (ResultSet r) throws Exception {
00294                 return toMap(r,true);
00295         }
00296 
00304         public static Map toMap (ResultSet r, boolean advance) throws Exception {
00305 
00306                 // Should we advance?
00307                 if (advance) { r.next(); }
00308 
00309                 // Return if we are not on a valid row
00310                 if (r.getRow() == 0) {
00311                         return new HashMap();
00312                 }
00313 
00314                 // Okay, now return the current row
00315 
00316                 Map map = new LinkedHashMap( 32 ); // Use LinkedHashMap to retain the result set column ordering.
00317                 ResultSetMetaData m = r.getMetaData();
00318                 int cc = m.getColumnCount();
00319                 for ( int i=1; i<=cc; i++ ){
00320                         map.put ( m.getColumnName(i) , r.getString(i) );
00321                 }
00322                 return map;
00323         }
00324 
00328         public List toList (ResultSet r) throws Exception {
00329                 List list = new ArrayList(32) ;
00330                 while (r.next()){
00331                         Map map = new HashMap( 32 );
00332                         ResultSetMetaData m = r.getMetaData();
00333                         int cc = m.getColumnCount();
00334                         for ( int i=1; i<=cc; i++ ){
00335                                 map.put (
00336                                         m.getColumnName(i)
00337                                 , r.getString(i) );
00338                         }
00339                         list.add(map);
00340                 }
00341                 return list;
00342         }
00343 
00345         // billing specific tools
00347 
00348         /*
00349          * These methods are meant to provide a single point of access to the db.
00350          * They will end up in a bean.
00351          * --
00352          * the pattern is as follows...
00353          */
00354 /*
00355         public Map addCustomer ( Map map ) throws Exception {
00356                 // this should be fixed to use an index in the future.
00357                 String sql = "SELECT * FROM customers WHERE tel = '"+map.get("custphone") + "';" ;
00358                 ResultSet r = query ( sql ) ;
00359                 if (r.next()){
00360                         // houston, we have a row. and, only one!
00361                         map.putAll ( toMap(r) );
00362                 }
00363                 else {
00365                         sql
00366                                 = "INSERT INTO customers "
00367                                 + "(firstname,lastname,tel,address,zip,city,province,country) "
00368                                 + "VALUES ('"
00369                                 +                               map.get("firstname")
00370                                 + "','" + map.get("lastname")
00371                                 + "','" + map.get("custphone")
00372                                 + "','" + map.get("custaddress1")
00373                                 + "','" + map.get("custzip")
00374                                 + "','" + map.get("custcity")
00375                                 + "','" + map.get("custstate")
00376                                 + "','US'"
00377                                 + "); SELECT MAX(id) FROM customers; ";
00378                         r = query (sql);
00379 //                      r = s.getResultSet();
00380                         r.first();
00381                         map.put ("customerid",new Integer(r.getInt(1)));
00382                 }
00383                 r.close();
00384                 return map;
00385         }
00386 */
00387 
00388 /*
00389         public int addAccount ( Map map ) throws Exception {
00390                 return 0;
00391         }
00392         public int addSale ( Map map ) throws Exception {}
00393         public int addPayment( Map map ) throws Exception {}
00394         public int fixCustomer ( Map map ) throws Exception {}
00395 */
00396 
00397 /*
00398 TODO: move this to a "BILLING" app specific file.
00399         public void selectHouses() throws Exception{
00400                 out.println ("<select name=house>") ;
00401                 ResultSet houses = query(
00402                         "select * FROM houses WHERE id >0;");
00403                 out.println ("<option value=-1>All</option>");
00404                 while (houses.next()){
00405                         out.print ("<option value=");
00406                         out.print (houses.getInt(1));
00407                         out.print (">");
00408                         out.print (houses.getString(2));
00409                         out.print ("</option>");
00410                 }
00411                 houses.close();
00412                 out.println("</select>");
00413         }
00414 
00415 TODO: move this to a "BILLING" app specific file.
00416         public void selectAgents() throws Exception{
00417                 out.println ("<select name=agent>") ;
00418                 ResultSet agents = query(
00419                         "select * FROM agents WHERE id >0;");
00420                 out.println ("<option value=-1>All</option>");
00421                 while (agents.next()){
00422                         out.print ("<option value=");
00423                         out.print (agents.getInt(1));
00424                         out.print (">");
00425                         out.print (agents.getString(2));
00426                         out.print ("</option>");
00427                 }
00428                 agents.close();
00429                 out.println("</select>");
00430         }
00431 
00432 TODO: move this to a "BILLING" app specific file.
00433         public void selectTypes() throws Exception{
00434                 out.println ("<select name=type>") ;
00435                 ResultSet types = query(
00436                 "select distinct authcode from transactiontest where authcode not like 'CheckAuth%';");
00437                 out.println ("<option value=-1>All</option>");
00438                 out.println ("<option value='CheckAuth%'>Preauth</option>");
00439                 while (types.next()){
00440                         out.print ("<option value='");
00441                         out.print (types.getString(1));
00442                         out.print ("'>");
00443                         out.print (types.getString(1));
00444                         out.print ("</option>");
00445                 }
00446                 types.close();
00447                 out.println("</select>");
00448         }
00449 */
00450 
00451         public StringBuffer resultSetToXML (ResultSet r) throws Exception {
00452                 return resultSetToXML(r,new StringBuffer(), Integer.MAX_VALUE);
00453         }
00454         
00458         public StringBuffer resultSetToXML (ResultSet r, StringBuffer sb, int count) throws Exception {
00459 
00460                 String emptyString = "";
00461 
00462                 if (r == null) { throw new Exception("No ResultSet provided."); }
00463                 if (sb == null) { throw new Exception("No StringBuffer provided."); }
00464                 if (count < 0) { throw new Exception("Count must be positive (" + count + ")"); }
00465 
00466                 int columnCount = r.getMetaData().getColumnCount();
00467                 String[] columnNames = new String[ columnCount ];
00468                 for (int i=1; i <= columnCount; i++) { 
00469                         columnNames[i-1] = r.getMetaData().getColumnName(i); 
00470                 }
00471 
00472                 sb.append("<resultSet>\n");
00473                 for (int x = 0; x < count && r.next(); x++) {
00474                         sb.append("<row>\n");
00475                         // This is the source of a 
00476                         for (int i=1; i <= columnCount; i++) {
00477                                 Object value = r.getObject(i);
00478                                 if (value == null) { value = emptyString; }
00479                                 sb.append("\t<"); sb.append(columnNames[i-1]); sb.append(">");
00480                                 sb.append( (""+r.getObject(i)).replaceAll("&","&amp;" )); // TODO: alot more XML convertions!
00481                                 sb.append("</"); sb.append(columnNames[i-1]); sb.append(">\n");
00482                         }
00483                         sb.append("</row>\n");
00484                 }
00485                 sb.append("</resultSet>\n");
00486                 return sb;
00487         }
00488 
00489         public void finalize () {
00490                 if (connection != null && connectionIsPrivate) {
00491                         try { connection.close(); }
00492                         catch (Exception e) {
00493                                 System.out.println("Error while closing connection during finalization");
00494                                 e.printStackTrace();
00495                         }
00496                 }
00497         }
00498 }

Generated on Mon Jul 14 17:19:20 2003 for SOSC by doxygen1.2.15