KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > testbed > workbench > jdbc > Database


1 package org.enhydra.barracuda.testbed.workbench.jdbc;
2
3 import java.awt.*;
4 import java.sql.*;
5 import java.util.*;
6
7 /**
8  * Database - this is really a legacy class; we should be using JDBC 2.0 and getting
9  * a DataSource, but for now we'll leave it like it is, since after all it already
10  * works ;-)
11  *
12  * @author Christian Cryder (csc)
13  * @version 1.0
14  */

15 public class Database {
16
17     private Connection conn = null;
18     private String JavaDoc jdbcDriverName = "";
19     private String JavaDoc jdbcServerURL = "";
20     private String JavaDoc dbUserName = "";
21     private String JavaDoc dbPassword = "";
22     private Properties props = new Properties();
23     private Driver theJDBCDriver = null;
24     private DriverManager dmanager = null;
25     private int commitLevel = -1;
26     private String JavaDoc userName = "";
27
28     /**
29      * The public contructor for Database
30      *
31      * @param ijdbcDriverName Jdbc Driver Name
32      * @param ijdbcServerURL Jdbc Server URL
33      * @param idbUserName Database User Name
34      * @param idbPassword Database password
35      */

36     public Database (String JavaDoc ijdbcDriverName, String JavaDoc ijdbcServerURL, String JavaDoc idbUserName, String JavaDoc idbPassword) {
37         jdbcDriverName = ijdbcDriverName;
38         jdbcServerURL = ijdbcServerURL;
39         dbUserName = idbUserName;
40         dbPassword = idbPassword;
41     }
42
43     /**
44      * connectServer
45      *
46      * @exception PropertyVetoException
47      */

48     public void connectServer() throws java.beans.PropertyVetoException JavaDoc {
49         // set the timeout so that the server closes if fail to connect
50
dmanager.setLoginTimeout(20);
51
52         //Make the connection to the database
53
try {
54             // create a specific driver for use with JDBC
55
theJDBCDriver = (Driver)Class.forName(jdbcDriverName).newInstance();
56
57             // connect to the database using the JDBC driver
58
props.put("user",dbUserName);
59             props.put("password",dbPassword);
60             conn = makeConnection(theJDBCDriver, jdbcServerURL, props);
61             setAutoCommit(true);
62         } catch (SQLException se) {
63             String JavaDoc message = null;
64             message = se.toString();
65             throw new java.beans.PropertyVetoException JavaDoc("Error Connecting to Database: "+message,null);
66         } catch (Exception JavaDoc e) {
67             throw new java.beans.PropertyVetoException JavaDoc("Error Connecting to Database: "+e,null);
68         }
69     }
70
71     /**
72      * makeConnection
73      *
74      * @param ijdbcDriverName Jdbc Driver Name
75      * @param ijdbcServerURL Jdbc Server URL
76      * @param props Properties
77      * @return Connection
78      * @exception SQLException
79      */

80     private static synchronized Connection makeConnection (Driver theJDBCDriver, String JavaDoc jdbcServerURL, Properties props) throws SQLException {
81         return theJDBCDriver.connect(jdbcServerURL, props);
82     }
83
84     /**
85      * disconnectServer
86      *
87      * @exception PropertyVetoException
88      */

89     public void disconnectServer() throws java.beans.PropertyVetoException JavaDoc {
90         //close the connection. If we do get an error, things are really hosed, so
91
//set the conn = null
92
try {
93             if (conn!=null) conn.close();
94         } catch (Exception JavaDoc e) {
95             throw new java.beans.PropertyVetoException JavaDoc("Error Disconnecting from Database:"+e,null);
96         } finally {
97             conn = null;
98         }
99     }
100
101     /**
102      * disconnectServer
103      *
104      * @return True if still connect to the database
105      */

106     public boolean isConnected() {
107         return conn!=null;
108     }
109
110     /**
111      * disconnectServer
112      *
113      * @param s String to be set in the prepare statement
114      * @return PreparedStatement
115      * @exception SQLException
116      */

117     public PreparedStatement prepareStatement(String JavaDoc s) throws SQLException {
118         for (;;) {
119             try {
120                 //if the connection has dropped for some reason, restablish
121
//we will continue doing this until the connection is established
122
while (!isConnected()) {
123                     try {
124                         connectServer();
125                     } catch (java.beans.PropertyVetoException JavaDoc pve) {
126                         System.out.println ("Server not responding...");
127                         try {Thread.sleep(200);}
128                         catch (InterruptedException JavaDoc ie) {}
129                     } finally {
130                         if (isConnected()) System.out.println ("Connection reestablished...");
131                     }
132                 }
133
134                 //return the connection
135
return conn.prepareStatement(s);
136             } catch (SQLException se) {
137                 String JavaDoc err = se.getSQLState();
138                 //see if we're having trouble talking to the server, and if so, disconnect.
139
//This will cause the server to automatically reconnect on the next pass through
140
//the loop
141
if (err.equals("08S01")) {
142                     try {disconnectServer();}
143                     catch (java.beans.PropertyVetoException JavaDoc pve) {}
144                 } else {
145                     throw se;
146                 }
147             }
148         }
149     }
150
151     /**
152      * createStatement
153      *
154      * @return Statement
155      * @exception SQLException
156      */

157     public Statement createStatement() throws SQLException {
158         for (;;) {
159             try {
160                 //if the connection has dropped for some reason, restablish
161
//we will continue doing this until the connection is established
162
while (!isConnected()) {
163                     try {connectServer();}
164                     catch (java.beans.PropertyVetoException JavaDoc pve) {
165                         System.out.println ("Server not responding...");
166                         try {Thread.sleep(200);}
167                         catch (InterruptedException JavaDoc ie) {}
168                     } finally {
169                         if (isConnected()) System.out.println ("Connection reestablished...");
170                     }
171                 }
172
173                 //return the connection
174
return conn.createStatement();
175             } catch (SQLException se) {
176                 String JavaDoc err = se.getSQLState();
177                 //see if we're having trouble talking to the server, and if so, disconnect.
178
//This will cause the server to automatically reconnect on the next pass through
179
//the loop
180
if (err.equals("08S01")) {
181                     try {disconnectServer();}
182                     catch (java.beans.PropertyVetoException JavaDoc pve) {}
183                 } else {
184                     throw se;
185                 }
186             }
187         }
188     }
189
190     /**
191      * getConnection
192      *
193      * @return Connection
194      * @exception PropertyVetoException
195      */

196     public Connection getConnection() throws java.beans.PropertyVetoException JavaDoc {
197         return getConnection(false);
198     }
199
200     /**
201      * getConnection
202      *
203      * @param verify Verify
204      * @return Connection
205      * @exception PropertyVetoException
206      */

207     public Connection getConnection(boolean verify) throws java.beans.PropertyVetoException JavaDoc {
208         //only verify the connection if specifically asked to do so (this will renegotiate the
209
//connection if necessary)
210
if (verify) {
211             try {verifyConnection();}
212             catch (SQLException se) {throw new java.beans.PropertyVetoException JavaDoc("Error getting the Connection to Database:"+se,null);}
213         }
214
215         //return the connection
216
return conn;
217     }
218
219     /**
220      * setConnection
221      *
222      * @param c Connection to be set
223      * @see Connection
224      */

225     public void setConnection (Connection c) {
226         conn = c;
227     }
228
229     /**
230      * verifyConnection
231      *
232      * @exception SQLException
233      */

234     public void verifyConnection() throws SQLException {
235         verifyConnection("select count(*) from metadata"); //we really ought to try and come up with a generic chunk of SQL here...something that's not specific to either database or tables
236
}
237     
238     public void verifyConnection(String JavaDoc s) throws SQLException {
239         this.prepareStatement(s).close();
240     }
241
242     /**
243      * resetConnection
244      */

245     public void resetConnection() {
246         conn = null;
247     }
248
249     /**
250      * commit
251      *
252      * @exception SQLException
253      */

254     public void commit() throws SQLException {
255         int cl = getCommitLevel();
256            if (cl>0) return;
257
258            if (!getAutoCommit()) {
259                conn.commit();
260                resetCommitLevel(); //just to make sure
261
}
262     }
263
264     /**
265      * rollback
266      *
267      * @exception SQLException
268      */

269     public void rollback() throws SQLException {
270         int cl = getCommitLevel();
271            if (cl>0) return;
272
273            if (!getAutoCommit()) {
274                conn.rollback();
275                resetCommitLevel(); //just to make sure
276
}
277     }
278
279     /**
280      * resetCommitLevel
281      */

282     public void resetCommitLevel() {
283         //This is kind of a safety valve...reset it just to make sure
284
commitLevel = -1;
285     }
286
287     /**
288      * getCommitLevel
289      */

290     public int getCommitLevel() {
291         //return the current commitLevel
292
return commitLevel;
293     }
294
295     /**
296      * setAutoCommit
297      *
298      * @param val True if commited
299      */

300     public void setAutoCommit(boolean val) {
301         //if the level is < 0, we know we're at the base...set the value
302
if (commitLevel<0) {
303             try {conn.setAutoCommit(val);}
304             catch (SQLException se) {
305                 System.out.println ("Error setting AutoCommit...");
306                 Throwable JavaDoc th = new Throwable JavaDoc();
307                 th.printStackTrace();
308             }
309         }
310         
311         //incr our commitLevel...this is to handle nested data objects. If
312
//UserData contains a UserAccessDataSet object, and each of these
313
//has rollback and commit potential, we need to be careful when we
314
//actually do the deed. If UserAccessDataSet exists all on its own
315
//and we hit an error, the rollback is appropriate immediately.
316
//If however, the UserAccessDataSet exists in the context of a UserData
317
//object, we need to defer on the rollback, pass the SQLException back
318
//on up and let the UserData object handle the rollback.
319
if (val==false) commitLevel++; //turning it off
320
else if (commitLevel>-1) commitLevel--; //turning it back on
321
}
322
323     /**
324      * getAutoCommit
325      *
326      * @return True if commited
327      */

328     public boolean getAutoCommit() {
329         try {return conn.getAutoCommit();}
330         catch (SQLException se) {
331             System.out.println ("Error getting AutoCommit...");
332             Throwable JavaDoc th = new Throwable JavaDoc();
333             th.printStackTrace();
334         }
335         return false;
336     }
337
338
339     /**
340      * getUserName
341      *
342      * @return User name
343      */

344     public String JavaDoc getUserName() {
345         return userName;
346     }
347
348     /**
349      * setUserName
350      *
351      * @param s User name to be set
352      */

353     public void setUserName(String JavaDoc s) {
354         userName = s;
355     }
356 }
357
Popular Tags