KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > dataset > provider > sql > JDBCDataConnection


1 /*
2  * $Id: JDBCDataConnection.java,v 1.2 2005/02/28 18:27:45 rbair Exp $
3  *
4  * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
5  * Santa Clara, California 95054, U.S.A. All rights reserved.
6  */

7
8 package org.jdesktop.dataset.provider.sql;
9 import java.sql.Connection JavaDoc;
10 import java.sql.DriverManager JavaDoc;
11 import java.sql.PreparedStatement JavaDoc;
12 import java.sql.ResultSet JavaDoc;
13 import java.util.Properties JavaDoc;
14 import javax.naming.InitialContext JavaDoc;
15 import org.jdesktop.dataset.DataConnection;
16
17 /**
18  * An implementation of the DataConnection for interacting with
19  * a local database. This implementation is "local", meaning that it is
20  * written and optimized for low latency database access, such as for an in
21  * memory database, or one on a local network.
22  * <p/>
23  * @author rbair
24  */

25 public class JDBCDataConnection extends DataConnection {
26     /**
27      * The connection to the database
28      */

29     private Connection JavaDoc conn;
30     /**
31      * This is a mutex used to control access to the conn object.
32      * Note that I create a new String object explicitly. This is done
33      * so that a single mutex is unique for each JDBCDataConnection
34      * instance.
35      */

36     private final Object JavaDoc connMutex = new String JavaDoc("Connection_Mutex");
37     /**
38      * If used, defines the JNDI context from which to get a connection to
39      * the data base
40      */

41     private String JavaDoc jndiContext;
42     /**
43      * When using the DriverManager to connect to the database, this specifies
44      * the URL to use to make that connection. URL's are specific to the
45      * JDBC vendor.
46      */

47     private String JavaDoc url;
48     /**
49      * When using the DriverManager to connect to the database, this specifies
50      * the user name to log in with.
51      */

52     private String JavaDoc userName;
53     /**
54      * When using the DriverManager to connect to the database, this specifies
55      * the password to log in with.
56      */

57     private String JavaDoc password;
58     /**
59      * When using the DriverManager to connect to the database, this specifies
60      * any additional properties to use when connecting.
61      */

62     private Properties JavaDoc properties;
63     
64     /**
65      * Create a new DatabaseDataStoreConnection. Be sure to set the JDBC connection
66      * properties (user name, password, connection method, etc)
67      * prior to connecting this object.
68      */

69     public JDBCDataConnection() {
70     }
71     
72     
73     /**
74      * Create a new JDBCDataConnection and initializes it to connect to a
75      * database using the given params.
76      * @param driver
77      * @param url
78      * @param user
79      * @param passwd
80      */

81     public JDBCDataConnection(String JavaDoc driver, String JavaDoc url, String JavaDoc user,
82             String JavaDoc passwd) {
83         try {
84             Class.forName(driver);
85         } catch (Exception JavaDoc e) {
86             System.err.println("WARN: The driver passed to the " +
87                     "JDBCDataConnection constructor could not be loaded. " +
88                     "This may be due to the driver not being on the classpath");
89             e.printStackTrace();
90         }
91         this.setUrl(url);
92         this.setUserName(user);
93         this.setPassword(passwd);
94     }
95     
96     /**
97      * Create a new JDBCDataConnection and initializes it to connect to a
98      * database using the given params.
99      * @param driver
100      * @param url
101      * @param props
102      */

103     public JDBCDataConnection(String JavaDoc driver, String JavaDoc url, Properties JavaDoc props) {
104         try {
105             Class.forName(driver);
106         } catch (Exception JavaDoc e) {
107             System.err.println("WARN: The driver passed to the " +
108                     "JDBCDataConnection constructor could not be loaded. " +
109                     "This may be due to the driver not being on the classpath");
110             e.printStackTrace();
111         }
112         this.setUrl(url);
113         this.setProperties(props);
114     }
115     
116     /**
117      * Create a new JDBCDataConnection and initializes it to connect to a
118      * database using the given params.
119      * @param jndiContext
120      * @param user
121      * @param passwd
122      */

123     public JDBCDataConnection(String JavaDoc jndiContext, String JavaDoc user, String JavaDoc passwd) {
124         this.jndiContext = jndiContext;
125         this.setUserName(user);
126         this.setPassword(passwd);
127     }
128     
129     
130     /**
131      * @return the JDBC connection url
132      */

133     public String JavaDoc getUrl() {
134         return url;
135     }
136
137     /**
138      * @param url set the JDBC connection url
139      */

140     public void setUrl(String JavaDoc url) {
141         this.url = url;
142     }
143
144     /**
145      * @return the user name used to connect to the database
146      */

147     public String JavaDoc getUserName() {
148         return userName;
149     }
150
151     /**
152      * @params userName used to connect to the database
153      */

154     public void setUserName(String JavaDoc userName) {
155         this.userName = userName;
156     }
157
158     /**
159      * @return the password used to connect to the database
160      */

161     public String JavaDoc getPassword() {
162         return password;
163     }
164
165     /**
166      * @param password the password used to connect to the database
167      */

168     public void setPassword(String JavaDoc password) {
169         this.password = password;
170     }
171
172     /**
173      * @return JDBC connection properties
174      */

175     public Properties JavaDoc getProperties() {
176         return properties;
177     }
178
179     /**
180      * @param properties miscellaneous JDBC properties to use when connecting
181      * to the database via the JDBC driver
182      */

183     public void setProperties(Properties JavaDoc properties) {
184         this.properties = properties;
185     }
186
187     /**
188      * Connect to the database. This method attempts to connect via jndiContext
189      * first, if possible. If not, then it tries to connect by using the
190      * DriverManager.
191      */

192     protected void connect() throws Exception JavaDoc {
193         //if the jndiContext is not null, then try to get the DataSource to use
194
//from jndi
195
if (jndiContext != null) {
196             try {
197                 connectByJNDI();
198             } catch (Exception JavaDoc e) {
199                 try {
200                     connectByDriverManager();
201                 } catch (Exception JavaDoc ex) {
202                     throw new Exception JavaDoc("Failed to connect to the database", e);
203                 }
204             }
205         } else {
206             try {
207                 connectByDriverManager();
208             } catch (Exception JavaDoc ex) {
209                 throw new Exception JavaDoc("Failed to connect to the database", ex);
210             }
211         }
212     }
213     
214     /**
215      * Attempts to get a JDBC Connection from a JNDI javax.sql.DataSource, using
216      * that connection for interacting with the database.
217      * @throws Exception
218      */

219     private void connectByJNDI() throws Exception JavaDoc {
220         InitialContext JavaDoc ctx = new InitialContext JavaDoc();
221         javax.sql.DataSource JavaDoc ds = (javax.sql.DataSource JavaDoc)ctx.lookup(jndiContext);
222         synchronized(connMutex) {
223             conn = ds.getConnection(getUserName(), getPassword());
224             conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
225         }
226     }
227     
228     /**
229      * Attempts to get a JDBC Connection from a DriverManager. If properties
230      * is not null, it tries to connect with those properties. If that fails,
231      * it then attempts to connect with a user name and password. If that fails,
232      * it attempts to connect without any credentials at all.
233      * <p>
234      * If, on the other hand, properties is null, it first attempts to connect
235      * with a username and password. Failing that, it tries to connect without
236      * any credentials at all.
237      * @throws Exception
238      */

239     private void connectByDriverManager() throws Exception JavaDoc {
240         synchronized(connMutex) {
241             if (getProperties() != null) {
242                 try {
243                     conn = DriverManager.getConnection(getUrl(), getProperties());
244                     conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
245                 } catch (Exception JavaDoc e) {
246                     try {
247                         conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
248                         conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
249                     } catch (Exception JavaDoc ex) {
250                         conn = DriverManager.getConnection(getUrl());
251                         conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
252                     }
253                 }
254             } else {
255                 try {
256                     conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
257                     
258                 } catch (Exception JavaDoc e) {
259                     e.printStackTrace();
260                     //try to connect without using the userName and password
261
conn = DriverManager.getConnection(getUrl());
262                     
263                 }
264                 
265 // try {
266
// conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
267
// } catch (SQLException e) {
268
// //never mind, this DB does not support transaction isolation
269
// }
270
}
271         }
272     }
273     
274     /**
275      * Disconnects from the database and causes all of the attached DataModels
276      * to flush their contents.
277      */

278     protected void disconnect() throws Exception JavaDoc {
279         synchronized(connMutex) {
280             if (conn != null) {
281                 conn.close();
282             }
283         }
284     }
285     
286     public ResultSet JavaDoc executeQuery(PreparedStatement JavaDoc ps) {
287         synchronized(connMutex) {
288             if (conn != null) {
289                 try {
290                     return ps.executeQuery();
291                 } catch (Exception JavaDoc e) {
292                     e.printStackTrace();
293                 }
294             }
295         }
296         return null;
297     }
298
299     public int executeUpdate(PreparedStatement JavaDoc ps) {
300         synchronized(connMutex) {
301             if (conn != null) {
302                 try {
303                     return ps.executeUpdate();
304                 } catch (Exception JavaDoc e) {
305                     e.printStackTrace();
306                 }
307             }
308         }
309         return 0;
310     }
311     
312     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql) throws Exception JavaDoc {
313         synchronized(connMutex) {
314             if (conn != null) {
315                 return conn.prepareStatement(sql);
316             }
317         }
318         return null;
319     }
320 }
321
Popular Tags